id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_bad_538_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /** @defgroup PI PI - Implementation of a packet iterator */ /*@{*/ /** @name Local static functions */ /*@{*/ /** Get next packet in layer-resolution-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-layer-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-precinct-component-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi); /** Get next packet in precinct-component-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi); /** Get next packet in component-precinct-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_cprl(opj_pi_iterator_t * pi); /*@}*/ /*@}*/ /* ========================================================== local functions ========================================================== */ static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { goto LABEL_SKIP; } else { int compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { int compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static opj_bool pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } /* ========================================================== Packet iterator interface ========================================================== */ opj_pi_iterator_t *pi_create_decode(opj_image_t *image, opj_cp_t *cp, int tileno) { int p, q; int compno, resno, pino; opj_pi_iterator_t *pi = NULL; opj_tcp_t *tcp = NULL; opj_tccp_t *tccp = NULL; tcp = &cp->tcps[tileno]; pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1), sizeof(opj_pi_iterator_t)); if (!pi) { /* TODO: throw an error */ return NULL; } for (pino = 0; pino < tcp->numpocs + 1; pino++) { /* change */ int maxres = 0; int maxprec = 0; p = tileno % cp->tw; q = tileno / cp->tw; pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0); pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0); pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1); pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1); pi[pino].numcomps = image->numcomps; pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (!pi[pino].comps) { /* TODO: throw an error */ pi_destroy(pi, cp, tileno); return NULL; } for (compno = 0; compno < pi->numcomps; compno++) { int tcx0, tcy0, tcx1, tcy1; opj_pi_comp_t *comp = &pi[pino].comps[compno]; tccp = &tcp->tccps[compno]; comp->dx = image->comps[compno].dx; comp->dy = image->comps[compno].dy; comp->numresolutions = tccp->numresolutions; comp->resolutions = (opj_pi_resolution_t*) opj_calloc(comp->numresolutions, sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { /* TODO: throw an error */ pi_destroy(pi, cp, tileno); return NULL; } tcx0 = int_ceildiv(pi->tx0, comp->dx); tcy0 = int_ceildiv(pi->ty0, comp->dy); tcx1 = int_ceildiv(pi->tx1, comp->dx); tcy1 = int_ceildiv(pi->ty1, comp->dy); if (comp->numresolutions > maxres) { maxres = comp->numresolutions; } for (resno = 0; resno < comp->numresolutions; resno++) { int levelno; int rx0, ry0, rx1, ry1; int px0, py0, px1, py1; opj_pi_resolution_t *res = &comp->resolutions[resno]; if (tccp->csty & J2K_CCP_CSTY_PRT) { res->pdx = tccp->prcw[resno]; res->pdy = tccp->prch[resno]; } else { res->pdx = 15; res->pdy = 15; } levelno = comp->numresolutions - 1 - resno; rx0 = int_ceildivpow2(tcx0, levelno); ry0 = int_ceildivpow2(tcy0, levelno); rx1 = int_ceildivpow2(tcx1, levelno); ry1 = int_ceildivpow2(tcy1, levelno); px0 = int_floordivpow2(rx0, res->pdx) << res->pdx; py0 = int_floordivpow2(ry0, res->pdy) << res->pdy; px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx; py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy; res->pw = (rx0 == rx1) ? 0 : ((px1 - px0) >> res->pdx); res->ph = (ry0 == ry1) ? 0 : ((py1 - py0) >> res->pdy); if (res->pw * res->ph > maxprec) { maxprec = res->pw * res->ph; } } } tccp = &tcp->tccps[0]; pi[pino].step_p = 1; pi[pino].step_c = maxprec * pi[pino].step_p; pi[pino].step_r = image->numcomps * pi[pino].step_c; pi[pino].step_l = maxres * pi[pino].step_r; if (pino == 0) { pi[pino].include = (short int*) opj_calloc(image->numcomps * maxres * tcp->numlayers * maxprec, sizeof(short int)); if (!pi[pino].include) { /* TODO: throw an error */ pi_destroy(pi, cp, tileno); return NULL; } } else { pi[pino].include = pi[pino - 1].include; } if (tcp->POC == 0) { pi[pino].first = 1; pi[pino].poc.resno0 = 0; pi[pino].poc.compno0 = 0; pi[pino].poc.layno1 = tcp->numlayers; pi[pino].poc.resno1 = maxres; pi[pino].poc.compno1 = image->numcomps; pi[pino].poc.prg = tcp->prg; } else { pi[pino].first = 1; pi[pino].poc.resno0 = tcp->pocs[pino].resno0; pi[pino].poc.compno0 = tcp->pocs[pino].compno0; pi[pino].poc.layno1 = tcp->pocs[pino].layno1; pi[pino].poc.resno1 = tcp->pocs[pino].resno1; pi[pino].poc.compno1 = tcp->pocs[pino].compno1; pi[pino].poc.prg = tcp->pocs[pino].prg; } pi[pino].poc.layno0 = 0; pi[pino].poc.precno0 = 0; pi[pino].poc.precno1 = maxprec; } return pi; } opj_pi_iterator_t *pi_initialise_encode(opj_image_t *image, opj_cp_t *cp, int tileno, J2K_T2_MODE t2_mode) { int p, q, pino; int compno, resno; int maxres = 0; int maxprec = 0; opj_pi_iterator_t *pi = NULL; opj_tcp_t *tcp = NULL; opj_tccp_t *tccp = NULL; tcp = &cp->tcps[tileno]; pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1), sizeof(opj_pi_iterator_t)); if (!pi) { return NULL; } pi->tp_on = cp->tp_on; for (pino = 0; pino < tcp->numpocs + 1 ; pino ++) { p = tileno % cp->tw; q = tileno / cp->tw; pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0); pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0); pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1); pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1); pi[pino].numcomps = image->numcomps; pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (!pi[pino].comps) { pi_destroy(pi, cp, tileno); return NULL; } for (compno = 0; compno < pi[pino].numcomps; compno++) { int tcx0, tcy0, tcx1, tcy1; opj_pi_comp_t *comp = &pi[pino].comps[compno]; tccp = &tcp->tccps[compno]; comp->dx = image->comps[compno].dx; comp->dy = image->comps[compno].dy; comp->numresolutions = tccp->numresolutions; comp->resolutions = (opj_pi_resolution_t*) opj_malloc(comp->numresolutions * sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { pi_destroy(pi, cp, tileno); return NULL; } tcx0 = int_ceildiv(pi[pino].tx0, comp->dx); tcy0 = int_ceildiv(pi[pino].ty0, comp->dy); tcx1 = int_ceildiv(pi[pino].tx1, comp->dx); tcy1 = int_ceildiv(pi[pino].ty1, comp->dy); if (comp->numresolutions > maxres) { maxres = comp->numresolutions; } for (resno = 0; resno < comp->numresolutions; resno++) { int levelno; int rx0, ry0, rx1, ry1; int px0, py0, px1, py1; opj_pi_resolution_t *res = &comp->resolutions[resno]; if (tccp->csty & J2K_CCP_CSTY_PRT) { res->pdx = tccp->prcw[resno]; res->pdy = tccp->prch[resno]; } else { res->pdx = 15; res->pdy = 15; } levelno = comp->numresolutions - 1 - resno; rx0 = int_ceildivpow2(tcx0, levelno); ry0 = int_ceildivpow2(tcy0, levelno); rx1 = int_ceildivpow2(tcx1, levelno); ry1 = int_ceildivpow2(tcy1, levelno); px0 = int_floordivpow2(rx0, res->pdx) << res->pdx; py0 = int_floordivpow2(ry0, res->pdy) << res->pdy; px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx; py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy; res->pw = (rx0 == rx1) ? 0 : ((px1 - px0) >> res->pdx); res->ph = (ry0 == ry1) ? 0 : ((py1 - py0) >> res->pdy); if (res->pw * res->ph > maxprec) { maxprec = res->pw * res->ph; } } } tccp = &tcp->tccps[0]; pi[pino].step_p = 1; pi[pino].step_c = maxprec * pi[pino].step_p; pi[pino].step_r = image->numcomps * pi[pino].step_c; pi[pino].step_l = maxres * pi[pino].step_r; for (compno = 0; compno < pi->numcomps; compno++) { opj_pi_comp_t *comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; opj_pi_resolution_t *res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi[pino].dx = !pi->dx ? dx : int_min(pi->dx, dx); pi[pino].dy = !pi->dy ? dy : int_min(pi->dy, dy); } } if (pino == 0) { pi[pino].include = (short int*) opj_calloc(tcp->numlayers * pi[pino].step_l, sizeof(short int)); if (!pi[pino].include) { pi_destroy(pi, cp, tileno); return NULL; } } else { pi[pino].include = pi[pino - 1].include; } /* Generation of boundaries for each prog flag*/ if (tcp->POC && (cp->cinema || ((!cp->cinema) && (t2_mode == FINAL_PASS)))) { tcp->pocs[pino].compS = tcp->pocs[pino].compno0; tcp->pocs[pino].compE = tcp->pocs[pino].compno1; tcp->pocs[pino].resS = tcp->pocs[pino].resno0; tcp->pocs[pino].resE = tcp->pocs[pino].resno1; tcp->pocs[pino].layE = tcp->pocs[pino].layno1; tcp->pocs[pino].prg = tcp->pocs[pino].prg1; if (pino > 0) { tcp->pocs[pino].layS = (tcp->pocs[pino].layE > tcp->pocs[pino - 1].layE) ? tcp->pocs[pino - 1].layE : 0; } } else { tcp->pocs[pino].compS = 0; tcp->pocs[pino].compE = image->numcomps; tcp->pocs[pino].resS = 0; tcp->pocs[pino].resE = maxres; tcp->pocs[pino].layS = 0; tcp->pocs[pino].layE = tcp->numlayers; tcp->pocs[pino].prg = tcp->prg; } tcp->pocs[pino].prcS = 0; tcp->pocs[pino].prcE = maxprec;; tcp->pocs[pino].txS = pi[pino].tx0; tcp->pocs[pino].txE = pi[pino].tx1; tcp->pocs[pino].tyS = pi[pino].ty0; tcp->pocs[pino].tyE = pi[pino].ty1; tcp->pocs[pino].dx = pi[pino].dx; tcp->pocs[pino].dy = pi[pino].dy; } return pi; } void pi_destroy(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno) { int compno, pino; opj_tcp_t *tcp = &cp->tcps[tileno]; if (pi) { for (pino = 0; pino < tcp->numpocs + 1; pino++) { if (pi[pino].comps) { for (compno = 0; compno < pi->numcomps; compno++) { opj_pi_comp_t *comp = &pi[pino].comps[compno]; if (comp->resolutions) { opj_free(comp->resolutions); } } opj_free(pi[pino].comps); } } if (pi->include) { opj_free(pi->include); } opj_free(pi); } } opj_bool pi_next(opj_pi_iterator_t * pi) { switch (pi->poc.prg) { case LRCP: return pi_next_lrcp(pi); case RLCP: return pi_next_rlcp(pi); case RPCL: return pi_next_rpcl(pi); case PCRL: return pi_next_pcrl(pi); case CPRL: return pi_next_cprl(pi); case PROG_UNKNOWN: return OPJ_FALSE; } return OPJ_FALSE; } opj_bool pi_create_encode(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno, int pino, int tpnum, int tppos, J2K_T2_MODE t2_mode, int cur_totnum_tp) { char prog[4]; int i; int incr_top = 1, resetX = 0; opj_tcp_t *tcps = &cp->tcps[tileno]; opj_poc_t *tcp = &tcps->pocs[pino]; pi[pino].first = 1; pi[pino].poc.prg = tcp->prg; switch (tcp->prg) { case CPRL: strncpy(prog, "CPRL", 4); break; case LRCP: strncpy(prog, "LRCP", 4); break; case PCRL: strncpy(prog, "PCRL", 4); break; case RLCP: strncpy(prog, "RLCP", 4); break; case RPCL: strncpy(prog, "RPCL", 4); break; case PROG_UNKNOWN: return OPJ_TRUE; } if (!(cp->tp_on && ((!cp->cinema && (t2_mode == FINAL_PASS)) || cp->cinema))) { pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; pi[pino].poc.tx0 = tcp->txS; pi[pino].poc.ty0 = tcp->tyS; pi[pino].poc.tx1 = tcp->txE; pi[pino].poc.ty1 = tcp->tyE; } else { if (tpnum < cur_totnum_tp) { for (i = 3; i >= 0; i--) { switch (prog[i]) { case 'C': if (i > tppos) { pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; } else { if (tpnum == 0) { tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; } else { if (incr_top == 1) { if (tcp->comp_t == tcp->compE) { tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; incr_top = 1; } else { pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; incr_top = 0; } } else { pi[pino].poc.compno0 = tcp->comp_t - 1; pi[pino].poc.compno1 = tcp->comp_t; } } } break; case 'R': if (i > tppos) { pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; } else { if (tpnum == 0) { tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; } else { if (incr_top == 1) { if (tcp->res_t == tcp->resE) { tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; incr_top = 1; } else { pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; incr_top = 0; } } else { pi[pino].poc.resno0 = tcp->res_t - 1; pi[pino].poc.resno1 = tcp->res_t; } } } break; case 'L': if (i > tppos) { pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; } else { if (tpnum == 0) { tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; } else { if (incr_top == 1) { if (tcp->lay_t == tcp->layE) { tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; incr_top = 1; } else { pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; incr_top = 0; } } else { pi[pino].poc.layno0 = tcp->lay_t - 1; pi[pino].poc.layno1 = tcp->lay_t; } } } break; case 'P': switch (tcp->prg) { case LRCP: case RLCP: if (i > tppos) { pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; } else { if (tpnum == 0) { tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; } else { if (incr_top == 1) { if (tcp->prc_t == tcp->prcE) { tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; incr_top = 1; } else { pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; incr_top = 0; } } else { pi[pino].poc.precno0 = tcp->prc_t - 1; pi[pino].poc.precno1 = tcp->prc_t; } } } break; default: if (i > tppos) { pi[pino].poc.tx0 = tcp->txS; pi[pino].poc.ty0 = tcp->tyS; pi[pino].poc.tx1 = tcp->txE; pi[pino].poc.ty1 = tcp->tyE; } else { if (tpnum == 0) { tcp->tx0_t = tcp->txS; tcp->ty0_t = tcp->tyS; pi[pino].poc.tx0 = tcp->tx0_t; pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx); pi[pino].poc.ty0 = tcp->ty0_t; pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); tcp->tx0_t = pi[pino].poc.tx1; tcp->ty0_t = pi[pino].poc.ty1; } else { if (incr_top == 1) { if (tcp->tx0_t >= tcp->txE) { if (tcp->ty0_t >= tcp->tyE) { tcp->ty0_t = tcp->tyS; pi[pino].poc.ty0 = tcp->ty0_t; pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); tcp->ty0_t = pi[pino].poc.ty1; incr_top = 1; resetX = 1; } else { pi[pino].poc.ty0 = tcp->ty0_t; pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); tcp->ty0_t = pi[pino].poc.ty1; incr_top = 0; resetX = 1; } if (resetX == 1) { tcp->tx0_t = tcp->txS; pi[pino].poc.tx0 = tcp->tx0_t; pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx); tcp->tx0_t = pi[pino].poc.tx1; } } else { pi[pino].poc.tx0 = tcp->tx0_t; pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx); tcp->tx0_t = pi[pino].poc.tx1; pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy); pi[pino].poc.ty1 = tcp->ty0_t ; incr_top = 0; } } else { pi[pino].poc.tx0 = tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx); pi[pino].poc.tx1 = tcp->tx0_t ; pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy); pi[pino].poc.ty1 = tcp->ty0_t ; } } } break; } break; } } } } return OPJ_FALSE; }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_538_0
crossvul-cpp_data_good_5311_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT U U M M % % Q Q U U A A NN N T U U MM MM % % Q Q U U AAAAA N N N T U U M M M % % Q QQ U U A A N NN T U U M M % % QQQQ UUU A A N N T UUU M M % % % % MagicCore Methods to Acquire / Destroy Quantum Pixels % % % % Software Design % % Cristy % % October 1998 % % % % % % Copyright 1999-2016 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 "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/color-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/delegate.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/statistic.h" #include "MagickCore/stream.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/utility.h" /* Define declarations. */ #define QuantumSignature 0xab /* Forward declarations. */ static void DestroyQuantumPixels(QuantumInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumInfo() allocates the QuantumInfo structure. % % The format of the AcquireQuantumInfo method is: % % QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ MagickExport QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info, Image *image) { MagickBooleanType status; QuantumInfo *quantum_info; quantum_info=(QuantumInfo *) AcquireMagickMemory(sizeof(*quantum_info)); if (quantum_info == (QuantumInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); quantum_info->signature=MagickCoreSignature; GetQuantumInfo(image_info,quantum_info); if (image == (const Image *) NULL) return(quantum_info); status=SetQuantumDepth(image,quantum_info,image->depth); quantum_info->endian=image->endian; if (status == MagickFalse) quantum_info=DestroyQuantumInfo(quantum_info); return(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumPixels() allocates the pixel staging areas. % % The format of the AcquireQuantumPixels method is: % % MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info, % const size_t extent) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o extent: the quantum info. % */ static MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info, const size_t extent) { register ssize_t i; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); quantum_info->pixels=(unsigned char **) AcquireQuantumMemory( quantum_info->number_threads,sizeof(*quantum_info->pixels)); if (quantum_info->pixels == (unsigned char **) NULL) return(MagickFalse); quantum_info->extent=extent; (void) ResetMagickMemory(quantum_info->pixels,0,quantum_info->number_threads* sizeof(*quantum_info->pixels)); for (i=0; i < (ssize_t) quantum_info->number_threads; i++) { quantum_info->pixels[i]=(unsigned char *) AcquireQuantumMemory(extent+1, sizeof(**quantum_info->pixels)); if (quantum_info->pixels[i] == (unsigned char *) NULL) { while (--i >= 0) quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory( quantum_info->pixels[i]); return(MagickFalse); } (void) ResetMagickMemory(quantum_info->pixels[i],0,(extent+1)* sizeof(**quantum_info->pixels)); quantum_info->pixels[i][extent]=QuantumSignature; } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantumInfo() deallocates memory associated with the QuantumInfo % structure. % % The format of the DestroyQuantumInfo method is: % % QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); if (quantum_info->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&quantum_info->semaphore); quantum_info->signature=(~MagickCoreSignature); quantum_info=(QuantumInfo *) RelinquishMagickMemory(quantum_info); return(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantumPixels() destroys the quantum pixels. % % The format of the DestroyQuantumPixels() method is: % % void DestroyQuantumPixels(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ static void DestroyQuantumPixels(QuantumInfo *quantum_info) { register ssize_t i; ssize_t extent; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); assert(quantum_info->pixels != (unsigned char **) NULL); extent=(ssize_t) quantum_info->extent; for (i=0; i < (ssize_t) quantum_info->number_threads; i++) if (quantum_info->pixels[i] != (unsigned char *) NULL) { /* Did we overrun our quantum buffer? */ assert(quantum_info->pixels[i][extent] == QuantumSignature); quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory( quantum_info->pixels[i]); } quantum_info->pixels=(unsigned char **) RelinquishMagickMemory( quantum_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumExtent() returns the quantum pixel buffer extent. % % The format of the GetQuantumExtent method is: % % size_t GetQuantumExtent(Image *image,const QuantumInfo *quantum_info, % const QuantumType quantum_type) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o quantum_type: Declare which pixel components to transfer (red, green, % blue, opacity, RGB, or RGBA). % */ MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t extent, packet_size; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); packet_size=1; switch (quantum_type) { case GrayAlphaQuantum: packet_size=2; break; case IndexAlphaQuantum: packet_size=2; break; case RGBQuantum: packet_size=3; break; case BGRQuantum: packet_size=3; break; case RGBAQuantum: packet_size=4; break; case RGBOQuantum: packet_size=4; break; case BGRAQuantum: packet_size=4; break; case CMYKQuantum: packet_size=4; break; case CMYKAQuantum: packet_size=5; break; default: break; } extent=MagickMax(image->columns,image->rows); if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*extent*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*extent*quantum_info->depth+7)/8)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m E n d i a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumEndian() returns the quantum endian of the image. % % The endian of the GetQuantumEndian method is: % % EndianType GetQuantumEndian(const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport EndianType GetQuantumEndian(const QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); return(quantum_info->endian); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumFormat() returns the quantum format of the image. % % The format of the GetQuantumFormat method is: % % QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); return(quantum_info->format); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumInfo() initializes the QuantumInfo structure to default values. % % The format of the GetQuantumInfo method is: % % GetQuantumInfo(const ImageInfo *image_info,QuantumInfo *quantum_info) % % A description of each parameter follows: % % o image_info: the image info. % % o quantum_info: the quantum info. % */ MagickExport void GetQuantumInfo(const ImageInfo *image_info, QuantumInfo *quantum_info) { const char *option; assert(quantum_info != (QuantumInfo *) NULL); (void) ResetMagickMemory(quantum_info,0,sizeof(*quantum_info)); quantum_info->quantum=8; quantum_info->maximum=1.0; quantum_info->scale=QuantumRange; quantum_info->pack=MagickTrue; quantum_info->semaphore=AcquireSemaphoreInfo(); quantum_info->signature=MagickCoreSignature; if (image_info == (const ImageInfo *) NULL) return; option=GetImageOption(image_info,"quantum:format"); if (option != (char *) NULL) quantum_info->format=(QuantumFormatType) ParseCommandOption( MagickQuantumFormatOptions,MagickFalse,option); option=GetImageOption(image_info,"quantum:minimum"); if (option != (char *) NULL) quantum_info->minimum=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"quantum:maximum"); if (option != (char *) NULL) quantum_info->maximum=StringToDouble(option,(char **) NULL); if ((quantum_info->minimum == 0.0) && (quantum_info->maximum == 0.0)) quantum_info->scale=0.0; else if (quantum_info->minimum == quantum_info->maximum) { quantum_info->scale=(double) QuantumRange/quantum_info->minimum; quantum_info->minimum=0.0; } else quantum_info->scale=(double) QuantumRange/(quantum_info->maximum- quantum_info->minimum); option=GetImageOption(image_info,"quantum:scale"); if (option != (char *) NULL) quantum_info->scale=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"quantum:polarity"); if (option != (char *) NULL) quantum_info->min_is_white=LocaleCompare(option,"min-is-white") == 0 ? MagickTrue : MagickFalse; quantum_info->endian=image_info->endian; ResetQuantumState(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumPixels() returns the quantum pixels. % % The format of the GetQuantumPixels method is: % % unsigned char *QuantumPixels GetQuantumPixels( % const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o image: the image. % */ MagickExport unsigned char *GetQuantumPixels(const QuantumInfo *quantum_info) { const int id = GetOpenMPThreadId(); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); return(quantum_info->pixels[id]); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumType() returns the quantum type of the image. % % The format of the GetQuantumType method is: % % QuantumType GetQuantumType(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport QuantumType GetQuantumType(Image *image,ExceptionInfo *exception) { QuantumType quantum_type; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); (void) exception; quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; } if (IsGrayColorspace(image->colorspace) != MagickFalse) { quantum_type=GrayQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=GrayAlphaQuantum; } if (image->storage_class == PseudoClass) { quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=IndexAlphaQuantum; } return(quantum_type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t Q u a n t u m S t a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetQuantumState() resets the quantum state. % % The format of the ResetQuantumState method is: % % void ResetQuantumState(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickPrivate void ResetQuantumState(QuantumInfo *quantum_info) { static const unsigned int mask[32] = { 0x00000000U, 0x00000001U, 0x00000003U, 0x00000007U, 0x0000000fU, 0x0000001fU, 0x0000003fU, 0x0000007fU, 0x000000ffU, 0x000001ffU, 0x000003ffU, 0x000007ffU, 0x00000fffU, 0x00001fffU, 0x00003fffU, 0x00007fffU, 0x0000ffffU, 0x0001ffffU, 0x0003ffffU, 0x0007ffffU, 0x000fffffU, 0x001fffffU, 0x003fffffU, 0x007fffffU, 0x00ffffffU, 0x01ffffffU, 0x03ffffffU, 0x07ffffffU, 0x0fffffffU, 0x1fffffffU, 0x3fffffffU, 0x7fffffffU }; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->state.inverse_scale=1.0; if (fabs(quantum_info->scale) >= MagickEpsilon) quantum_info->state.inverse_scale/=quantum_info->scale; quantum_info->state.pixel=0U; quantum_info->state.bits=0U; quantum_info->state.mask=mask; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumAlphaType() sets the quantum format. % % The format of the SetQuantumAlphaType method is: % % void SetQuantumAlphaType(QuantumInfo *quantum_info, % const QuantumAlphaType type) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o type: the alpha type (e.g. associate). % */ MagickExport void SetQuantumAlphaType(QuantumInfo *quantum_info, const QuantumAlphaType type) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->alpha_type=type; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumDepth() sets the quantum depth. % % The format of the SetQuantumDepth method is: % % MagickBooleanType SetQuantumDepth(const Image *image, % QuantumInfo *quantum_info,const size_t depth) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o depth: the quantum depth. % */ MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=MagickMax(image->columns,image->rows)*quantum; if ((MagickMax(image->columns,image->rows) != 0) && (quantum != (extent/MagickMax(image->columns,image->rows)))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m E n d i a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumEndian() sets the quantum endian. % % The endian of the SetQuantumEndian method is: % % MagickBooleanType SetQuantumEndian(const Image *image, % QuantumInfo *quantum_info,const EndianType endian) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o endian: the quantum endian. % */ MagickExport MagickBooleanType SetQuantumEndian(const Image *image, QuantumInfo *quantum_info,const EndianType endian) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->endian=endian; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumFormat() sets the quantum format. % % The format of the SetQuantumFormat method is: % % MagickBooleanType SetQuantumFormat(const Image *image, % QuantumInfo *quantum_info,const QuantumFormatType format) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o format: the quantum format. % */ MagickExport MagickBooleanType SetQuantumFormat(const Image *image, QuantumInfo *quantum_info,const QuantumFormatType format) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->format=format; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m I m a g e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumImageType() sets the image type based on the quantum type. % % The format of the SetQuantumImageType method is: % % void ImageType SetQuantumImageType(Image *image, % const QuantumType quantum_type) % % A description of each parameter follows: % % o image: the image. % % o quantum_type: Declare which pixel components to transfer (red, green, % blue, opacity, RGB, or RGBA). % */ MagickExport void SetQuantumImageType(Image *image, const QuantumType quantum_type) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); switch (quantum_type) { case IndexQuantum: case IndexAlphaQuantum: { image->type=PaletteType; break; } case GrayQuantum: case GrayAlphaQuantum: { image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; break; } case CyanQuantum: case MagentaQuantum: case YellowQuantum: case BlackQuantum: case CMYKQuantum: case CMYKAQuantum: { image->type=ColorSeparationType; break; } default: { image->type=TrueColorType; break; } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m P a c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumPack() sets the quantum pack flag. % % The format of the SetQuantumPack method is: % % void SetQuantumPack(QuantumInfo *quantum_info, % const MagickBooleanType pack) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o pack: the pack flag. % */ MagickExport void SetQuantumPack(QuantumInfo *quantum_info, const MagickBooleanType pack) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->pack=pack; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m P a d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumPad() sets the quantum pad. % % The format of the SetQuantumPad method is: % % MagickBooleanType SetQuantumPad(const Image *image, % QuantumInfo *quantum_info,const size_t pad) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o pad: the quantum pad. % */ MagickExport MagickBooleanType SetQuantumPad(const Image *image, QuantumInfo *quantum_info,const size_t pad) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->pad=pad; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m M i n I s W h i t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumMinIsWhite() sets the quantum min-is-white flag. % % The format of the SetQuantumMinIsWhite method is: % % void SetQuantumMinIsWhite(QuantumInfo *quantum_info, % const MagickBooleanType min_is_white) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o min_is_white: the min-is-white flag. % */ MagickExport void SetQuantumMinIsWhite(QuantumInfo *quantum_info, const MagickBooleanType min_is_white) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->min_is_white=min_is_white; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m Q u a n t u m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumQuantum() sets the quantum quantum. % % The format of the SetQuantumQuantum method is: % % void SetQuantumQuantum(QuantumInfo *quantum_info, % const size_t quantum) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o quantum: the quantum quantum. % */ MagickExport void SetQuantumQuantum(QuantumInfo *quantum_info, const size_t quantum) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->quantum=quantum; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m S c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumScale() sets the quantum scale. % % The format of the SetQuantumScale method is: % % void SetQuantumScale(QuantumInfo *quantum_info,const double scale) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o scale: the quantum scale. % */ MagickExport void SetQuantumScale(QuantumInfo *quantum_info,const double scale) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->scale=scale; }
./CrossVul/dataset_final_sorted/CWE-369/c/good_5311_0
crossvul-cpp_data_good_817_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % X X W W DDDD % % X X W W D D % % X W W D D % % X X W W W D D % % X X W W DDDD % % % % % % Read/Write X Windows System Window Dump Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 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://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/colormap-private.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/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #if defined(MAGICKCORE_X11_DELEGATE) #include "magick/xwindow-private.h" #if !defined(vms) #include <X11/XWDFile.h> #else #include "XWDFile.h" #endif #endif /* Forward declarations. */ #if defined(MAGICKCORE_X11_DELEGATE) static MagickBooleanType WriteXWDImage(const ImageInfo *,Image *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s X W D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsXWD() returns MagickTrue if the image format type, identified by the % magick string, is XWD. % % The format of the IsXWD method is: % % MagickBooleanType IsXWD(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 IsXWD(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick+1,"\000\000",2) == 0) { if (memcmp(magick+4,"\007\000\000",3) == 0) return(MagickTrue); if (memcmp(magick+5,"\000\000\007",3) == 0) return(MagickTrue); } return(MagickFalse); } #if defined(MAGICKCORE_X11_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadXWDImage() reads an X Window System window dump 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 ReadXWDImage method is: % % Image *ReadXWDImage(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 *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CheckOverflowException(length,width,height) \ (((height) != 0) && ((length)/((size_t) height) != ((size_t) width))) char *comment; Image *image; IndexPacket index; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register size_t pixel; size_t length; ssize_t count, y; unsigned long lsb_first; XColor *colors; XImage *ximage; XWDFileHeader header; /* 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); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read in header information. */ count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header); if (count != sz_XWDheader) ThrowReaderException(CorruptImageError,"UnableToReadImageHeader"); /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &header,sz_XWDheader); /* Check to see if the dump file is in the proper format. */ if (header.file_version != XWD_FILE_VERSION) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); if (header.header_size < sz_XWDheader) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((header.bits_per_pixel == 0) || (header.bits_per_pixel > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((header.bitmap_bit_order != MSBFirst) && (header.bitmap_bit_order != LSBFirst)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (header.bitmap_unit > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (header.ncolors > 256) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.visual_class) { case StaticGray: case GrayScale: case StaticColor: case PseudoColor: case TrueColor: case DirectColor: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.pixmap_format) { case XYBitmap: case XYPixmap: case ZPixmap: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } length=(size_t) (header.header_size-sz_XWDheader); if ((length+1) != ((size_t) ((CARD32) (length+1)))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length,(unsigned char *) comment); comment[length]='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Initialize the X image. */ ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage)); if (ximage == (XImage *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ximage->depth=(int) header.pixmap_depth; ximage->format=(int) header.pixmap_format; ximage->xoffset=(int) header.xoffset; ximage->data=(char *) NULL; ximage->width=(int) header.pixmap_width; ximage->height=(int) header.pixmap_height; ximage->bitmap_pad=(int) header.bitmap_pad; ximage->bytes_per_line=(int) header.bytes_per_line; ximage->byte_order=(int) header.byte_order; ximage->bitmap_unit=(int) header.bitmap_unit; ximage->bitmap_bit_order=(int) header.bitmap_bit_order; ximage->bits_per_pixel=(int) header.bits_per_pixel; ximage->red_mask=header.red_mask; ximage->green_mask=header.green_mask; ximage->blue_mask=header.blue_mask; if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) || (ximage->format < 0) || (ximage->byte_order < 0) || (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) || (ximage->bytes_per_line < 0)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->width > 65535) || (ximage->height > 65535)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } x_status=XInitImage(ximage); if (x_status == 0) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } /* Read colormap. */ authentic_colormap=MagickFalse; colors=(XColor *) NULL; if (header.ncolors != 0) { XWDColor color; length=(size_t) header.ncolors; if (length > ((~0UL)/sizeof(*colors))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); colors=(XColor *) AcquireQuantumMemory(length,sizeof(*colors)); if (colors == (XColor *) NULL) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) header.ncolors; i++) { count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != sz_XWDColor) { colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } colors[i].pixel=color.pixel; colors[i].red=color.red; colors[i].green=color.green; colors[i].blue=color.blue; colors[i].flags=(char) color.flags; if (color.flags != 0) authentic_colormap=MagickTrue; } /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) for (i=0; i < (ssize_t) header.ncolors; i++) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } /* Allocate the pixel buffer. */ length=(size_t) ximage->bytes_per_line*ximage->height; if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (ximage->format != ZPixmap) { size_t extent; extent=length; length*=ximage->depth; if (CheckOverflowException(length,extent,ximage->depth)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data)); if (ximage->data == (char *) NULL) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } count=ReadBlob(image,length,(unsigned char *) ximage->data); if (count != (ssize_t) length) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } /* Convert image to MIFF format. */ image->columns=(size_t) ximage->width; image->rows=(size_t) ximage->height; image->depth=8; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((header.ncolors == 0U) || (ximage->red_mask != 0) || (ximage->green_mask != 0) || (ximage->blue_mask != 0)) image->storage_class=DirectClass; else image->storage_class=PseudoClass; image->colors=header.ncolors; if (image_info->ping == MagickFalse) switch (image->storage_class) { case DirectClass: default: { register size_t color; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=ximage->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=ximage->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=ximage->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((image->colors != 0) && (authentic_colormap != MagickFalse)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> red_shift) & red_mask); SetPixelRed(q,ScaleShortToQuantum(colors[(ssize_t) index].red)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> green_shift) & green_mask); SetPixelGreen(q,ScaleShortToQuantum(colors[(ssize_t) index].green)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> blue_shift) & blue_mask); SetPixelBlue(q,ScaleShortToQuantum(colors[(ssize_t) index].blue)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); color=(pixel >> red_shift) & red_mask; if (red_mask != 0) color=(color*65535UL)/red_mask; SetPixelRed(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case PseudoClass: { /* Convert X image to PseudoClass packets. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleShortToQuantum(colors[i].red); image->colormap[i].green=ScaleShortToQuantum(colors[i].green); image->colormap[i].blue=ScaleShortToQuantum(colors[i].blue); } 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++) { index=ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int) x,(int) y)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } } /* Free image and colormap. */ if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterXWDImage() adds properties for the XWD 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 RegisterXWDImage method is: % % size_t RegisterXWDImage(void) % */ ModuleExport size_t RegisterXWDImage(void) { MagickInfo *entry; entry=SetMagickInfo("XWD"); #if defined(MAGICKCORE_X11_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadXWDImage; entry->encoder=(EncodeImageHandler *) WriteXWDImage; #endif entry->magick=(IsImageFormatHandler *) IsXWD; entry->adjoin=MagickFalse; entry->description=ConstantString("X Windows system window dump (color)"); entry->module=ConstantString("XWD"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterXWDImage() removes format registrations made by the % XWD module from the list of supported formats. % % The format of the UnregisterXWDImage method is: % % UnregisterXWDImage(void) % */ ModuleExport void UnregisterXWDImage(void) { (void) UnregisterMagickInfo("XWD"); } #if defined(MAGICKCORE_X11_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteXWDImage() writes an image to a file in X window dump % rasterfile format. % % The format of the WriteXWDImage method is: % % MagickBooleanType WriteXWDImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteXWDImage(const ImageInfo *image_info,Image *image) { const char *value; MagickBooleanType status; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t x; register unsigned char *q; size_t bits_per_pixel, bytes_per_line, length, scanline_pad; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; XWDFileHeader xwd_info; /* Open output image 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); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); if ((image->columns != (CARD32) image->columns) || (image->rows != (CARD32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageType(image,TrueColorType); (void) TransformImageColorspace(image,sRGBColorspace); /* Initialize XWD file header. */ (void) memset(&xwd_info,0,sizeof(xwd_info)); xwd_info.header_size=(CARD32) sz_XWDheader; value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) xwd_info.header_size+=(CARD32) strlen(value); xwd_info.header_size++; xwd_info.file_version=(CARD32) XWD_FILE_VERSION; xwd_info.pixmap_format=(CARD32) ZPixmap; xwd_info.pixmap_depth=(CARD32) (image->storage_class == DirectClass ? 24 : 8); xwd_info.pixmap_width=(CARD32) image->columns; xwd_info.pixmap_height=(CARD32) image->rows; xwd_info.xoffset=(CARD32) 0; xwd_info.byte_order=(CARD32) MSBFirst; xwd_info.bitmap_unit=(CARD32) (image->storage_class == DirectClass ? 32 : 8); xwd_info.bitmap_bit_order=(CARD32) MSBFirst; xwd_info.bitmap_pad=(CARD32) (image->storage_class == DirectClass ? 32 : 8); bits_per_pixel=(size_t) (image->storage_class == DirectClass ? 24 : 8); xwd_info.bits_per_pixel=(CARD32) bits_per_pixel; bytes_per_line=(CARD32) ((((xwd_info.bits_per_pixel* xwd_info.pixmap_width)+((xwd_info.bitmap_pad)-1))/ (xwd_info.bitmap_pad))*((xwd_info.bitmap_pad) >> 3)); xwd_info.bytes_per_line=(CARD32) bytes_per_line; xwd_info.visual_class=(CARD32) (image->storage_class == DirectClass ? DirectColor : PseudoColor); xwd_info.red_mask=(CARD32) (image->storage_class == DirectClass ? 0xff0000 : 0); xwd_info.green_mask=(CARD32) (image->storage_class == DirectClass ? 0xff00 : 0); xwd_info.blue_mask=(CARD32) (image->storage_class == DirectClass ? 0xff : 0); xwd_info.bits_per_rgb=(CARD32) (image->storage_class == DirectClass ? 24 : 8); xwd_info.colormap_entries=(CARD32) (image->storage_class == DirectClass ? 256 : image->colors); xwd_info.ncolors=(unsigned int) (image->storage_class == DirectClass ? 0 : image->colors); xwd_info.window_width=(CARD32) image->columns; xwd_info.window_height=(CARD32) image->rows; xwd_info.window_x=0; xwd_info.window_y=0; xwd_info.window_bdrwidth=(CARD32) 0; /* Write XWD header. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &xwd_info,sizeof(xwd_info)); (void) WriteBlob(image,sz_XWDheader,(unsigned char *) &xwd_info); if (value != (const char *) NULL) (void) WriteBlob(image,strlen(value),(unsigned char *) value); (void) WriteBlob(image,1,(const unsigned char *) "\0"); if (image->storage_class == PseudoClass) { register ssize_t i; XColor *colors; XWDColor color; /* Dump colormap to file. */ (void) memset(&color,0,sizeof(color)); colors=(XColor *) AcquireQuantumMemory((size_t) image->colors, sizeof(*colors)); if (colors == (XColor *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) { colors[i].pixel=(unsigned long) i; colors[i].red=ScaleQuantumToShort(image->colormap[i].red); colors[i].green=ScaleQuantumToShort(image->colormap[i].green); colors[i].blue=ScaleQuantumToShort(image->colormap[i].blue); colors[i].flags=(char) (DoRed | DoGreen | DoBlue); colors[i].pad='\0'; if ((int) (*(char *) &lsb_first) != 0) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } for (i=0; i < (ssize_t) image->colors; i++) { color.pixel=(CARD32) colors[i].pixel; color.red=colors[i].red; color.green=colors[i].green; color.blue=colors[i].blue; color.flags=(CARD8) colors[i].flags; count=WriteBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != (ssize_t) sz_XWDColor) break; } colors=(XColor *) RelinquishMagickMemory(colors); } /* Allocate memory for pixels. */ length=3*bytes_per_line; if (image->storage_class == PseudoClass) length=bytes_per_line; pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(pixels,0,length); /* Convert MIFF to XWD raster pixels. */ scanline_pad=(bytes_per_line-((image->columns*bits_per_pixel) >> 3)); 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; q=pixels; if (image->storage_class == PseudoClass) { indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); } else for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); p++; } for (x=0; x < (ssize_t) scanline_pad; x++) *q++='\0'; length=(size_t) (q-pixels); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-369/c/good_817_0
crossvul-cpp_data_good_257_0
/* * MOV, 3GP, MP4 muxer * Copyright (c) 2003 Thomas Raivio * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org> * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com> * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdint.h> #include <inttypes.h> #include "movenc.h" #include "avformat.h" #include "avio_internal.h" #include "riff.h" #include "avio.h" #include "isom.h" #include "avc.h" #include "libavcodec/ac3_parser_internal.h" #include "libavcodec/dnxhddata.h" #include "libavcodec/flac.h" #include "libavcodec/get_bits.h" #include "libavcodec/internal.h" #include "libavcodec/put_bits.h" #include "libavcodec/vc1_common.h" #include "libavcodec/raw.h" #include "internal.h" #include "libavutil/avstring.h" #include "libavutil/intfloat.h" #include "libavutil/mathematics.h" #include "libavutil/libm.h" #include "libavutil/opt.h" #include "libavutil/dict.h" #include "libavutil/pixdesc.h" #include "libavutil/stereo3d.h" #include "libavutil/timecode.h" #include "libavutil/color_utils.h" #include "hevc.h" #include "rtpenc.h" #include "mov_chan.h" #include "vpcc.h" static const AVOption options[] = { { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 }, { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags), { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "empty_hdlr_name", "write zero-length name string in hdlr atoms within mdia and minf atoms", offsetof(MOVMuxContext, empty_hdlr_name), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { NULL }, }; #define MOV_CLASS(flavor)\ static const AVClass flavor ## _muxer_class = {\ .class_name = #flavor " muxer",\ .item_name = av_default_item_name,\ .option = options,\ .version = LIBAVUTIL_VERSION_INT,\ }; static int get_moov_size(AVFormatContext *s); static int utf8len(const uint8_t *b) { int len = 0; int val; while (*b) { GET_UTF8(val, *b++, return -1;) len++; } return len; } //FIXME support 64 bit variant with wide placeholders static int64_t update_size(AVIOContext *pb, int64_t pos) { int64_t curpos = avio_tell(pb); avio_seek(pb, pos, SEEK_SET); avio_wb32(pb, curpos - pos); /* rewrite size */ avio_seek(pb, curpos, SEEK_SET); return curpos - pos; } static int co64_required(const MOVTrack *track) { if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX) return 1; return 0; } static int is_cover_image(const AVStream *st) { /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS * is encoded as sparse video track */ return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC; } static int rtp_hinting_needed(const AVStream *st) { /* Add hint tracks for each real audio and video stream */ if (is_cover_image(st)) return 0; return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO; } /* Chunk offset atom */ static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track) { int i; int mode64 = co64_required(track); // use 32 bit size variant if possible int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ if (mode64) ffio_wfourcc(pb, "co64"); else ffio_wfourcc(pb, "stco"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->chunkCount); /* entry count */ for (i = 0; i < track->entry; i++) { if (!track->cluster[i].chunkNum) continue; if (mode64 == 1) avio_wb64(pb, track->cluster[i].pos + track->data_offset); else avio_wb32(pb, track->cluster[i].pos + track->data_offset); } return update_size(pb, pos); } /* Sample size atom */ static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track) { int equalChunks = 1; int i, j, entries = 0, tst = -1, oldtst = -1; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsz"); avio_wb32(pb, 0); /* version & flags */ for (i = 0; i < track->entry; i++) { tst = track->cluster[i].size / track->cluster[i].entries; if (oldtst != -1 && tst != oldtst) equalChunks = 0; oldtst = tst; entries += track->cluster[i].entries; } if (equalChunks && track->entry) { int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0; sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0 avio_wb32(pb, sSize); // sample size avio_wb32(pb, entries); // sample count } else { avio_wb32(pb, 0); // sample size avio_wb32(pb, entries); // sample count for (i = 0; i < track->entry; i++) { for (j = 0; j < track->cluster[i].entries; j++) { avio_wb32(pb, track->cluster[i].size / track->cluster[i].entries); } } } return update_size(pb, pos); } /* Sample to chunk atom */ static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track) { int index = 0, oldval = -1, i; int64_t entryPos, curpos; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsc"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->chunkCount); // entry count for (i = 0; i < track->entry; i++) { if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) { avio_wb32(pb, track->cluster[i].chunkNum); // first chunk avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk avio_wb32(pb, 0x1); // sample description index oldval = track->cluster[i].samples_in_chunk; index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sync sample atom */ static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag) { int64_t curpos, entryPos; int i, index = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->entry); // entry count for (i = 0; i < track->entry; i++) { if (track->cluster[i].flags & flag) { avio_wb32(pb, i + 1); index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sample dependency atom */ static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track) { int i; uint8_t leading, dependent, reference, redundancy; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "sdtp"); avio_wb32(pb, 0); // version & flags for (i = 0; i < track->entry; i++) { dependent = MOV_SAMPLE_DEPENDENCY_YES; leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN; if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) { reference = MOV_SAMPLE_DEPENDENCY_NO; } if (track->cluster[i].flags & MOV_SYNC_SAMPLE) { dependent = MOV_SAMPLE_DEPENDENCY_NO; } avio_w8(pb, (leading << 6) | (dependent << 4) | (reference << 2) | redundancy); } return update_size(pb, pos); } static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x11); /* size */ if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr"); else ffio_wfourcc(pb, "damr"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */ avio_w8(pb, 0x00); /* Mode change period (no restriction) */ avio_w8(pb, 0x01); /* Frames per sample */ return 0x11; } static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track) { GetBitContext gbc; PutBitContext pbc; uint8_t buf[3]; int fscod, bsid, bsmod, acmod, lfeon, frmsizecod; if (track->vos_len < 7) return -1; avio_wb32(pb, 11); ffio_wfourcc(pb, "dac3"); init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8); fscod = get_bits(&gbc, 2); frmsizecod = get_bits(&gbc, 6); bsid = get_bits(&gbc, 5); bsmod = get_bits(&gbc, 3); acmod = get_bits(&gbc, 3); if (acmod == 2) { skip_bits(&gbc, 2); // dsurmod } else { if ((acmod & 1) && acmod != 1) skip_bits(&gbc, 2); // cmixlev if (acmod & 4) skip_bits(&gbc, 2); // surmixlev } lfeon = get_bits1(&gbc); init_put_bits(&pbc, buf, sizeof(buf)); put_bits(&pbc, 2, fscod); put_bits(&pbc, 5, bsid); put_bits(&pbc, 3, bsmod); put_bits(&pbc, 3, acmod); put_bits(&pbc, 1, lfeon); put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code put_bits(&pbc, 5, 0); // reserved flush_put_bits(&pbc); avio_write(pb, buf, sizeof(buf)); return 11; } struct eac3_info { AVPacket pkt; uint8_t ec3_done; uint8_t num_blocks; /* Layout of the EC3SpecificBox */ /* maximum bitrate */ uint16_t data_rate; /* number of independent substreams */ uint8_t num_ind_sub; struct { /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */ uint8_t fscod; /* bit stream identification 5 bits */ uint8_t bsid; /* one bit reserved */ /* audio service mixing (not supported yet) 1 bit */ /* bit stream mode 3 bits */ uint8_t bsmod; /* audio coding mode 3 bits */ uint8_t acmod; /* sub woofer on 1 bit */ uint8_t lfeon; /* 3 bits reserved */ /* number of dependent substreams associated with this substream 4 bits */ uint8_t num_dep_sub; /* channel locations of the dependent substream(s), if any, 9 bits */ uint16_t chan_loc; /* if there is no dependent substream, then one bit reserved instead */ } substream[1]; /* TODO: support 8 independent substreams */ }; #if CONFIG_AC3_PARSER static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov->fc, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { //info->num_ind_sub++; avpriv_request_sample(mov->fc, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } else { if (hdr->substreamid != 0) { avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } #endif static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track) { PutBitContext pbc; uint8_t *buf; struct eac3_info *info; int size, i; if (!track->eac3_priv) return AVERROR(EINVAL); info = track->eac3_priv; size = 2 + 4 * (info->num_ind_sub + 1); buf = av_malloc(size); if (!buf) { size = AVERROR(ENOMEM); goto end; } init_put_bits(&pbc, buf, size); put_bits(&pbc, 13, info->data_rate); put_bits(&pbc, 3, info->num_ind_sub); for (i = 0; i <= info->num_ind_sub; i++) { put_bits(&pbc, 2, info->substream[i].fscod); put_bits(&pbc, 5, info->substream[i].bsid); put_bits(&pbc, 1, 0); /* reserved */ put_bits(&pbc, 1, 0); /* asvc */ put_bits(&pbc, 3, info->substream[i].bsmod); put_bits(&pbc, 3, info->substream[i].acmod); put_bits(&pbc, 1, info->substream[i].lfeon); put_bits(&pbc, 5, 0); /* reserved */ put_bits(&pbc, 4, info->substream[i].num_dep_sub); if (!info->substream[i].num_dep_sub) { put_bits(&pbc, 1, 0); /* reserved */ size--; } else { put_bits(&pbc, 9, info->substream[i].chan_loc); } } flush_put_bits(&pbc); avio_wb32(pb, size + 8); ffio_wfourcc(pb, "dec3"); avio_write(pb, buf, size); av_free(buf); end: av_packet_unref(&info->pkt); av_freep(&track->eac3_priv); return size; } /** * This function writes extradata "as is". * Extradata must be formatted like a valid atom (with size and tag). */ static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track) { avio_write(pb, track->par->extradata, track->par->extradata_size); return track->par->extradata_size; } static int mov_write_enda_tag(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 1); /* little endian */ return 10; } static int mov_write_enda_tag_be(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 0); /* big endian */ return 10; } static void put_descr(AVIOContext *pb, int tag, unsigned int size) { int i = 3; avio_w8(pb, tag); for (; i > 0; i--) avio_w8(pb, (size >> (7 * i)) | 0x80); avio_w8(pb, size & 0x7F); } static unsigned compute_avg_bitrate(MOVTrack *track) { uint64_t size = 0; int i; if (!track->track_duration) return 0; for (i = 0; i < track->entry; i++) size += track->cluster[i].size; return size * 8 * track->timescale / track->track_duration; } static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic { AVCPBProperties *props; int64_t pos = avio_tell(pb); int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0; unsigned avg_bitrate; avio_wb32(pb, 0); // size ffio_wfourcc(pb, "esds"); avio_wb32(pb, 0); // Version // ES descriptor put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1); avio_wb16(pb, track->track_id); avio_w8(pb, 0x00); // flags (= no flags) // DecoderConfig descriptor put_descr(pb, 0x04, 13 + decoder_specific_info_len); // Object type indication if ((track->par->codec_id == AV_CODEC_ID_MP2 || track->par->codec_id == AV_CODEC_ID_MP3) && track->par->sample_rate > 24000) avio_w8(pb, 0x6B); // 11172-3 else avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id)); // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio) // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved) if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream) else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_w8(pb, 0x15); // flags (= Audiostream) else avio_w8(pb, 0x11); // flags (= Visualstream) props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB avg_bitrate = compute_avg_bitrate(track); avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window) avio_wb32(pb, avg_bitrate); if (track->vos_len) { // DecoderSpecific info descriptor put_descr(pb, 0x05, track->vos_len); avio_write(pb, track->vos_data, track->vos_len); } // SL descriptor put_descr(pb, 0x06, 1); avio_w8(pb, 0x02); return update_size(pb, pos); } static int mov_pcm_le_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24LE || codec_id == AV_CODEC_ID_PCM_S32LE || codec_id == AV_CODEC_ID_PCM_F32LE || codec_id == AV_CODEC_ID_PCM_F64LE; } static int mov_pcm_be_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24BE || codec_id == AV_CODEC_ID_PCM_S32BE || codec_id == AV_CODEC_ID_PCM_F32BE || codec_id == AV_CODEC_ID_PCM_F64BE; } static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); avio_wl32(pb, track->tag); // store it byteswapped track->par->codec_tag = av_bswap16(track->tag >> 16); if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0) return ret; return update_size(pb, pos); } static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "wfex"); if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0) return ret; return update_size(pb, pos); } static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dfLa"); avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */ if (track->par->extradata_size != FLAC_STREAMINFO_SIZE) return AVERROR_INVALIDDATA; /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */ avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */ avio_wb24(pb, track->par->extradata_size); /* Length */ avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */ return update_size(pb, pos); } static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dOps"); avio_w8(pb, 0); /* Version */ if (track->par->extradata_size < 19) { av_log(pb, AV_LOG_ERROR, "invalid extradata size\n"); return AVERROR_INVALIDDATA; } /* extradata contains an Ogg OpusHead, other than byte-ordering and OpusHead's preceeding magic/version, OpusSpecificBox is currently identical. */ avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */ avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */ avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */ avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */ /* Write the rest of the header out without byte-swapping. */ avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18); return update_size(pb, pos); } static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { uint32_t layout_tag, bitmap; int64_t pos = avio_tell(pb); layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id, track->par->channel_layout, &bitmap); if (!layout_tag) { av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to " "lack of channel information\n"); return 0; } if (track->multichannel_as_mono) return 0; avio_wb32(pb, 0); // Size ffio_wfourcc(pb, "chan"); // Type avio_w8(pb, 0); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, layout_tag); // mChannelLayoutTag avio_wb32(pb, bitmap); // mChannelBitmap avio_wb32(pb, 0); // mNumberChannelDescriptions return update_size(pb, pos); } static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "wave"); if (track->par->codec_id != AV_CODEC_ID_QDM2) { avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "frma"); avio_wl32(pb, track->tag); } if (track->par->codec_id == AV_CODEC_ID_AAC) { /* useless atom needed by mplayer, ipod, not needed by quicktime */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0); mov_write_esds_tag(pb, track); } else if (mov_pcm_le_gt16(track->par->codec_id)) { mov_write_enda_tag(pb); } else if (mov_pcm_be_gt16(track->par->codec_id)) { mov_write_enda_tag_be(pb); } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) { mov_write_amr_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_AC3) { mov_write_ac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_EAC3) { mov_write_eac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_QDM2) { mov_write_extradata_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { mov_write_ms_tag(s, pb, track); } avio_wb32(pb, 8); /* size */ avio_wb32(pb, 0); /* null tag */ return update_size(pb, pos); } static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf) { uint8_t *unescaped; const uint8_t *start, *next, *end = track->vos_data + track->vos_len; int unescaped_size, seq_found = 0; int level = 0, interlace = 0; int packet_seq = track->vc1_info.packet_seq; int packet_entry = track->vc1_info.packet_entry; int slices = track->vc1_info.slices; PutBitContext pbc; if (track->start_dts == AV_NOPTS_VALUE) { /* No packets written yet, vc1_info isn't authoritative yet. */ /* Assume inline sequence and entry headers. */ packet_seq = packet_entry = 1; av_log(NULL, AV_LOG_WARNING, "moov atom written before any packets, unable to write correct " "dvc1 atom. Set the delay_moov flag to fix this.\n"); } unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE); if (!unescaped) return AVERROR(ENOMEM); start = find_next_marker(track->vos_data, end); for (next = start; next < end; start = next) { GetBitContext gb; int size; next = find_next_marker(start + 4, end); size = next - start - 4; if (size <= 0) continue; unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped); init_get_bits(&gb, unescaped, 8 * unescaped_size); if (AV_RB32(start) == VC1_CODE_SEQHDR) { int profile = get_bits(&gb, 2); if (profile != PROFILE_ADVANCED) { av_free(unescaped); return AVERROR(ENOSYS); } seq_found = 1; level = get_bits(&gb, 3); /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag, * width, height */ skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12); skip_bits(&gb, 1); /* broadcast */ interlace = get_bits1(&gb); skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */ } } if (!seq_found) { av_free(unescaped); return AVERROR(ENOSYS); } init_put_bits(&pbc, buf, 7); /* VC1DecSpecStruc */ put_bits(&pbc, 4, 12); /* profile - advanced */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* reserved */ /* VC1AdvDecSpecStruc */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* cbr */ put_bits(&pbc, 6, 0); /* reserved */ put_bits(&pbc, 1, !interlace); /* no interlace */ put_bits(&pbc, 1, !packet_seq); /* no multiple seq */ put_bits(&pbc, 1, !packet_entry); /* no multiple entry */ put_bits(&pbc, 1, !slices); /* no slice code */ put_bits(&pbc, 1, 0); /* no bframe */ put_bits(&pbc, 1, 0); /* reserved */ /* framerate */ if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0) put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den); else put_bits32(&pbc, 0xffffffff); flush_put_bits(&pbc); av_free(unescaped); return 0; } static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track) { uint8_t buf[7] = { 0 }; int ret; if ((ret = mov_write_dvc1_structs(track, buf)) < 0) return ret; avio_wb32(pb, track->vos_len + 8 + sizeof(buf)); ffio_wfourcc(pb, "dvc1"); avio_write(pb, buf, sizeof(buf)); avio_write(pb, track->vos_data, track->vos_len); return 0; } static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, track->vos_len + 8); ffio_wfourcc(pb, "glbl"); avio_write(pb, track->vos_data, track->vos_len); return 8 + track->vos_len; } /** * Compute flags for 'lpcm' tag. * See CoreAudioTypes and AudioStreamBasicDescription at Apple. */ static int mov_get_lpcm_flags(enum AVCodecID codec_id) { switch (codec_id) { case AV_CODEC_ID_PCM_F32BE: case AV_CODEC_ID_PCM_F64BE: return 11; case AV_CODEC_ID_PCM_F32LE: case AV_CODEC_ID_PCM_F64LE: return 9; case AV_CODEC_ID_PCM_U8: return 10; case AV_CODEC_ID_PCM_S16BE: case AV_CODEC_ID_PCM_S24BE: case AV_CODEC_ID_PCM_S32BE: return 14; case AV_CODEC_ID_PCM_S8: case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S24LE: case AV_CODEC_ID_PCM_S32LE: return 12; default: return 0; } } static int get_cluster_duration(MOVTrack *track, int cluster_idx) { int64_t next_dts; if (cluster_idx >= track->entry) return 0; if (cluster_idx + 1 == track->entry) next_dts = track->track_duration + track->start_dts; else next_dts = track->cluster[cluster_idx + 1].dts; next_dts -= track->cluster[cluster_idx].dts; av_assert0(next_dts >= 0); av_assert0(next_dts <= INT_MAX); return next_dts; } static int get_samples_per_packet(MOVTrack *track) { int i, first_duration; // return track->par->frame_size; /* use 1 for raw PCM */ if (!track->audio_vbr) return 1; /* check to see if duration is constant for all clusters */ if (!track->entry) return 0; first_duration = get_cluster_duration(track, 0); for (i = 1; i < track->entry; i++) { if (get_cluster_duration(track, i) != first_duration) return 0; } return first_duration; } static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int version = 0; uint32_t tag = track->tag; if (track->mode == MODE_MOV) { if (track->timescale > UINT16_MAX) { if (mov_get_lpcm_flags(track->par->codec_id)) tag = AV_RL32("lpcm"); version = 2; } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id) || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2) { version = 1; } } avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "enca"); } else { avio_wl32(pb, tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */ /* SoundDescription */ avio_wb16(pb, version); /* Version */ avio_wb16(pb, 0); /* Revision level */ avio_wb32(pb, 0); /* Reserved */ if (version == 2) { avio_wb16(pb, 3); avio_wb16(pb, 16); avio_wb16(pb, 0xfffe); avio_wb16(pb, 0); avio_wb32(pb, 0x00010000); avio_wb32(pb, 72); avio_wb64(pb, av_double2int(track->par->sample_rate)); avio_wb32(pb, track->par->channels); avio_wb32(pb, 0x7F000000); avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id)); avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id)); avio_wb32(pb, track->sample_size); avio_wb32(pb, get_samples_per_packet(track)); } else { if (track->mode == MODE_MOV) { avio_wb16(pb, track->par->channels); if (track->par->codec_id == AV_CODEC_ID_PCM_U8 || track->par->codec_id == AV_CODEC_ID_PCM_S8) avio_wb16(pb, 8); /* bits per sample */ else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726) avio_wb16(pb, track->par->bits_per_coded_sample); else avio_wb16(pb, 16); avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */ } else { /* reserved for mp4/3gp */ if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { avio_wb16(pb, track->par->channels); } else { avio_wb16(pb, 2); } if (track->par->codec_id == AV_CODEC_ID_FLAC) { avio_wb16(pb, track->par->bits_per_raw_sample); } else { avio_wb16(pb, 16); } avio_wb16(pb, 0); } avio_wb16(pb, 0); /* packet size (= 0) */ if (track->par->codec_id == AV_CODEC_ID_OPUS) avio_wb16(pb, 48000); else avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ? track->par->sample_rate : 0); avio_wb16(pb, 0); /* Reserved */ } if (version == 1) { /* SoundDescription V1 extended info */ if (mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id)) avio_wb32(pb, 1); /* must be 1 for uncompressed formats */ else avio_wb32(pb, track->par->frame_size); /* Samples per packet */ avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */ avio_wb32(pb, track->sample_size); /* Bytes per frame */ avio_wb32(pb, 2); /* Bytes per sample */ } if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_AAC || track->par->codec_id == AV_CODEC_ID_AC3 || track->par->codec_id == AV_CODEC_ID_EAC3 || track->par->codec_id == AV_CODEC_ID_AMR_NB || track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2 || (mov_pcm_le_gt16(track->par->codec_id) && version==1) || (mov_pcm_be_gt16(track->par->codec_id) && version==1))) mov_write_wave_tag(s, pb, track); else if (track->tag == MKTAG('m','p','4','a')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) mov_write_amr_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AC3) mov_write_ac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_EAC3) mov_write_eac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_ALAC) mov_write_extradata_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) mov_write_wfex_tag(s, pb, track); else if (track->par->codec_id == AV_CODEC_ID_FLAC) mov_write_dfla_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_OPUS) mov_write_dops_tag(pb, track); else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_chan_tag(s, pb, track); if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } return update_size(pb, pos); } static int mov_write_d263_tag(AVIOContext *pb) { avio_wb32(pb, 0xf); /* size */ ffio_wfourcc(pb, "d263"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ /* FIXME use AVCodecContext level/profile, when encoder will set values */ avio_w8(pb, 0xa); /* level */ avio_w8(pb, 0); /* profile */ return 0xf; } static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "avcC"); ff_isom_write_avcc(pb, track->vos_data, track->vos_len); return update_size(pb, pos); } static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "vpcC"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); /* flags */ ff_isom_write_vpcc(s, pb, track->par); return update_size(pb, pos); } static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "hvcC"); if (track->tag == MKTAG('h','v','c','1')) ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1); else ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0); return update_size(pb, pos); } /* also used by all avid codecs (dv, imx, meridien) and their variants */ static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track) { int i; int interlaced; int cid; int display_width = track->par->width; if (track->vos_data && track->vos_len > 0x29) { if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) { /* looks like a DNxHD bit stream */ interlaced = (track->vos_data[5] & 2); cid = AV_RB32(track->vos_data + 0x28); } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n"); return 0; } } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n"); return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "0001"); if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */ track->par->color_range == AVCOL_RANGE_UNSPECIFIED) { avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */ } else { /* Full range (0-255) */ avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */ } avio_wb32(pb, 0); /* unknown */ if (track->tag == MKTAG('A','V','d','h')) { avio_wb32(pb, 32); ffio_wfourcc(pb, "ADHR"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 0); /* unknown */ return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 120); /* size */ ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); /* dnxhd cid, some id ? */ if ( track->par->sample_aspect_ratio.num > 0 && track->par->sample_aspect_ratio.den > 0) display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den; avio_wb32(pb, display_width); /* values below are based on samples created with quicktime and avid codecs */ if (interlaced) { avio_wb32(pb, track->par->height / 2); avio_wb32(pb, 2); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 4); /* unknown */ } else { avio_wb32(pb, track->par->height); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ if (track->par->height == 1080) avio_wb32(pb, 5); /* unknown */ else avio_wb32(pb, 6); /* unknown */ } /* padding */ for (i = 0; i < 10; i++) avio_wb64(pb, 0); return 0; } static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 12); ffio_wfourcc(pb, "DpxE"); if (track->par->extradata_size >= 12 && !memcmp(&track->par->extradata[4], "DpxE", 4)) { avio_wb32(pb, track->par->extradata[11]); } else { avio_wb32(pb, 1); } return 0; } static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (track->par->width == 720) { /* SD */ if (track->par->height == 480) { /* NTSC */ if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n'); else tag = MKTAG('d','v','c',' '); }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p'); else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p'); else tag = MKTAG('d','v','p','p'); } else if (track->par->height == 720) { /* HD 720 line */ if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q'); else tag = MKTAG('d','v','h','p'); } else if (track->par->height == 1080) { /* HD 1080 line */ if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5'); else tag = MKTAG('d','v','h','6'); } else { av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n"); return 0; } return tag; } static AVRational find_fps(AVFormatContext *s, AVStream *st) { AVRational rate = st->avg_frame_rate; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS rate = av_inv_q(st->codec->time_base); if (av_timecode_check_frame_rate(rate) < 0) { av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n", rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den); rate = st->avg_frame_rate; } FF_ENABLE_DEPRECATION_WARNINGS #endif return rate; } static int defined_frame_rate(AVFormatContext *s, AVStream *st) { AVRational rational_framerate = find_fps(s, st); int rate = 0; if (rational_framerate.den != 0) rate = av_q2d(rational_framerate); return rate; } static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('m', '2', 'v', '1'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','4'); else if (rate == 25) tag = MKTAG('x','d','v','5'); else if (rate == 30) tag = MKTAG('x','d','v','1'); else if (rate == 50) tag = MKTAG('x','d','v','a'); else if (rate == 60) tag = MKTAG('x','d','v','9'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','6'); else if (rate == 25) tag = MKTAG('x','d','v','7'); else if (rate == 30) tag = MKTAG('x','d','v','8'); } else { if (rate == 25) tag = MKTAG('x','d','v','3'); else if (rate == 30) tag = MKTAG('x','d','v','2'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','d'); else if (rate == 25) tag = MKTAG('x','d','v','e'); else if (rate == 30) tag = MKTAG('x','d','v','f'); } else { if (rate == 25) tag = MKTAG('x','d','v','c'); else if (rate == 30) tag = MKTAG('x','d','v','b'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','4'); else if (rate == 25) tag = MKTAG('x','d','5','5'); else if (rate == 30) tag = MKTAG('x','d','5','1'); else if (rate == 50) tag = MKTAG('x','d','5','a'); else if (rate == 60) tag = MKTAG('x','d','5','9'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','d'); else if (rate == 25) tag = MKTAG('x','d','5','e'); else if (rate == 30) tag = MKTAG('x','d','5','f'); } else { if (rate == 25) tag = MKTAG('x','d','5','c'); else if (rate == 30) tag = MKTAG('x','d','5','b'); } } } return tag; } static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P10) { if (track->par->width == 960 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','p'); else if (rate == 25) tag = MKTAG('a','i','5','q'); else if (rate == 30) tag = MKTAG('a','i','5','p'); else if (rate == 50) tag = MKTAG('a','i','5','q'); else if (rate == 60) tag = MKTAG('a','i','5','p'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','3'); else if (rate == 25) tag = MKTAG('a','i','5','2'); else if (rate == 30) tag = MKTAG('a','i','5','3'); } else { if (rate == 50) tag = MKTAG('a','i','5','5'); else if (rate == 60) tag = MKTAG('a','i','5','6'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P10) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','p'); else if (rate == 25) tag = MKTAG('a','i','1','q'); else if (rate == 30) tag = MKTAG('a','i','1','p'); else if (rate == 50) tag = MKTAG('a','i','1','q'); else if (rate == 60) tag = MKTAG('a','i','1','p'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','3'); else if (rate == 25) tag = MKTAG('a','i','1','2'); else if (rate == 30) tag = MKTAG('a','i','1','3'); } else { if (rate == 25) tag = MKTAG('a','i','1','5'); else if (rate == 50) tag = MKTAG('a','i','1','5'); else if (rate == 60) tag = MKTAG('a','i','1','6'); } } else if ( track->par->width == 4096 && track->par->height == 2160 || track->par->width == 3840 && track->par->height == 2160 || track->par->width == 2048 && track->par->height == 1080) { tag = MKTAG('a','i','v','x'); } } return tag; } static const struct { enum AVPixelFormat pix_fmt; uint32_t tag; unsigned bps; } mov_pix_fmt_tags[] = { { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 }, { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 }, { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 }, { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 }, { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 }, { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 }, { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 }, { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 }, { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 }, { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 }, { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 }, { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 }, { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 }, { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 }, { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 }, }; static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = MKTAG('A','V','d','n'); if (track->par->profile != FF_PROFILE_UNKNOWN && track->par->profile != FF_PROFILE_DNXHD) tag = MKTAG('A','V','d','h'); return tag; } static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int i; enum AVPixelFormat pix_fmt; for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) { if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) { tag = mov_pix_fmt_tags[i].tag; track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps; if (track->par->codec_tag == mov_pix_fmt_tags[i].tag) break; } } pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov, track->par->bits_per_coded_sample); if (tag == MKTAG('r','a','w',' ') && track->par->format != pix_fmt && track->par->format != AV_PIX_FMT_GRAY8 && track->par->format != AV_PIX_FMT_NONE) av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n", av_get_pix_fmt_name(track->par->format)); return tag; } static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL && (track->par->codec_id == AV_CODEC_ID_DVVIDEO || track->par->codec_id == AV_CODEC_ID_RAWVIDEO || track->par->codec_id == AV_CODEC_ID_H263 || track->par->codec_id == AV_CODEC_ID_H264 || track->par->codec_id == AV_CODEC_ID_DNXHD || track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO || av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio if (track->par->codec_id == AV_CODEC_ID_DVVIDEO) tag = mov_get_dv_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) tag = mov_get_rawvideo_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO) tag = mov_get_mpeg2_xdcam_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_H264) tag = mov_get_h264_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_DNXHD) tag = mov_get_dnxhd_codec_tag(s, track); else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id); if (tag) av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, " "the file may be unplayable!\n"); } } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id); if (ms_tag) { tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff)); av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, " "the file may be unplayable!\n"); } } } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id); } return tag; } static const AVCodecTag codec_cover_image_tags[] = { { AV_CODEC_ID_MJPEG, 0xD }, { AV_CODEC_ID_PNG, 0xE }, { AV_CODEC_ID_BMP, 0x1B }, { AV_CODEC_ID_NONE, 0 }, }; static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (is_cover_image(track->st)) return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id); if (track->mode == MODE_MP4 || track->mode == MODE_PSP) tag = track->par->codec_tag; else if (track->mode == MODE_ISM) tag = track->par->codec_tag; else if (track->mode == MODE_IPOD) { if (!av_match_ext(s->url, "m4a") && !av_match_ext(s->url, "m4v") && !av_match_ext(s->url, "m4b")) av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v " "Quicktime/Ipod might not play the file\n"); tag = track->par->codec_tag; } else if (track->mode & MODE_3GP) tag = track->par->codec_tag; else if (track->mode == MODE_F4V) tag = track->par->codec_tag; else tag = mov_get_codec_tag(s, track); return tag; } /** Write uuid atom. * Needed to make file play in iPods running newest firmware * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1 */ static int mov_write_uuid_tag_ipod(AVIOContext *pb) { avio_wb32(pb, 28); ffio_wfourcc(pb, "uuid"); avio_wb32(pb, 0x6b6840f2); avio_wb32(pb, 0x5f244fc5); avio_wb32(pb, 0xba39a51b); avio_wb32(pb, 0xcf0323f3); avio_wb32(pb, 0x0); return 28; } static const uint16_t fiel_data[] = { 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e }; static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order) { unsigned mov_field_order = 0; if (field_order < FF_ARRAY_ELEMS(fiel_data)) mov_field_order = fiel_data[field_order]; else return 0; avio_wb32(pb, 10); ffio_wfourcc(pb, "fiel"); avio_wb16(pb, mov_field_order); return 10; } static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wl32(pb, track->tag); // store it byteswapped avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_write_esds_tag(pb, track); else if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); return update_size(pb, pos); } static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d) { int8_t stereo_mode; if (stereo_3d->flags != 0) { av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags); return 0; } switch (stereo_3d->type) { case AV_STEREO3D_2D: stereo_mode = 0; break; case AV_STEREO3D_TOPBOTTOM: stereo_mode = 1; break; case AV_STEREO3D_SIDEBYSIDE: stereo_mode = 2; break; default: av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type)); return 0; } avio_wb32(pb, 13); /* size */ ffio_wfourcc(pb, "st3d"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_w8(pb, stereo_mode); return 13; } static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping) { int64_t sv3d_pos, svhd_pos, proj_pos; const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT; if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR && spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE && spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) { av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection); return 0; } sv3d_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sv3d"); svhd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "svhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_put_str(pb, metadata_source); update_size(pb, svhd_pos); proj_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "proj"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "prhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->yaw); avio_wb32(pb, spherical_mapping->pitch); avio_wb32(pb, spherical_mapping->roll); switch (spherical_mapping->projection) { case AV_SPHERICAL_EQUIRECTANGULAR: case AV_SPHERICAL_EQUIRECTANGULAR_TILE: avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "equi"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->bound_top); avio_wb32(pb, spherical_mapping->bound_bottom); avio_wb32(pb, spherical_mapping->bound_left); avio_wb32(pb, spherical_mapping->bound_right); break; case AV_SPHERICAL_CUBEMAP: avio_wb32(pb, 20); /* size */ ffio_wfourcc(pb, "cbmp"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, 0); /* layout */ avio_wb32(pb, spherical_mapping->padding); /* padding */ break; } update_size(pb, proj_pos); return update_size(pb, sv3d_pos); } static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 40); ffio_wfourcc(pb, "clap"); avio_wb32(pb, track->par->width); /* apertureWidth_N */ avio_wb32(pb, 1); /* apertureWidth_D (= 1) */ avio_wb32(pb, track->height); /* apertureHeight_N */ avio_wb32(pb, 1); /* apertureHeight_D (= 1) */ avio_wb32(pb, 0); /* horizOff_N (= 0) */ avio_wb32(pb, 1); /* horizOff_D (= 1) */ avio_wb32(pb, 0); /* vertOff_N (= 0) */ avio_wb32(pb, 1); /* vertOff_D (= 1) */ return 40; } static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track) { AVRational sar; av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num, track->par->sample_aspect_ratio.den, INT_MAX); avio_wb32(pb, 16); ffio_wfourcc(pb, "pasp"); avio_wb32(pb, sar.num); avio_wb32(pb, sar.den); return 16; } static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma) { uint32_t gama = 0; if (gamma <= 0.0) { gamma = avpriv_get_gamma_from_trc(track->par->color_trc); } av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma); if (gamma > 1e-6) { gama = (uint32_t)lrint((double)(1<<16) * gamma); av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama); av_assert0(track->mode == MODE_MOV); avio_wb32(pb, 12); ffio_wfourcc(pb, "gama"); avio_wb32(pb, gama); return 12; } else { av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n"); } return 0; } static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track) { // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9 // Ref (MP4): ISO/IEC 14496-12:2012 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED && track->par->color_trc == AVCOL_TRC_UNSPECIFIED && track->par->color_space == AVCOL_SPC_UNSPECIFIED) { if ((track->par->width >= 1920 && track->par->height >= 1080) || (track->par->width == 1280 && track->par->height == 720)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n"); track->par->color_primaries = AVCOL_PRI_BT709; } else if (track->par->width == 720 && track->height == 576) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n"); track->par->color_primaries = AVCOL_PRI_BT470BG; } else if (track->par->width == 720 && (track->height == 486 || track->height == 480)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n"); track->par->color_primaries = AVCOL_PRI_SMPTE170M; } else { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n"); } switch (track->par->color_primaries) { case AVCOL_PRI_BT709: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_BT709; break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_BT470BG: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_SMPTE170M; break; } } /* We should only ever be called by MOV or MP4. */ av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4); avio_wb32(pb, 18 + (track->mode == MODE_MP4)); ffio_wfourcc(pb, "colr"); if (track->mode == MODE_MP4) ffio_wfourcc(pb, "nclx"); else ffio_wfourcc(pb, "nclc"); switch (track->par->color_primaries) { case AVCOL_PRI_BT709: avio_wb16(pb, 1); break; case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break; case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break; case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break; case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break; default: avio_wb16(pb, 2); } switch (track->par->color_trc) { case AVCOL_TRC_BT709: avio_wb16(pb, 1); break; case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break; case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break; case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break; default: avio_wb16(pb, 2); } switch (track->par->color_space) { case AVCOL_SPC_BT709: avio_wb16(pb, 1); break; case AVCOL_SPC_BT470BG: case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break; case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break; default: avio_wb16(pb, 2); } if (track->mode == MODE_MP4) { int full_range = track->par->color_range == AVCOL_RANGE_JPEG; avio_w8(pb, full_range << 7); return 19; } else { return 18; } } static void find_compressor(char * compressor_name, int len, MOVTrack *track) { AVDictionaryEntry *encoder; int xdcam_res = (track->par->width == 1280 && track->par->height == 720) || (track->par->width == 1440 && track->par->height == 1080) || (track->par->width == 1920 && track->par->height == 1080); if (track->mode == MODE_MOV && (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) { av_strlcpy(compressor_name, encoder->value, 32); } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) { int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(NULL, st); av_strlcatf(compressor_name, len, "XDCAM"); if (track->par->format == AV_PIX_FMT_YUV422P) { av_strlcatf(compressor_name, len, " HD422"); } else if(track->par->width == 1440) { av_strlcatf(compressor_name, len, " HD"); } else av_strlcatf(compressor_name, len, " EX"); av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p'); av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1)); } } static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); char compressor_name[32] = { 0 }; int avid = 0; int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422) || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422) || track->par->codec_id == AV_CODEC_ID_V308 || track->par->codec_id == AV_CODEC_ID_V408 || track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210); avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "encv"); } else { avio_wl32(pb, track->tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (uncompressed_ycbcr) { avio_wb16(pb, 2); /* Codec stream version */ } else { avio_wb16(pb, 0); /* Codec stream version */ } avio_wb16(pb, 0); /* Codec stream revision (=0) */ if (track->mode == MODE_MOV) { ffio_wfourcc(pb, "FFMP"); /* Vendor */ if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) { avio_wb32(pb, 0); /* Temporal Quality */ avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/ } else { avio_wb32(pb, 0x200); /* Temporal Quality = normal */ avio_wb32(pb, 0x200); /* Spatial Quality = normal */ } } else { avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ } avio_wb16(pb, track->par->width); /* Video width */ avio_wb16(pb, track->height); /* Video height */ avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */ avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */ avio_wb32(pb, 0); /* Data size (= 0) */ avio_wb16(pb, 1); /* Frame count (= 1) */ /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */ find_compressor(compressor_name, 32, track); avio_w8(pb, strlen(compressor_name)); avio_write(pb, compressor_name, 31); if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210)) avio_wb16(pb, 0x18); else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample) avio_wb16(pb, track->par->bits_per_coded_sample | (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0)); else avio_wb16(pb, 0x18); /* Reserved */ if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) { int pal_size = 1 << track->par->bits_per_coded_sample; int i; avio_wb16(pb, 0); /* Color table ID */ avio_wb32(pb, 0); /* Color table seed */ avio_wb16(pb, 0x8000); /* Color table flags */ avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */ for (i = 0; i < pal_size; i++) { uint32_t rgb = track->palette[i]; uint16_t r = (rgb >> 16) & 0xff; uint16_t g = (rgb >> 8) & 0xff; uint16_t b = rgb & 0xff; avio_wb16(pb, 0); avio_wb16(pb, (r << 8) | r); avio_wb16(pb, (g << 8) | g); avio_wb16(pb, (b << 8) | b); } } else avio_wb16(pb, 0xffff); /* Reserved */ if (track->tag == MKTAG('m','p','4','v')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H263) mov_write_d263_tag(pb); else if (track->par->codec_id == AV_CODEC_ID_AVUI || track->par->codec_id == AV_CODEC_ID_SVQ3) { mov_write_extradata_tag(pb, track); avio_wb32(pb, 0); } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) { mov_write_avid_tag(pb, track); avid = 1; } else if (track->par->codec_id == AV_CODEC_ID_HEVC) mov_write_hvcc_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) { mov_write_avcc_tag(pb, track); if (track->mode == MODE_IPOD) mov_write_uuid_tag_ipod(pb); } else if (track->par->codec_id == AV_CODEC_ID_VP9) { mov_write_vpcc_tag(mov->fc, pb, track); } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0) mov_write_dvc1_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_VP6F || track->par->codec_id == AV_CODEC_ID_VP6A) { /* Don't write any potential extradata here - the cropping * is signalled via the normal width/height fields. */ } else if (track->par->codec_id == AV_CODEC_ID_R10K) { if (track->par->codec_tag == MKTAG('R','1','0','k')) mov_write_dpxe_tag(pb, track); } else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->par->codec_id != AV_CODEC_ID_H264 && track->par->codec_id != AV_CODEC_ID_MPEG4 && track->par->codec_id != AV_CODEC_ID_DNXHD) { int field_order = track->par->field_order; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN) field_order = track->st->codec->field_order; FF_ENABLE_DEPRECATION_WARNINGS #endif if (field_order != AV_FIELD_UNKNOWN) mov_write_fiel_tag(pb, track, field_order); } if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) { if (track->mode == MODE_MOV) mov_write_gama_tag(pb, track, mov->gamma); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n"); } if (mov->flags & FF_MOV_FLAG_WRITE_COLR) { if (track->mode == MODE_MOV || track->mode == MODE_MP4) mov_write_colr_tag(pb, track); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n"); } if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) { AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL); AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL); if (stereo_3d) mov_write_st3d_tag(pb, stereo_3d); if (spherical_mapping) mov_write_sv3d_tag(mov->fc, pb, spherical_mapping); } if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) { mov_write_pasp_tag(pb, track); } if (uncompressed_ycbcr){ mov_write_clap_tag(pb, track); } if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } /* extra padding for avid stsd */ /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */ if (avid) avio_wb32(pb, 0); return update_size(pb, pos); } static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "rtp "); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb16(pb, 1); /* Hint track version */ avio_wb16(pb, 1); /* Highest compatible version */ avio_wb32(pb, track->max_packet_size); /* Max packet size */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "tims"); avio_wb32(pb, track->timescale); return update_size(pb, pos); } static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name) { uint64_t str_size =strlen(reel_name); int64_t pos = avio_tell(pb); if (str_size >= UINT16_MAX){ av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size); avio_wb16(pb, 0); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "name"); /* Data format */ avio_wb16(pb, str_size); /* string size */ avio_wb16(pb, track->language); /* langcode */ avio_write(pb, reel_name, str_size); /* reel name */ return update_size(pb,pos); } static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); #if 1 int frame_duration; int nb_frames; AVDictionaryEntry *t = NULL; if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) { #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den); nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num); FF_ENABLE_DEPRECATION_WARNINGS #else av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n"); return AVERROR(EINVAL); #endif } else { frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den); nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num); } if (nb_frames > 255) { av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ avio_wb32(pb, 0); /* Flags */ avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */ avio_wb32(pb, track->timescale); /* Timescale */ avio_wb32(pb, frame_duration); /* Frame duration */ avio_w8(pb, nb_frames); /* Number of frames */ avio_w8(pb, 0); /* Reserved */ t = av_dict_get(track->st->metadata, "reel_name", NULL, 0); if (t && utf8len(t->value) && track->mode != MODE_MP4) mov_write_source_reference_tag(pb, track, t->value); else avio_wb16(pb, 0); /* zero size */ #else avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); #endif return update_size(pb, pos); } static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb32(pb, 0); /* Reserved */ return update_size(pb, pos); } static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsd"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_video_tag(pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_audio_tag(s, pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) mov_write_subtitle_tag(pb, track); else if (track->par->codec_tag == MKTAG('r','t','p',' ')) mov_write_rtp_tag(pb, track); else if (track->par->codec_tag == MKTAG('t','m','c','d')) mov_write_tmcd_tag(pb, track); else if (track->par->codec_tag == MKTAG('g','p','m','d')) mov_write_gpmd_tag(pb, track); return update_size(pb, pos); } static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; MOVStts *ctts_entries; uint32_t entries = 0; uint32_t atom_size; int i; ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */ if (!ctts_entries) return AVERROR(ENOMEM); ctts_entries[0].count = 1; ctts_entries[0].duration = track->cluster[0].cts; for (i = 1; i < track->entry; i++) { if (track->cluster[i].cts == ctts_entries[entries].duration) { ctts_entries[entries].count++; /* compress */ } else { entries++; ctts_entries[entries].duration = track->cluster[i].cts; ctts_entries[entries].count = 1; } } entries++; /* last one */ atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "ctts"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, ctts_entries[i].count); avio_wb32(pb, ctts_entries[i].duration); } av_free(ctts_entries); return atom_size; } /* Time to sample atom */ static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track) { MOVStts *stts_entries = NULL; uint32_t entries = -1; uint32_t atom_size; int i; if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) { stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */ if (!stts_entries) return AVERROR(ENOMEM); stts_entries[0].count = track->sample_count; stts_entries[0].duration = 1; entries = 1; } else { if (track->entry) { stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */ if (!stts_entries) return AVERROR(ENOMEM); } for (i = 0; i < track->entry; i++) { int duration = get_cluster_duration(track, i); if (i && duration == stts_entries[entries].duration) { stts_entries[entries].count++; /* compress */ } else { entries++; stts_entries[entries].duration = duration; stts_entries[entries].count = 1; } } entries++; /* last one */ } atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "stts"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, stts_entries[i].count); avio_wb32(pb, stts_entries[i].duration); } av_free(stts_entries); return atom_size; } static int mov_write_dref_tag(AVIOContext *pb) { avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "dref"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ avio_wb32(pb, 0xc); /* size */ //FIXME add the alis and rsrc atom ffio_wfourcc(pb, "url "); avio_wb32(pb, 1); /* version & flags */ return 28; } static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track) { struct sgpd_entry { int count; int16_t roll_distance; int group_description_index; }; struct sgpd_entry *sgpd_entries = NULL; int entries = -1; int group = 0; int i, j; const int OPUS_SEEK_PREROLL_MS = 80; int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS, (AVRational){1, 1000}, (AVRational){1, 48000}); if (!track->entry) return 0; sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries)); if (!sgpd_entries) return AVERROR(ENOMEM); av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC); if (track->par->codec_id == AV_CODEC_ID_OPUS) { for (i = 0; i < track->entry; i++) { int roll_samples_remaining = roll_samples; int distance = 0; for (j = i - 1; j >= 0; j--) { roll_samples_remaining -= get_cluster_duration(track, j); distance++; if (roll_samples_remaining <= 0) break; } /* We don't have enough preceeding samples to compute a valid roll_distance here, so this sample can't be independently decoded. */ if (roll_samples_remaining > 0) distance = 0; /* Verify distance is a minimum of 2 (60ms) packets and a maximum of 32 (2.5ms) packets. */ av_assert0(distance == 0 || (distance >= 2 && distance <= 32)); if (i && distance == sgpd_entries[entries].roll_distance) { sgpd_entries[entries].count++; } else { entries++; sgpd_entries[entries].count = 1; sgpd_entries[entries].roll_distance = distance; sgpd_entries[entries].group_description_index = distance ? ++group : 0; } } } else { entries++; sgpd_entries[entries].count = track->sample_count; sgpd_entries[entries].roll_distance = 1; sgpd_entries[entries].group_description_index = ++group; } entries++; if (!group) { av_free(sgpd_entries); return 0; } /* Write sgpd tag */ avio_wb32(pb, 24 + (group * 2)); /* size */ ffio_wfourcc(pb, "sgpd"); avio_wb32(pb, 1 << 24); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, 2); /* default_length */ avio_wb32(pb, group); /* entry_count */ for (i = 0; i < entries; i++) { if (sgpd_entries[i].group_description_index) { avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */ } } /* Write sbgp tag */ avio_wb32(pb, 20 + (entries * 8)); /* size */ ffio_wfourcc(pb, "sbgp"); avio_wb32(pb, 0); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, entries); /* entry_count */ for (i = 0; i < entries; i++) { avio_wb32(pb, sgpd_entries[i].count); /* sample_count */ avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */ } av_free(sgpd_entries); return 0; } static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stbl"); mov_write_stsd_tag(s, pb, mov, track); mov_write_stts_tag(pb, track); if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_tag == MKTAG('r','t','p',' ')) && track->has_keyframes && track->has_keyframes < track->entry) mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable) mov_write_sdtp_tag(pb, track); if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS) mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->flags & MOV_TRACK_CTTS && track->entry) { if ((ret = mov_write_ctts_tag(s, pb, track)) < 0) return ret; } mov_write_stsc_tag(pb, track); mov_write_stsz_tag(pb, track); mov_write_stco_tag(pb, track); if (track->cenc.aes_ctr) { ff_mov_cenc_write_stbl_atoms(&track->cenc, pb); } if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) { mov_preroll_write_stbl_atoms(pb, track); } return update_size(pb, pos); } static int mov_write_dinf_tag(AVIOContext *pb) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "dinf"); mov_write_dref_tag(pb); return update_size(pb, pos); } static int mov_write_nmhd_tag(AVIOContext *pb) { avio_wb32(pb, 12); ffio_wfourcc(pb, "nmhd"); avio_wb32(pb, 0); return 12; } static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); const char *font = "Lucida Grande"; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* text font */ avio_wb16(pb, 0); /* text face */ avio_wb16(pb, 12); /* text size */ avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */ avio_wb16(pb, 0x0000); /* text color (red) */ avio_wb16(pb, 0x0000); /* text color (green) */ avio_wb16(pb, 0x0000); /* text color (blue) */ avio_wb16(pb, 0xffff); /* background color (red) */ avio_wb16(pb, 0xffff); /* background color (green) */ avio_wb16(pb, 0xffff); /* background color (blue) */ avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */ avio_write(pb, font, strlen(font)); /* font name */ return update_size(pb, pos); } static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gmhd"); avio_wb32(pb, 0x18); /* gmin size */ ffio_wfourcc(pb, "gmin");/* generic media info */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0x40); /* graphics mode = */ avio_wb16(pb, 0x8000); /* opColor (r?) */ avio_wb16(pb, 0x8000); /* opColor (g?) */ avio_wb16(pb, 0x8000); /* opColor (b?) */ avio_wb16(pb, 0); /* balance */ avio_wb16(pb, 0); /* reserved */ /* * This special text atom is required for * Apple Quicktime chapters. The contents * don't appear to be documented, so the * bytes are copied verbatim. */ if (track->tag != MKTAG('c','6','0','8')) { avio_wb32(pb, 0x2C); /* size */ ffio_wfourcc(pb, "text"); avio_wb16(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00004000); avio_wb16(pb, 0x0000); } if (track->par->codec_tag == MKTAG('t','m','c','d')) { int64_t tmcd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); mov_write_tcmi_tag(pb, track); update_size(pb, tmcd_pos); } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { int64_t gpmd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* version */ update_size(pb, gpmd_pos); } return update_size(pb, pos); } static int mov_write_smhd_tag(AVIOContext *pb) { avio_wb32(pb, 16); /* size */ ffio_wfourcc(pb, "smhd"); avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* reserved (balance, normally = 0) */ avio_wb16(pb, 0); /* reserved */ return 16; } static int mov_write_vmhd_tag(AVIOContext *pb) { avio_wb32(pb, 0x14); /* size (always 0x14) */ ffio_wfourcc(pb, "vmhd"); avio_wb32(pb, 0x01); /* version & flags */ avio_wb64(pb, 0); /* reserved (graphics mode = copy) */ return 0x14; } static int is_clcp_track(MOVTrack *track) { return track->tag == MKTAG('c','7','0','8') || track->tag == MKTAG('c','6','0','8'); } static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; const char *hdlr, *descr = NULL, *hdlr_type = NULL; int64_t pos = avio_tell(pb); hdlr = "dhlr"; hdlr_type = "url "; descr = "DataHandler"; if (track) { hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0"; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { hdlr_type = "vide"; descr = "VideoHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { hdlr_type = "soun"; descr = "SoundHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (is_clcp_track(track)) { hdlr_type = "clcp"; descr = "ClosedCaptionHandler"; } else { if (track->tag == MKTAG('t','x','3','g')) { hdlr_type = "sbtl"; } else if (track->tag == MKTAG('m','p','4','s')) { hdlr_type = "subp"; } else { hdlr_type = "text"; } descr = "SubtitleHandler"; } } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) { hdlr_type = "hint"; descr = "HintHandler"; } else if (track->par->codec_tag == MKTAG('t','m','c','d')) { hdlr_type = "tmcd"; descr = "TimeCodeHandler"; } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { hdlr_type = "meta"; descr = "GoPro MET"; // GoPro Metadata } else { av_log(s, AV_LOG_WARNING, "Unknown hldr_type for %s, writing dummy values\n", av_fourcc2str(track->par->codec_tag)); } if (track->st) { // hdlr.name is used by some players to identify the content title // of the track. So if an alternate handler description is // specified, use it. AVDictionaryEntry *t; t = av_dict_get(track->st->metadata, "handler_name", NULL, 0); if (t && utf8len(t->value)) descr = t->value; } } if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */ descr = ""; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); /* Version & flags */ avio_write(pb, hdlr, 4); /* handler */ ffio_wfourcc(pb, hdlr_type); /* handler type */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ if (!track || track->mode == MODE_MOV) avio_w8(pb, strlen(descr)); /* pascal string */ avio_write(pb, descr, strlen(descr)); /* handler description */ if (track && track->mode != MODE_MOV) avio_w8(pb, 0); /* c string */ return update_size(pb, pos); } static int mov_write_hmhd_tag(AVIOContext *pb) { /* This atom must be present, but leaving the values at zero * seems harmless. */ avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "hmhd"); avio_wb32(pb, 0); /* version, flags */ avio_wb16(pb, 0); /* maxPDUsize */ avio_wb16(pb, 0); /* avgPDUsize */ avio_wb32(pb, 0); /* maxbitrate */ avio_wb32(pb, 0); /* avgbitrate */ avio_wb32(pb, 0); /* reserved */ return 28; } static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "minf"); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_vmhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_smhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) { mov_write_gmhd_tag(pb, track); } else { mov_write_nmhd_tag(pb); } } else if (track->tag == MKTAG('r','t','p',' ')) { mov_write_hmhd_tag(pb); } else if (track->tag == MKTAG('t','m','c','d')) { if (track->mode != MODE_MOV) mov_write_nmhd_tag(pb); else mov_write_gmhd_tag(pb, track); } else if (track->tag == MKTAG('g','p','m','d')) { mov_write_gmhd_tag(pb, track); } if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */ mov_write_hdlr_tag(s, pb, NULL); mov_write_dinf_tag(pb); if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int version = track->track_duration < INT32_MAX ? 0 : 1; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, "mdhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */ avio_wb16(pb, track->language); /* language */ avio_wb16(pb, 0); /* reserved (quality) */ if (version != 0 && track->mode == MODE_MOV) { av_log(NULL, AV_LOG_ERROR, "FATAL error, file duration too long for timebase, this file will not be\n" "playable with quicktime. Choose a different timebase or a different\n" "container format\n"); } return 32; } static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "mdia"); mov_write_mdhd_tag(pb, mov, track); mov_write_hdlr_tag(s, pb, track); if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } /* transformation matrix |a b u| |c d v| |tx ty w| */ static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c, int16_t d, int16_t tx, int16_t ty) { avio_wb32(pb, a << 16); /* 16.16 format */ avio_wb32(pb, b << 16); /* 16.16 format */ avio_wb32(pb, 0); /* u in 2.30 format */ avio_wb32(pb, c << 16); /* 16.16 format */ avio_wb32(pb, d << 16); /* 16.16 format */ avio_wb32(pb, 0); /* v in 2.30 format */ avio_wb32(pb, tx << 16); /* 16.16 format */ avio_wb32(pb, ty << 16); /* 16.16 format */ avio_wb32(pb, 1 << 30); /* w in 2.30 format */ } static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int flags = MOV_TKHD_FLAG_IN_MOVIE; int rotation = 0; int group = 0; uint32_t *display_matrix = NULL; int display_matrix_size, i; if (st) { if (mov->per_stream_grouping) group = st->index; else group = st->codecpar->codec_type; display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &display_matrix_size); if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix)) display_matrix = NULL; } if (track->flags & MOV_TRACK_ENABLED) flags |= MOV_TKHD_FLAG_ENABLED; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */ ffio_wfourcc(pb, "tkhd"); avio_w8(pb, version); avio_wb24(pb, flags); if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->track_id); /* track-id */ avio_wb32(pb, 0); /* reserved */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb16(pb, 0); /* layer */ avio_wb16(pb, group); /* alternate group) */ /* Volume, only for audio */ if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_wb16(pb, 0x0100); else avio_wb16(pb, 0); avio_wb16(pb, 0); /* reserved */ /* Matrix structure */ #if FF_API_OLD_ROTATE_API if (st && st->metadata) { AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0); rotation = (rot && rot->value) ? atoi(rot->value) : 0; } #endif if (display_matrix) { for (i = 0; i < 9; i++) avio_wb32(pb, display_matrix[i]); #if FF_API_OLD_ROTATE_API } else if (rotation == 90) { write_matrix(pb, 0, 1, -1, 0, track->par->height, 0); } else if (rotation == 180) { write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height); } else if (rotation == 270) { write_matrix(pb, 0, -1, 1, 0, 0, track->par->width); #endif } else { write_matrix(pb, 1, 0, 0, 1, 0, 0); } /* Track width and height, for visual only */ if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) { int64_t track_width_1616; if (track->mode == MODE_MOV) { track_width_1616 = track->par->width * 0x10000ULL; } else { track_width_1616 = av_rescale(st->sample_aspect_ratio.num, track->par->width * 0x10000LL, st->sample_aspect_ratio.den); if (!track_width_1616 || track->height != track->par->height || track_width_1616 > UINT32_MAX) track_width_1616 = track->par->width * 0x10000ULL; } if (track_width_1616 > UINT32_MAX) { av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n"); track_width_1616 = 0; } avio_wb32(pb, track_width_1616); if (track->height > 0xFFFF) { av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n"); avio_wb32(pb, 0); } else avio_wb32(pb, track->height * 0x10000U); } else { avio_wb32(pb, 0); avio_wb32(pb, 0); } return 0x5c; } static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track) { int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width, track->par->sample_aspect_ratio.den); int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tapt"); avio_wb32(pb, 20); ffio_wfourcc(pb, "clef"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "prof"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "enof"); avio_wb32(pb, 0); avio_wb32(pb, track->par->width << 16); avio_wb32(pb, track->par->height << 16); return update_size(pb, pos); } // This box seems important for the psp playback ... without it the movie seems to hang static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int entry_size, entry_count, size; int64_t delay, start_ct = track->start_cts; int64_t start_dts = track->start_dts; if (track->entry) { if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) { av_log(mov->fc, AV_LOG_DEBUG, "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n", track->cluster[0].dts, track->cluster[0].cts, start_dts, start_ct, track->track_id); start_dts = track->cluster[0].dts; start_ct = track->cluster[0].cts; } } delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN); version |= delay < INT32_MAX ? 0 : 1; entry_size = (version == 1) ? 20 : 12; entry_count = 1 + (delay > 0); size = 24 + entry_count * entry_size; /* write the atom data */ avio_wb32(pb, size); ffio_wfourcc(pb, "edts"); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "elst"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entry_count); if (delay > 0) { /* add an empty edit to delay presentation */ /* In the positive delay case, the delay includes the cts * offset, and the second edit list entry below trims out * the same amount from the actual content. This makes sure * that the offset last sample is included in the edit * list duration as well. */ if (version == 1) { avio_wb64(pb, delay); avio_wb64(pb, -1); } else { avio_wb32(pb, delay); avio_wb32(pb, -1); } avio_wb32(pb, 0x00010000); } else { /* Avoid accidentally ending up with start_ct = -1 which has got a * special meaning. Normally start_ct should end up positive or zero * here, but use FFMIN in case dts is a small positive integer * rounded to 0 when represented in MOV_TIMESCALE units. */ av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0); start_ct = -FFMIN(start_dts, 0); /* Note, this delay is calculated from the pts of the first sample, * ensuring that we don't reduce the duration for cases with * dts<0 pts=0. */ duration += delay; } /* For fragmented files, we don't know the full length yet. Setting * duration to 0 allows us to only specify the offset, including * the rest of the content (from all future fragments) without specifying * an explicit duration. */ if (mov->flags & FF_MOV_FLAG_FRAGMENT) duration = 0; /* duration */ if (version == 1) { avio_wb64(pb, duration); avio_wb64(pb, start_ct); } else { avio_wb32(pb, duration); avio_wb32(pb, start_ct); } avio_wb32(pb, 0x00010000); return size; } static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 20); // size ffio_wfourcc(pb, "tref"); avio_wb32(pb, 12); // size (subatom) avio_wl32(pb, track->tref_tag); avio_wb32(pb, track->tref_id); return 20; } // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it) static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov) { avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x1c); // another size here! ffio_wfourcc(pb, "MTDT"); avio_wb32(pb, 0x00010012); avio_wb32(pb, 0x0a); avio_wb32(pb, 0x55c40000); avio_wb32(pb, 0x1); avio_wb32(pb, 0x0); return 0x34; } static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track) { AVFormatContext *ctx = track->rtp_ctx; char buf[1000] = ""; int len; ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track, NULL, NULL, 0, 0, ctx); av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id); len = strlen(buf); avio_wb32(pb, len + 24); ffio_wfourcc(pb, "udta"); avio_wb32(pb, len + 16); ffio_wfourcc(pb, "hnti"); avio_wb32(pb, len + 8); ffio_wfourcc(pb, "sdp "); avio_write(pb, buf, len); return len + 24; } static int mov_write_track_metadata(AVIOContext *pb, AVStream *st, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */ return update_size(pb, pos); } static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVStream *st) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; if (!st) return 0; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & (MODE_MP4|MODE_MOV)) mov_write_track_metadata(pb_buf, st, "name", "title"); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t pos = avio_tell(pb); int entry_backup = track->entry; int chunk_backup = track->chunkCount; int ret; /* If we want to have an empty moov, but some samples already have been * buffered (delay_moov), pretend that no samples have been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) track->chunkCount = track->entry = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "trak"); mov_write_tkhd_tag(pb, mov, track, st); av_assert2(mov->use_editlist >= 0); if (track->start_dts != AV_NOPTS_VALUE) { if (mov->use_editlist) mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track)) av_log(mov->fc, AV_LOG_WARNING, "Not writing any edit list even though one would have been required\n"); } if (track->tref_tag) mov_write_tref_tag(pb, track); if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0) return ret; if (track->mode == MODE_PSP) mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box if (track->tag == MKTAG('r','t','p',' ')) mov_write_udta_sdp(pb, track); if (track->mode == MODE_MOV) { if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio); if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) { mov_write_tapt_tag(pb, track); } } if (is_clcp_track(track) && st->sample_aspect_ratio.num) { mov_write_tapt_tag(pb, track); } } mov_write_track_udta_tag(pb, mov, st); track->entry = entry_backup; track->chunkCount = chunk_backup; return update_size(pb, pos); } static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov) { int i, has_audio = 0, has_video = 0; int64_t pos = avio_tell(pb); int audio_profile = mov->iods_audio_profile; int video_profile = mov->iods_video_profile; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO; has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO; } } if (audio_profile < 0) audio_profile = 0xFF - has_audio; if (video_profile < 0) video_profile = 0xFF - has_video; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "iods"); avio_wb32(pb, 0); /* version & flags */ put_descr(pb, 0x10, 7); avio_wb16(pb, 0x004f); avio_w8(pb, 0xff); avio_w8(pb, 0xff); avio_w8(pb, audio_profile); avio_w8(pb, video_profile); avio_w8(pb, 0xff); return update_size(pb, pos); } static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x20); /* size */ ffio_wfourcc(pb, "trex"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->track_id); /* track ID */ avio_wb32(pb, 1); /* default sample description index */ avio_wb32(pb, 0); /* default sample duration */ avio_wb32(pb, 0); /* default sample size */ avio_wb32(pb, 0); /* default sample flags */ return 0; } static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "mvex"); for (i = 0; i < mov->nb_streams; i++) mov_write_trex_tag(pb, &mov->tracks[i]); return update_size(pb, pos); } static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov) { int max_track_id = 1, i; int64_t max_track_len = 0; int version; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) { int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration, MOV_TIMESCALE, mov->tracks[i].timescale, AV_ROUND_UP); if (max_track_len < max_track_len_temp) max_track_len = max_track_len_temp; if (max_track_id < mov->tracks[i].track_id) max_track_id = mov->tracks[i].track_id; } } /* If using delay_moov, make sure the output is the same as if no * samples had been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { max_track_len = 0; max_track_id = 1; } version = max_track_len < UINT32_MAX ? 0 : 1; avio_wb32(pb, version == 1 ? 120 : 108); /* size */ ffio_wfourcc(pb, "mvhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, mov->time); avio_wb64(pb, mov->time); } else { avio_wb32(pb, mov->time); /* creation time */ avio_wb32(pb, mov->time); /* modification time */ } avio_wb32(pb, MOV_TIMESCALE); (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */ avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */ avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */ avio_wb16(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ /* Matrix structure */ write_matrix(pb, 1, 0, 0, 1, 0, 0); avio_wb32(pb, 0); /* reserved (preview time) */ avio_wb32(pb, 0); /* reserved (preview duration) */ avio_wb32(pb, 0); /* reserved (poster time) */ avio_wb32(pb, 0); /* reserved (selection time) */ avio_wb32(pb, 0); /* reserved (selection duration) */ avio_wb32(pb, 0); /* reserved (current time) */ avio_wb32(pb, max_track_id + 1); /* Next track id */ return 0x6c; } static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdir"); ffio_wfourcc(pb, "appl"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } /* helper function to write a data tag with the specified string as data */ static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style) { if (long_style) { int size = 16 + strlen(data); avio_wb32(pb, size); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 1); avio_wb32(pb, 0); avio_write(pb, data, strlen(data)); return size; } else { if (!lang) lang = ff_mov_iso639_to_lang("und", 1); avio_wb16(pb, strlen(data)); /* string length */ avio_wb16(pb, lang); avio_write(pb, data, strlen(data)); return strlen(data) + 4; } } static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style) { int size = 0; if (value && value[0]) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, name); mov_write_string_data_tag(pb, value, lang, long_style); size = update_size(pb, pos); } return size; } static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s, const char *tag, int *lang) { int l, len, len2; AVDictionaryEntry *t, *t2 = NULL; char tag2[16]; *lang = 0; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return NULL; len = strlen(t->key); snprintf(tag2, sizeof(tag2), "%s-", tag); while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) { len2 = strlen(t2->key); if (len2 == len + 4 && !strcmp(t->value, t2->value) && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) { *lang = l; return t; } } return t; } static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int long_style) { int lang; AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang); if (!t) return 0; return mov_write_string_tag(pb, name, t->value, lang, long_style); } /* iTunes bpm number */ static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0); int size = 0, tmpo = t ? atoi(t->value) : 0; if (tmpo) { size = 26; avio_wb32(pb, size); ffio_wfourcc(pb, "tmpo"); avio_wb32(pb, size-8); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); //type specifier avio_wb32(pb, 0); avio_wb16(pb, tmpo); // data } return size; } /* 3GPP TS 26.244 */ static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb) { int lang; int64_t pos = avio_tell(pb); double latitude, longitude, altitude; int32_t latitude_fix, longitude_fix, altitude_fix; AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang); const char *ptr, *place = ""; char *end; static const char *astronomical_body = "earth"; if (!t) return 0; ptr = t->value; longitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; latitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; altitude = strtod(ptr, &end); /* If no altitude was present, the default 0 should be fine */ if (*end == '/') place = end + 1; latitude_fix = (int32_t) ((1 << 16) * latitude); longitude_fix = (int32_t) ((1 << 16) * longitude); altitude_fix = (int32_t) ((1 << 16) * altitude); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "loci"); /* type */ avio_wb32(pb, 0); /* version + flags */ avio_wb16(pb, lang); avio_write(pb, place, strlen(place) + 1); avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */ avio_wb32(pb, latitude_fix); avio_wb32(pb, longitude_fix); avio_wb32(pb, altitude_fix); avio_write(pb, astronomical_body, strlen(astronomical_body) + 1); avio_w8(pb, 0); /* additional notes, null terminated string */ return update_size(pb, pos); } /* iTunes track or disc number */ static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s, int disc) { AVDictionaryEntry *t = av_dict_get(s->metadata, disc ? "disc" : "track", NULL, 0); int size = 0, track = t ? atoi(t->value) : 0; if (track) { int tracks = 0; char *slash = strchr(t->value, '/'); if (slash) tracks = atoi(slash + 1); avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, disc ? "disk" : "trkn"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0); // 8 bytes empty avio_wb32(pb, 0); avio_wb16(pb, 0); // empty avio_wb16(pb, track); // track / disc number avio_wb16(pb, tracks); // total track / disc number avio_wb16(pb, 0); // empty size = 32; } return size; } static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int len) { AVDictionaryEntry *t = NULL; uint8_t num; int size = 24 + len; if (len != 1 && len != 4) return -1; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return 0; num = atoi(t->value); avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); avio_wb32(pb, 0); if (len==4) avio_wb32(pb, num); else avio_w8 (pb, num); return size; } static int mov_write_covr(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = 0; int i; for (i = 0; i < s->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (!is_cover_image(trk->st) || trk->cover_image.size <= 0) continue; if (!pos) { pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "covr"); } avio_wb32(pb, 16 + trk->cover_image.size); ffio_wfourcc(pb, "data"); avio_wb32(pb, trk->tag); avio_wb32(pb , 0); avio_write(pb, trk->cover_image.data, trk->cover_image.size); } return pos ? update_size(pb, pos) : 0; } /* iTunes meta data list */ static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); mov_write_string_metadata(s, pb, "\251nam", "title" , 1); mov_write_string_metadata(s, pb, "\251ART", "artist" , 1); mov_write_string_metadata(s, pb, "aART", "album_artist", 1); mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1); mov_write_string_metadata(s, pb, "\251alb", "album" , 1); mov_write_string_metadata(s, pb, "\251day", "date" , 1); if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) { if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1); } mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1); mov_write_string_metadata(s, pb, "\251gen", "genre" , 1); mov_write_string_metadata(s, pb, "cprt", "copyright", 1); mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1); mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1); mov_write_string_metadata(s, pb, "desc", "description",1); mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1); mov_write_string_metadata(s, pb, "tvsh", "show" , 1); mov_write_string_metadata(s, pb, "tven", "episode_id",1); mov_write_string_metadata(s, pb, "tvnn", "network" , 1); mov_write_string_metadata(s, pb, "keyw", "keywords" , 1); mov_write_int8_metadata (s, pb, "tves", "episode_sort",4); mov_write_int8_metadata (s, pb, "tvsn", "season_number",4); mov_write_int8_metadata (s, pb, "stik", "media_type",1); mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1); mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1); mov_write_int8_metadata (s, pb, "cpil", "compilation", 1); mov_write_covr(pb, s); mov_write_trkn_tag(pb, mov, s, 0); // track number mov_write_trkn_tag(pb, mov, s, 1); // disc number mov_write_tmpo_tag(pb, s); return update_size(pb, pos); } static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdta"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int64_t curpos, entry_pos; int count = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "keys"); avio_wb32(pb, 0); entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* entry count */ while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { avio_wb32(pb, strlen(t->key) + 8); ffio_wfourcc(pb, "mdta"); avio_write(pb, t->key, strlen(t->key)); count += 1; } curpos = avio_tell(pb); avio_seek(pb, entry_pos, SEEK_SET); avio_wb32(pb, count); // rewrite entry count avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int count = 1; /* keys are 1-index based */ avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { int64_t entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wb32(pb, count); /* key */ mov_write_string_data_tag(pb, t->value, 0, 1); update_size(pb, entry_pos); count += 1; } return update_size(pb, pos); } /* meta data tags */ static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int size = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "meta"); avio_wb32(pb, 0); if (mov->flags & FF_MOV_FLAG_USE_MDTA) { mov_write_mdta_hdlr_tag(pb, mov, s); mov_write_mdta_keys_tag(pb, mov, s); mov_write_mdta_ilst_tag(pb, mov, s); } else { /* iTunes metadata tag */ mov_write_itunes_hdlr_tag(pb, mov, s); mov_write_ilst_tag(pb, mov, s); } size = update_size(pb, pos); return size; } static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb, const char *name, const char *key) { int len; AVDictionaryEntry *t; if (!(t = av_dict_get(s->metadata, key, NULL, 0))) return 0; len = strlen(t->value); if (len > 0) { int size = len + 8; avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_write(pb, t->value, len); return size; } return 0; } static int ascii_to_wc(AVIOContext *pb, const uint8_t *b) { int val; while (*b) { GET_UTF8(val, *b++, return -1;) avio_wb16(pb, val); } avio_wb16(pb, 0x00); return 0; } static uint16_t language_code(const char *str) { return (((str[0] - 0x60) & 0x1F) << 10) + (((str[1] - 0x60) & 0x1F) << 5) + (( str[2] - 0x60) & 0x1F); } static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_wb32(pb, 0); /* version + flags */ if (!strcmp(tag, "yrrc")) avio_wb16(pb, atoi(t->value)); else { avio_wb16(pb, language_code("eng")); /* language */ avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */ if (!strcmp(tag, "albm") && (t = av_dict_get(s->metadata, "track", NULL, 0))) avio_w8(pb, atoi(t->value)); } return update_size(pb, pos); } static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i, nb_chapters = FFMIN(s->nb_chapters, 255); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "chpl"); avio_wb32(pb, 0x01000000); // version + flags avio_wb32(pb, 0); // unknown avio_w8(pb, nb_chapters); for (i = 0; i < nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000})); if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { int len = FFMIN(strlen(t->value), 255); avio_w8(pb, len); avio_write(pb, t->value, len); } else avio_w8(pb, 0); } return update_size(pb, pos); } static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & MODE_3GP) { mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist"); mov_write_3gp_udta_tag(pb_buf, s, "titl", "title"); mov_write_3gp_udta_tag(pb_buf, s, "auth", "author"); mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre"); mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment"); mov_write_3gp_udta_tag(pb_buf, s, "albm", "album"); mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright"); mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date"); mov_write_loci_tag(s, pb_buf); } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0); mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0); mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0); mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0); mov_write_string_metadata(s, pb_buf, "\251day", "date", 0); mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0); // currently ignored by mov.c mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0); // add support for libquicktime, this atom is also actually read by mov.c mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0); mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0); mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0); mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0); mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0); mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0); mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0); mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp"); } else { /* iTunes meta data */ mov_write_meta_tag(pb_buf, mov, s); mov_write_loci_tag(s, pb_buf); } if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL)) mov_write_chpl_tag(pb_buf, s); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static void mov_write_psp_udta_tag(AVIOContext *pb, const char *str, const char *lang, int type) { int len = utf8len(str) + 1; if (len <= 0) return; avio_wb16(pb, len * 2 + 10); /* size */ avio_wb32(pb, type); /* type */ avio_wb16(pb, language_code(lang)); /* language */ avio_wb16(pb, 0x01); /* ? */ ascii_to_wc(pb, str); } static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0); int64_t pos, pos2; if (title) { pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); pos2 = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "MTDT"); avio_wb16(pb, 4); // ? avio_wb16(pb, 0x0C); /* size */ avio_wb32(pb, 0x0B); /* type */ avio_wb16(pb, language_code("und")); /* language */ avio_wb16(pb, 0x0); /* ? */ avio_wb16(pb, 0x021C); /* data */ if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04); mov_write_psp_udta_tag(pb, title->value, "eng", 0x01); mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03); update_size(pb, pos2); return update_size(pb, pos); } return 0; } static void build_chunks(MOVTrack *trk) { int i; MOVIentry *chunk = &trk->cluster[0]; uint64_t chunkSize = chunk->size; chunk->chunkNum = 1; if (trk->chunkCount) return; trk->chunkCount = 1; for (i = 1; i<trk->entry; i++){ if (chunk->pos + chunkSize == trk->cluster[i].pos && chunkSize + trk->cluster[i].size < (1<<20)){ chunkSize += trk->cluster[i].size; chunk->samples_in_chunk += trk->cluster[i].entries; } else { trk->cluster[i].chunkNum = chunk->chunkNum+1; chunk=&trk->cluster[i]; chunkSize = chunk->size; trk->chunkCount++; } } } /** * Assign track ids. If option "use_stream_ids_as_track_ids" is set, * the stream ids are used as track ids. * * This assumes mov->tracks and s->streams are in the same order and * there are no gaps in either of them (so mov->tracks[n] refers to * s->streams[n]). * * As an exception, there can be more entries in * s->streams than in mov->tracks, in which case new track ids are * generated (starting after the largest found stream id). */ static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s) { int i; if (mov->track_ids_ok) return 0; if (mov->use_stream_ids_as_track_ids) { int next_generated_track_id = 0; for (i = 0; i < s->nb_streams; i++) { if (s->streams[i]->id > next_generated_track_id) next_generated_track_id = s->streams[i]->id; } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id; } } else { for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i + 1; } } mov->track_ids_ok = 1; return 0; } static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int i; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "moov"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].time = mov->time; if (mov->tracks[i].entry) build_chunks(&mov->tracks[i]); } if (mov->chapter_track) for (i = 0; i < s->nb_streams; i++) { mov->tracks[i].tref_tag = MKTAG('c','h','a','p'); mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->tag == MKTAG('r','t','p',' ')) { track->tref_tag = MKTAG('h','i','n','t'); track->tref_id = mov->tracks[track->src_track].track_id; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { int * fallback, size; fallback = (int*)av_stream_get_side_data(track->st, AV_PKT_DATA_FALLBACK_TRACK, &size); if (fallback != NULL && size == sizeof(int)) { if (*fallback >= 0 && *fallback < mov->nb_streams) { track->tref_tag = MKTAG('f','a','l','l'); track->tref_id = mov->tracks[*fallback].track_id; } } } } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('t','m','c','d')) { int src_trk = mov->tracks[i].src_track; mov->tracks[src_trk].tref_tag = mov->tracks[i].tag; mov->tracks[src_trk].tref_id = mov->tracks[i].track_id; //src_trk may have a different timescale than the tmcd track mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration, mov->tracks[i].timescale, mov->tracks[src_trk].timescale); } } mov_write_mvhd_tag(pb, mov); if (mov->mode != MODE_MOV && !mov->iods_skip) mov_write_iods_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL); if (ret < 0) return ret; } } if (mov->flags & FF_MOV_FLAG_FRAGMENT) mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */ if (mov->mode == MODE_PSP) mov_write_uuidusmt_tag(pb, s); else mov_write_udta_tag(pb, mov, s); return update_size(pb, pos); } static void param_write_int(AVIOContext *pb, const char *name, int value) { avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value); } static void param_write_string(AVIOContext *pb, const char *name, const char *value) { avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value); } static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len) { char buf[150]; len = FFMIN(sizeof(buf) / 2 - 1, len); ff_data_to_hex(buf, value, len, 0); buf[2 * len] = '\0'; avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf); } static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i; int64_t manifest_bit_rate = 0; AVCPBProperties *props = NULL; static const uint8_t uuid[] = { 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd, 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }; avio_wb32(pb, 0); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_wb32(pb, 0); avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n"); avio_printf(pb, "<head>\n"); if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT)) avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n", LIBAVFORMAT_IDENT); avio_printf(pb, "</head>\n"); avio_printf(pb, "<body>\n"); avio_printf(pb, "<switch>\n"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; const char *type; int track_id = track->track_id; char track_name_buf[32] = { 0 }; AVStream *st = track->st; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) { type = "video"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { type = "audio"; } else { continue; } props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); if (track->par->bit_rate) { manifest_bit_rate = track->par->bit_rate; } else if (props) { manifest_bit_rate = props->max_bitrate; } avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type, manifest_bit_rate); param_write_int(pb, "systemBitrate", manifest_bit_rate); param_write_int(pb, "trackID", track_id); param_write_string(pb, "systemLanguage", lang ? lang->value : "und"); /* Build track name piece by piece: */ /* 1. track type */ av_strlcat(track_name_buf, type, sizeof(track_name_buf)); /* 2. track language, if available */ if (lang) av_strlcatf(track_name_buf, sizeof(track_name_buf), "_%s", lang->value); /* 3. special type suffix */ /* "_cc" = closed captions, "_ad" = audio_description */ if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf)); else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED) av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf)); param_write_string(pb, "trackName", track_name_buf); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->par->codec_id == AV_CODEC_ID_H264) { uint8_t *ptr; int size = track->par->extradata_size; if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr, &size)) { param_write_hex(pb, "CodecPrivateData", ptr ? ptr : track->par->extradata, size); av_free(ptr); } param_write_string(pb, "FourCC", "H264"); } else if (track->par->codec_id == AV_CODEC_ID_VC1) { param_write_string(pb, "FourCC", "WVC1"); param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); } param_write_int(pb, "MaxWidth", track->par->width); param_write_int(pb, "MaxHeight", track->par->height); param_write_int(pb, "DisplayWidth", track->par->width); param_write_int(pb, "DisplayHeight", track->par->height); } else { if (track->par->codec_id == AV_CODEC_ID_AAC) { switch (track->par->profile) { case FF_PROFILE_AAC_HE_V2: param_write_string(pb, "FourCC", "AACP"); break; case FF_PROFILE_AAC_HE: param_write_string(pb, "FourCC", "AACH"); break; default: param_write_string(pb, "FourCC", "AACL"); } } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) { param_write_string(pb, "FourCC", "WMAP"); } param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id)); param_write_int(pb, "Channels", track->par->channels); param_write_int(pb, "SamplingRate", track->par->sample_rate); param_write_int(pb, "BitsPerSample", 16); param_write_int(pb, "PacketSize", track->par->block_align ? track->par->block_align : 4); } avio_printf(pb, "</%s>\n", type); } avio_printf(pb, "</switch>\n"); avio_printf(pb, "</body>\n"); avio_printf(pb, "</smil>\n"); return update_size(pb, pos); } static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 16); ffio_wfourcc(pb, "mfhd"); avio_wb32(pb, 0); avio_wb32(pb, mov->fragments); return 0; } static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry) { return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO : (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC); } static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET; if (!track->entry) { flags |= MOV_TFHD_DURATION_IS_EMPTY; } else { flags |= MOV_TFHD_DEFAULT_FLAGS; } if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET) flags &= ~MOV_TFHD_BASE_DATA_OFFSET; if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) { flags &= ~MOV_TFHD_BASE_DATA_OFFSET; flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF; } /* Don't set a default sample size, the silverlight player refuses * to play files with that set. Don't set a default sample duration, * WMP freaks out if it is set. Don't set a base data offset, PIFF * file format says it MUST NOT be set. */ if (track->mode == MODE_ISM) flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET); avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfhd"); avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, track->track_id); /* track-id */ if (flags & MOV_TFHD_BASE_DATA_OFFSET) avio_wb64(pb, moof_offset); if (flags & MOV_TFHD_DEFAULT_DURATION) { track->default_duration = get_cluster_duration(track, 0); avio_wb32(pb, track->default_duration); } if (flags & MOV_TFHD_DEFAULT_SIZE) { track->default_size = track->entry ? track->cluster[0].size : 1; avio_wb32(pb, track->default_size); } else track->default_size = -1; if (flags & MOV_TFHD_DEFAULT_FLAGS) { /* Set the default flags based on the second sample, if available. * If the first sample is different, that can be signaled via a separate field. */ if (track->entry > 1) track->default_sample_flags = get_sample_flags(track, &track->cluster[1]); else track->default_sample_flags = track->par->codec_type == AVMEDIA_TYPE_VIDEO ? (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) : MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO; avio_wb32(pb, track->default_sample_flags); } return update_size(pb, pos); } static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int moof_size, int first, int end) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TRUN_DATA_OFFSET; int i; for (i = first; i < end; i++) { if (get_cluster_duration(track, i) != track->default_duration) flags |= MOV_TRUN_SAMPLE_DURATION; if (track->cluster[i].size != track->default_size) flags |= MOV_TRUN_SAMPLE_SIZE; if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags) flags |= MOV_TRUN_SAMPLE_FLAGS; } if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 && get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags) flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS; if (track->flags & MOV_TRACK_CTTS) flags |= MOV_TRUN_SAMPLE_CTS; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "trun"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, end - first); /* sample count */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) && !mov->first_trun) avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */ else avio_wb32(pb, moof_size + 8 + track->data_offset + track->cluster[first].pos); /* data offset */ if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[first])); for (i = first; i < end; i++) { if (flags & MOV_TRUN_SAMPLE_DURATION) avio_wb32(pb, get_cluster_duration(track, i)); if (flags & MOV_TRUN_SAMPLE_SIZE) avio_wb32(pb, track->cluster[i].size); if (flags & MOV_TRUN_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[i])); if (flags & MOV_TRUN_SAMPLE_CTS) avio_wb32(pb, track->cluster[i].cts); } mov->first_trun = 0; return update_size(pb, pos); } static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); static const uint8_t uuid[] = { 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6, 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2 }; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_wb64(pb, track->start_dts + track->frag_start + track->cluster[0].cts); avio_wb64(pb, track->end_pts - (track->cluster[0].dts + track->cluster[0].cts)); return update_size(pb, pos); } static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int entry) { int n = track->nb_frag_info - 1 - entry, i; int size = 8 + 16 + 4 + 1 + 16*n; static const uint8_t uuid[] = { 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95, 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f }; if (entry < 0) return 0; avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET); avio_wb32(pb, size); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_w8(pb, n); for (i = 0; i < n; i++) { int index = entry + 1 + i; avio_wb64(pb, track->frag_info[index].time); avio_wb64(pb, track->frag_info[index].duration); } if (n < mov->ism_lookahead) { int free_size = 16 * (mov->ism_lookahead - n); avio_wb32(pb, free_size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, free_size - 8); } return 0; } static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; for (i = 0; i < mov->ism_lookahead; i++) { /* Update the tfrf tag for the last ism_lookahead fragments, * nb_frag_info - 1 is the next fragment to be written. */ mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i); } avio_seek(pb, pos, SEEK_SET); return 0; } static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks, int size) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; MOVFragmentInfo *info; if ((tracks >= 0 && i != tracks) || !track->entry) continue; track->nb_frag_info++; if (track->nb_frag_info >= track->frag_info_capacity) { unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT; if (av_reallocp_array(&track->frag_info, new_capacity, sizeof(*track->frag_info))) return AVERROR(ENOMEM); track->frag_info_capacity = new_capacity; } info = &track->frag_info[track->nb_frag_info - 1]; info->offset = avio_tell(pb); info->size = size; // Try to recreate the original pts for the first packet // from the fields we have stored info->time = track->start_dts + track->frag_start + track->cluster[0].cts; info->duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); // If the pts is less than zero, we will have trimmed // away parts of the media track using an edit list, // and the corresponding start presentation time is zero. if (info->time < 0) { info->duration += info->time; info->time = 0; } info->tfrf_offset = 0; mov_write_tfrf_tags(pb, mov, track); } return 0; } static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if ((tracks >= 0 && i != tracks) || !track->entry) continue; if (track->nb_frag_info > max) { memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info)); track->nb_frag_info = max; } } } static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tfdt"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb64(pb, track->frag_start); return update_size(pb, pos); } static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset, int moof_size) { int64_t pos = avio_tell(pb); int i, start = 0; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "traf"); mov_write_tfhd_tag(pb, mov, track, moof_offset); if (mov->mode != MODE_ISM) mov_write_tfdt_tag(pb, track); for (i = 1; i < track->entry; i++) { if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) { mov_write_trun_tag(pb, mov, track, moof_size, start, i); start = i; } } mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry); if (mov->mode == MODE_ISM) { mov_write_tfxd_tag(pb, track); if (mov->ism_lookahead) { int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead; if (track->nb_frag_info > 0) { MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1]; if (!info->tfrf_offset) info->tfrf_offset = avio_tell(pb); } avio_wb32(pb, 8 + size); ffio_wfourcc(pb, "free"); for (i = 0; i < size; i++) avio_w8(pb, 0); } } return update_size(pb, pos); } static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov, int tracks, int moof_size) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "moof"); mov->first_trun = 1; mov_write_mfhd_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; if (!track->entry) continue; mov_write_traf_tag(pb, mov, track, pos, moof_size); } return update_size(pb, pos); } static int mov_write_sidx_tag(AVIOContext *pb, MOVTrack *track, int ref_size, int total_sidx_size) { int64_t pos = avio_tell(pb), offset_pos, end_pos; int64_t presentation_time, duration, offset; int starts_with_SAP, i, entries; if (track->entry) { entries = 1; presentation_time = track->start_dts + track->frag_start + track->cluster[0].cts; duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE; // pts<0 should be cut away using edts if (presentation_time < 0) { duration += presentation_time; presentation_time = 0; } } else { entries = track->nb_frag_info; if (entries <= 0) return 0; presentation_time = track->frag_info[0].time; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sidx"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); /* reference_ID */ avio_wb32(pb, track->timescale); /* timescale */ avio_wb64(pb, presentation_time); /* earliest_presentation_time */ offset_pos = avio_tell(pb); avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */ avio_wb16(pb, 0); /* reserved */ avio_wb16(pb, entries); /* reference_count */ for (i = 0; i < entries; i++) { if (!track->entry) { if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) { av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n"); } duration = track->frag_info[i].duration; ref_size = track->frag_info[i].size; starts_with_SAP = 1; } avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */ avio_wb32(pb, duration); /* subsegment_duration */ avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */ } end_pos = avio_tell(pb); offset = pos + total_sidx_size - end_pos; avio_seek(pb, offset_pos, SEEK_SET); avio_wb64(pb, offset); avio_seek(pb, end_pos, SEEK_SET); return update_size(pb, pos); } static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov, int tracks, int ref_size) { int i, round, ret; AVIOContext *avio_buf; int total_size = 0; for (round = 0; round < 2; round++) { // First run one round to calculate the total size of all // sidx atoms. // This would be much simpler if we'd only write one sidx // atom, for the first track in the moof. if (round == 0) { if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; } else { avio_buf = pb; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; // When writing a sidx for the full file, entry is 0, but // we want to include all tracks. ref_size is 0 in this case, // since we read it from frag_info instead. if (!track->entry && ref_size > 0) continue; total_size -= mov_write_sidx_tag(avio_buf, track, ref_size, total_size); } if (round == 0) total_size = ffio_close_null_buf(avio_buf); } return 0; } static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks) { int64_t pos = avio_tell(pb), pts_us, ntp_ts; MOVTrack *first_track; /* PRFT should be associated with at most one track. So, choosing only the * first track. */ if (tracks > 0) return 0; first_track = &(mov->tracks[0]); if (!first_track->entry) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n"); return 0; } if (first_track->cluster[0].pts == AV_NOPTS_VALUE) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n"); return 0; } if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) { ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time()); } else if (mov->write_prft == MOV_PRFT_SRC_PTS) { pts_us = av_rescale_q(first_track->cluster[0].pts, first_track->st->time_base, AV_TIME_BASE_Q); ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US); } else { av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n", mov->write_prft); return 0; } avio_wb32(pb, 0); // Size place holder ffio_wfourcc(pb, "prft"); // Type avio_w8(pb, 1); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, first_track->track_id); // reference track ID avio_wb64(pb, ntp_ts); // NTP time stamp avio_wb64(pb, first_track->cluster[0].pts); //media time return update_size(pb, pos); } static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks, int64_t mdat_size) { AVIOContext *avio_buf; int ret, moof_size; if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; mov_write_moof_tag_internal(avio_buf, mov, tracks, 0); moof_size = ffio_close_null_buf(avio_buf); if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size); if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB) mov_write_prft_tag(pb, mov, tracks); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX || !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) || mov->ism_lookahead) { if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0) return ret; if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) && mov->flags & FF_MOV_FLAG_SKIP_TRAILER) { mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1); } } return mov_write_moof_tag_internal(pb, mov, tracks, moof_size); } static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfra"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); avio_wb32(pb, 0); /* length of traf/trun/sample num */ avio_wb32(pb, track->nb_frag_info); for (i = 0; i < track->nb_frag_info; i++) { avio_wb64(pb, track->frag_info[i].time); avio_wb64(pb, track->frag_info[i].offset + track->data_offset); avio_w8(pb, 1); /* traf number */ avio_w8(pb, 1); /* trun number */ avio_w8(pb, 1); /* sample number */ } return update_size(pb, pos); } static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "mfra"); /* An empty mfra atom is enough to indicate to the publishing point that * the stream has ended. */ if (mov->flags & FF_MOV_FLAG_ISML) return update_size(pb, pos); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->nb_frag_info) mov_write_tfra_tag(pb, track); } avio_wb32(pb, 16); ffio_wfourcc(pb, "mfro"); avio_wb32(pb, 0); /* version + flags */ avio_wb32(pb, avio_tell(pb) + 4 - pos); return update_size(pb, pos); } static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 8); // placeholder for extended size field (64 bit) ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free"); mov->mdat_pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "mdat"); return 0; } /* TODO: This needs to be more general */ static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = avio_tell(pb); int has_h264 = 0, has_video = 0; int minor = 0x200; int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) has_video = 1; if (st->codecpar->codec_id == AV_CODEC_ID_H264) has_h264 = 1; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ftyp"); if (mov->major_brand && strlen(mov->major_brand) >= 4) ffio_wfourcc(pb, mov->major_brand); else if (mov->mode == MODE_3GP) { ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4"); minor = has_h264 ? 0x100 : 0x200; } else if (mov->mode & MODE_3G2) { ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a"); minor = has_h264 ? 0x20000 : 0x10000; } else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) ffio_wfourcc(pb, "iso4"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "isom"); else if (mov->mode == MODE_IPOD) ffio_wfourcc(pb, has_video ? "M4V ":"M4A "); else if (mov->mode == MODE_ISM) ffio_wfourcc(pb, "isml"); else if (mov->mode == MODE_F4V) ffio_wfourcc(pb, "f4v "); else ffio_wfourcc(pb, "qt "); avio_wb32(pb, minor); if (mov->mode == MODE_MOV) ffio_wfourcc(pb, "qt "); else if (mov->mode == MODE_ISM) { ffio_wfourcc(pb, "piff"); } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) { ffio_wfourcc(pb, "isom"); ffio_wfourcc(pb, "iso2"); if (has_h264) ffio_wfourcc(pb, "avc1"); } // We add tfdt atoms when fragmenting, signal this with the iso6 compatible // brand. This is compatible with users that don't understand tfdt. if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM) ffio_wfourcc(pb, "iso6"); if (mov->mode == MODE_3GP) ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4"); else if (mov->mode & MODE_3G2) ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a"); else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "mp41"); if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) ffio_wfourcc(pb, "dash"); return update_size(pb, pos); } static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s) { AVStream *video_st = s->streams[0]; AVCodecParameters *video_par = s->streams[0]->codecpar; AVCodecParameters *audio_par = s->streams[1]->codecpar; int audio_rate = audio_par->sample_rate; int64_t frame_rate = video_st->avg_frame_rate.den ? (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den : 0; int audio_kbitrate = audio_par->bit_rate / 1000; int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate); if (frame_rate < 0 || frame_rate > INT32_MAX) { av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000); return AVERROR(EINVAL); } avio_wb32(pb, 0x94); /* size */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "PROF"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x3); /* 3 sections ? */ avio_wb32(pb, 0x14); /* size */ ffio_wfourcc(pb, "FPRF"); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x2c); /* size */ ffio_wfourcc(pb, "APRF"); /* audio */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x2); /* TrackID */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0x20f); avio_wb32(pb, 0x0); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_rate); avio_wb32(pb, audio_par->channels); avio_wb32(pb, 0x34); /* size */ ffio_wfourcc(pb, "VPRF"); /* video */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x1); /* TrackID */ if (video_par->codec_id == AV_CODEC_ID_H264) { ffio_wfourcc(pb, "avc1"); avio_wb16(pb, 0x014D); avio_wb16(pb, 0x0015); } else { ffio_wfourcc(pb, "mp4v"); avio_wb16(pb, 0x0000); avio_wb16(pb, 0x0103); } avio_wb32(pb, 0x0); avio_wb32(pb, video_kbitrate); avio_wb32(pb, video_kbitrate); avio_wb32(pb, frame_rate); avio_wb32(pb, frame_rate); avio_wb16(pb, video_par->width); avio_wb16(pb, video_par->height); avio_wb32(pb, 0x010001); /* ? */ return 0; } static int mov_write_identification(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; mov_write_ftyp_tag(pb,s); if (mov->mode == MODE_PSP) { int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) video_streams_nb++; else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) audio_streams_nb++; else other_streams_nb++; } if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) { av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n"); return AVERROR(EINVAL); } return mov_write_uuidprof_tag(pb, s); } return 0; } static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags) { uint32_t c = -1; int i, closed_gop = 0; for (i = 0; i < pkt->size - 4; i++) { c = (c << 8) + pkt->data[i]; if (c == 0x1b8) { // gop closed_gop = pkt->data[i + 4] >> 6 & 0x01; } else if (c == 0x100) { // pic int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6); if (!temp_ref || closed_gop) // I picture is not reordered *flags = MOV_SYNC_SAMPLE; else *flags = MOV_PARTIAL_SYNC_SAMPLE; break; } } return 0; } static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk) { const uint8_t *start, *next, *end = pkt->data + pkt->size; int seq = 0, entry = 0; int key = pkt->flags & AV_PKT_FLAG_KEY; start = find_next_marker(pkt->data, end); for (next = start; next < end; start = next) { next = find_next_marker(start + 4, end); switch (AV_RB32(start)) { case VC1_CODE_SEQHDR: seq = 1; break; case VC1_CODE_ENTRYPOINT: entry = 1; break; case VC1_CODE_SLICE: trk->vc1_info.slices = 1; break; } } if (!trk->entry && trk->vc1_info.first_packet_seen) trk->vc1_info.first_frag_written = 1; if (!trk->entry && !trk->vc1_info.first_frag_written) { /* First packet in first fragment */ trk->vc1_info.first_packet_seq = seq; trk->vc1_info.first_packet_entry = entry; trk->vc1_info.first_packet_seen = 1; } else if ((seq && !trk->vc1_info.packet_seq) || (entry && !trk->vc1_info.packet_entry)) { int i; for (i = 0; i < trk->entry; i++) trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE; trk->has_keyframes = 0; if (seq) trk->vc1_info.packet_seq = 1; if (entry) trk->vc1_info.packet_entry = 1; if (!trk->vc1_info.first_frag_written) { /* First fragment */ if ((!seq || trk->vc1_info.first_packet_seq) && (!entry || trk->vc1_info.first_packet_entry)) { /* First packet had the same headers as this one, readd the * sync sample flag. */ trk->cluster[0].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes = 1; } } } if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry) key = seq && entry; else if (trk->vc1_info.packet_seq) key = seq; else if (trk->vc1_info.packet_entry) key = entry; if (key) { trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes++; } } static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; int ret, buf_size; uint8_t *buf; int i, offset; if (!track->mdat_buf) return 0; if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; offset = avio_tell(mov->mdat_buf); avio_write(mov->mdat_buf, buf, buf_size); av_free(buf); for (i = track->entries_flushed; i < track->entry; i++) track->cluster[i].pos += offset; track->entries_flushed = track->entry; return 0; } static int mov_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int i, first_track = -1; int64_t mdat_size = 0; int ret; int has_video = 0, starts_with_key = 0, first_video_track = 1; if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) return 0; // Try to fill in the duration of the last packet in each stream // from queued packets in the interleave queues. If the flushing // of fragments was triggered automatically by an AVPacket, we // already have reliable info for the end of that track, but other // tracks may need to be filled in. for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (!track->end_reliable) { AVPacket pkt; if (!ff_interleaved_peek(s, i, &pkt, 1)) { if (track->dts_shift != AV_NOPTS_VALUE) pkt.dts += track->dts_shift; track->track_duration = pkt.dts - track->start_dts; if (pkt.pts != AV_NOPTS_VALUE) track->end_pts = pkt.pts; else track->end_pts = pkt.dts; } } } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->entry <= 1) continue; // Sample durations are calculated as the diff of dts values, // but for the last sample in a fragment, we don't know the dts // of the first sample in the next fragment, so we have to rely // on what was set as duration in the AVPacket. Not all callers // set this though, so we might want to replace it with an // estimate if it currently is zero. if (get_cluster_duration(track, track->entry - 1) != 0) continue; // Use the duration (i.e. dts diff) of the second last sample for // the last one. This is a wild guess (and fatal if it turns out // to be too long), but probably the best we can do - having a zero // duration is bad as well. track->track_duration += get_cluster_duration(track, track->entry - 2); track->end_pts += get_cluster_duration(track, track->entry - 2); if (!mov->missing_duration_warned) { av_log(s, AV_LOG_WARNING, "Estimating the duration of the last packet in a " "fragment, consider setting the duration field in " "AVPacket instead.\n"); mov->missing_duration_warned = 1; } } if (!mov->moov_written) { int64_t pos = avio_tell(s->pb); uint8_t *buf; int buf_size, moov_size; for (i = 0; i < mov->nb_streams; i++) if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st)) break; /* Don't write the initial moov unless all tracks have data */ if (i < mov->nb_streams && !force) return 0; moov_size = get_moov_size(s); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = pos + moov_size + 8; avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER); if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov_write_identification(s->pb, s); if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) { if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); avio_flush(s->pb); mov->moov_written = 1; return 0; } buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; avio_wb32(s->pb, buf_size + 8); ffio_wfourcc(s->pb, "mdat"); avio_write(s->pb, buf, buf_size); av_free(buf); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); mov->moov_written = 1; mov->mdat_size = 0; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry) mov->tracks[i].frag_start += mov->tracks[i].start_dts + mov->tracks[i].track_duration - mov->tracks[i].cluster[0].dts; mov->tracks[i].entry = 0; mov->tracks[i].end_reliable = 0; } avio_flush(s->pb); return 0; } if (mov->frag_interleave) { for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int ret; if ((ret = mov_flush_fragment_interleaving(s, track)) < 0) return ret; } if (!mov->mdat_buf) return 0; mdat_size = avio_tell(mov->mdat_buf); } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave) track->data_offset = 0; else track->data_offset = mdat_size; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { has_video = 1; if (first_video_track) { if (track->entry) starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE; first_video_track = 0; } } if (!track->entry) continue; if (track->mdat_buf) mdat_size += avio_tell(track->mdat_buf); if (first_track < 0) first_track = i; } if (!mdat_size) return 0; avio_write_marker(s->pb, av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale), (has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int buf_size, write_moof = 1, moof_tracks = -1; uint8_t *buf; int64_t duration = 0; if (track->entry) duration = track->start_dts + track->track_duration - track->cluster[0].dts; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) { if (!track->mdat_buf) continue; mdat_size = avio_tell(track->mdat_buf); moof_tracks = i; } else { write_moof = i == first_track; } if (write_moof) { avio_flush(s->pb); mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size); mov->fragments++; avio_wb32(s->pb, mdat_size + 8); ffio_wfourcc(s->pb, "mdat"); } if (track->entry) track->frag_start += duration; track->entry = 0; track->entries_flushed = 0; track->end_reliable = 0; if (!mov->frag_interleave) { if (!track->mdat_buf) continue; buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; } else { if (!mov->mdat_buf) continue; buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; } avio_write(s->pb, buf, buf_size); av_free(buf); } mov->mdat_size = 0; avio_flush(s->pb); return 0; } static int mov_auto_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int had_moov = mov->moov_written; int ret = mov_flush_fragment(s, force); if (ret < 0) return ret; // If using delay_moov, the first flush only wrote the moov, // not the actual moof+mdat pair, thus flush once again. if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV) ret = mov_flush_fragment(s, force); return ret; } static int check_pkt(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; int64_t ref; uint64_t duration; if (trk->entry) { ref = trk->cluster[trk->entry - 1].dts; } else if ( trk->start_dts != AV_NOPTS_VALUE && !trk->frag_discont) { ref = trk->start_dts + trk->track_duration; } else ref = pkt->dts; // Skip tests for the first packet if (trk->dts_shift != AV_NOPTS_VALUE) { /* With negative CTS offsets we have set an offset to the DTS, * reverse this for the check. */ ref -= trk->dts_shift; } duration = pkt->dts - ref; if (pkt->dts < ref || duration >= INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n", duration, pkt->dts ); pkt->dts = ref + 1; pkt->pts = AV_NOPTS_VALUE; } if (pkt->duration < 0 || pkt->duration > INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration); return AVERROR(EINVAL); } return 0; } int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; unsigned int samples_in_chunk = 0; int size = pkt->size, ret = 0; uint8_t *reformatted_data = NULL; ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret; if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { if (mov->frag_interleave && mov->fragments > 0) { if (trk->entry - trk->entries_flushed >= mov->frag_interleave) { if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0) return ret; } } if (!trk->mdat_buf) { if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0) return ret; } pb = trk->mdat_buf; } else { if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } pb = mov->mdat_buf; } } if (par->codec_id == AV_CODEC_ID_AMR_NB) { /* We must find out how many AMR blocks there are in one packet */ static const uint16_t packed_size[16] = {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1}; int len = 0; while (len < size && samples_in_chunk < 100) { len += packed_size[(pkt->data[len] >> 3) & 0x0F]; samples_in_chunk++; } if (samples_in_chunk > 1) { av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n"); return -1; } } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS || par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { samples_in_chunk = trk->par->frame_size; } else if (trk->sample_size) samples_in_chunk = size / trk->sample_size; else samples_in_chunk = 1; if (samples_in_chunk < 1) { av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n"); return AVERROR_PATCHWELCOME; } /* copy extradata if it exists */ if (trk->vos_len == 0 && par->extradata_size > 0 && !TAG_IS_AVCI(trk->tag) && (par->codec_id != AV_CODEC_ID_DNXHD)) { trk->vos_len = par->extradata_size; trk->vos_data = av_malloc(trk->vos_len); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, par->extradata, trk->vos_len); } if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return -1; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) { /* from x264 or from bytestream H.264 */ /* NAL reformatting needed */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data, &size); avio_write(pb, reformatted_data, size); } else { if (trk->cenc.aes_ctr) { size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size); if (size < 0) { ret = size; goto err; } } else { size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size); } } } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 && (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) { /* extradata is Annex B, assume the bitstream is too and convert it */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL); avio_write(pb, reformatted_data, size); } else { size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL); } #if CONFIG_AC3_PARSER } else if (par->codec_id == AV_CODEC_ID_EAC3) { size = handle_eac3(mov, pkt, trk); if (size < 0) return size; else if (!size) goto end; avio_write(pb, pkt->data, size); #endif } else { if (trk->cenc.aes_ctr) { if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) { int nal_size_length = (par->extradata[4] & 0x3) + 1; ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size); } else { ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size); } if (ret) { goto err; } } else { avio_write(pb, pkt->data, size); } } if ((par->codec_id == AV_CODEC_ID_DNXHD || par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) { /* copy frame to create needed atoms */ trk->vos_len = size; trk->vos_data = av_malloc(size); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, pkt->data, size); } if (trk->entry >= trk->cluster_capacity) { unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE); if (av_reallocp_array(&trk->cluster, new_capacity, sizeof(*trk->cluster))) { ret = AVERROR(ENOMEM); goto err; } trk->cluster_capacity = new_capacity; } trk->cluster[trk->entry].pos = avio_tell(pb) - size; trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk; trk->cluster[trk->entry].chunkNum = 0; trk->cluster[trk->entry].size = size; trk->cluster[trk->entry].entries = samples_in_chunk; trk->cluster[trk->entry].dts = pkt->dts; trk->cluster[trk->entry].pts = pkt->pts; if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) { if (!trk->frag_discont) { /* First packet of a new fragment. We already wrote the duration * of the last packet of the previous fragment based on track_duration, * which might not exactly match our dts. Therefore adjust the dts * of this packet to be what the previous packets duration implies. */ trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration; /* We also may have written the pts and the corresponding duration * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with * the next fragment. This means the cts of the first sample must * be the same in all fragments, unless end_pts was updated by * the packet causing the fragment to be written. */ if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) || mov->mode == MODE_ISM) pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts; } else { /* New fragment, but discontinuous from previous fragments. * Pretend the duration sum of the earlier fragments is * pkt->dts - trk->start_dts. */ trk->frag_start = pkt->dts - trk->start_dts; trk->end_pts = AV_NOPTS_VALUE; trk->frag_discont = 0; } } if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) { /* Not using edit lists and shifting the first track to start from zero. * If the other streams start from a later timestamp, we won't be able * to signal the difference in starting time without an edit list. * Thus move the timestamp for this first sample to 0, increasing * its duration instead. */ trk->cluster[trk->entry].dts = trk->start_dts = 0; } if (trk->start_dts == AV_NOPTS_VALUE) { trk->start_dts = pkt->dts; if (trk->frag_discont) { if (mov->use_editlist) { /* Pretend the whole stream started at pts=0, with earlier fragments * already written. If the stream started at pts=0, the duration sum * of earlier fragments would have been pkt->pts. */ trk->frag_start = pkt->pts; trk->start_dts = pkt->dts - pkt->pts; } else { /* Pretend the whole stream started at dts=0, with earlier fragments * already written, with a duration summing up to pkt->dts. */ trk->frag_start = pkt->dts; trk->start_dts = 0; } trk->frag_discont = 0; } else if (pkt->dts && mov->moov_written) av_log(s, AV_LOG_WARNING, "Track %d starts with a nonzero dts %"PRId64", while the moov " "already has been written. Set the delay_moov flag to handle " "this case.\n", pkt->stream_index, pkt->dts); } trk->track_duration = pkt->dts - trk->start_dts + pkt->duration; trk->last_sample_is_subtitle_end = 0; if (pkt->pts == AV_NOPTS_VALUE) { av_log(s, AV_LOG_WARNING, "pts has no value\n"); pkt->pts = pkt->dts; } if (pkt->dts != pkt->pts) trk->flags |= MOV_TRACK_CTTS; trk->cluster[trk->entry].cts = pkt->pts - pkt->dts; trk->cluster[trk->entry].flags = 0; if (trk->start_cts == AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; if (trk->end_pts == AV_NOPTS_VALUE) trk->end_pts = trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration; else trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration); if (par->codec_id == AV_CODEC_ID_VC1) { mov_parse_vc1_frame(pkt, trk); } else if (pkt->flags & AV_PKT_FLAG_KEY) { if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO && trk->entry > 0) { // force sync sample for the first key frame mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags); if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE) trk->flags |= MOV_TRACK_STPS; } else { trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE; } if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE) trk->has_keyframes++; } if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) { trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE; trk->has_disposable++; } trk->entry++; trk->sample_count += samples_in_chunk; mov->mdat_size += size; if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry, reformatted_data, size); end: err: av_free(reformatted_data); return ret; } static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; int64_t frag_duration = 0; int size = pkt->size; int ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) { int i; for (i = 0; i < s->nb_streams; i++) mov->tracks[i].frag_discont = 1; mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT; } if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) { if (trk->dts_shift == AV_NOPTS_VALUE) trk->dts_shift = pkt->pts - pkt->dts; pkt->dts += trk->dts_shift; } if (trk->par->codec_id == AV_CODEC_ID_MP4ALS || trk->par->codec_id == AV_CODEC_ID_AAC || trk->par->codec_id == AV_CODEC_ID_FLAC) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!newextra) return AVERROR(ENOMEM); av_free(par->extradata); par->extradata = newextra; memcpy(par->extradata, side, side_size); par->extradata_size = side_size; if (!pkt->size) // Flush packet mov->need_rewrite_extradata = 1; } } if (!pkt->size) { if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) { trk->start_dts = pkt->dts; if (pkt->pts != AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; else trk->start_cts = 0; } return 0; /* Discard 0 sized packets */ } if (trk->entry && pkt->stream_index < s->nb_streams) frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q); if ((mov->max_fragment_duration && frag_duration >= mov->max_fragment_duration) || (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) || (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME && par->codec_type == AVMEDIA_TYPE_VIDEO && trk->entry && pkt->flags & AV_PKT_FLAG_KEY) || (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) { if (frag_duration >= mov->min_fragment_duration) { // Set the duration of this track to line up with the next // sample in this track. This avoids relying on AVPacket // duration, but only helps for this particular track, not // for the other ones that are flushed at the same time. trk->track_duration = pkt->dts - trk->start_dts; if (pkt->pts != AV_NOPTS_VALUE) trk->end_pts = pkt->pts; else trk->end_pts = pkt->dts; trk->end_reliable = 1; mov_auto_flush_fragment(s, 0); } } return ff_mov_write_packet(s, pkt); } static int mov_write_subtitle_end_packet(AVFormatContext *s, int stream_index, int64_t dts) { AVPacket end; uint8_t data[2] = {0}; int ret; av_init_packet(&end); end.size = sizeof(data); end.data = data; end.pts = dts; end.dts = dts; end.duration = 0; end.stream_index = stream_index; ret = mov_write_single_packet(s, &end); av_packet_unref(&end); return ret; } static int mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk; if (!pkt) { mov_flush_fragment(s, 1); return 1; } trk = &mov->tracks[pkt->stream_index]; if (is_cover_image(trk->st)) { int ret; if (trk->st->nb_frames >= 1) { if (trk->st->nb_frames == 1) av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d," " ignoring.\n", pkt->stream_index); return 0; } if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0) return ret; return 0; } else { int i; if (!pkt->size) return mov_write_single_packet(s, pkt); /* Passthrough. */ /* * Subtitles require special handling. * * 1) For full complaince, every track must have a sample at * dts == 0, which is rarely true for subtitles. So, as soon * as we see any packet with dts > 0, write an empty subtitle * at dts == 0 for any subtitle track with no samples in it. * * 2) For each subtitle track, check if the current packet's * dts is past the duration of the last subtitle sample. If * so, we now need to write an end sample for that subtitle. * * This must be done conditionally to allow for subtitles that * immediately replace each other, in which case an end sample * is not needed, and is, in fact, actively harmful. * * 3) See mov_write_trailer for how the final end sample is * handled. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; int ret; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && trk->track_duration < pkt->dts && (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) { ret = mov_write_subtitle_end_packet(s, i, trk->track_duration); if (ret < 0) return ret; trk->last_sample_is_subtitle_end = 1; } } if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) { AVPacket *opkt = pkt; int reshuffle_ret, ret; if (trk->is_unaligned_qt_rgb) { int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16; int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2; reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride); if (reshuffle_ret < 0) return reshuffle_ret; } else reshuffle_ret = 0; if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) { ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette); if (ret < 0) goto fail; if (ret) trk->pal_done++; } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO && (trk->par->format == AV_PIX_FMT_GRAY8 || trk->par->format == AV_PIX_FMT_MONOBLACK)) { for (i = 0; i < pkt->size; i++) pkt->data[i] = ~pkt->data[i]; } if (reshuffle_ret) { ret = mov_write_single_packet(s, pkt); fail: if (reshuffle_ret) av_packet_free(&pkt); return ret; } } return mov_write_single_packet(s, pkt); } } // QuickTime chapters involve an additional text track with the chapter names // as samples, and a tref pointing from the other tracks to the chapter one. static int mov_create_chapter_track(AVFormatContext *s, int tracknum) { AVIOContext *pb; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[tracknum]; AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY }; int i, len; track->mode = mov->mode; track->tag = MKTAG('t','e','x','t'); track->timescale = MOV_TIMESCALE; track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_SUBTITLE; #if 0 // These properties are required to make QT recognize the chapter track uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, }; if (ff_alloc_extradata(track->par, sizeof(chapter_properties))) return AVERROR(ENOMEM); memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties)); #else if (avio_open_dyn_buf(&pb) >= 0) { int size; uint8_t *buf; /* Stub header (usually for Quicktime chapter track) */ // TextSampleEntry avio_wb32(pb, 0x01); // displayFlags avio_w8(pb, 0x00); // horizontal justification avio_w8(pb, 0x00); // vertical justification avio_w8(pb, 0x00); // bgColourRed avio_w8(pb, 0x00); // bgColourGreen avio_w8(pb, 0x00); // bgColourBlue avio_w8(pb, 0x00); // bgColourAlpha // BoxRecord avio_wb16(pb, 0x00); // defTextBoxTop avio_wb16(pb, 0x00); // defTextBoxLeft avio_wb16(pb, 0x00); // defTextBoxBottom avio_wb16(pb, 0x00); // defTextBoxRight // StyleRecord avio_wb16(pb, 0x00); // startChar avio_wb16(pb, 0x00); // endChar avio_wb16(pb, 0x01); // fontID avio_w8(pb, 0x00); // fontStyleFlags avio_w8(pb, 0x00); // fontSize avio_w8(pb, 0x00); // fgColourRed avio_w8(pb, 0x00); // fgColourGreen avio_w8(pb, 0x00); // fgColourBlue avio_w8(pb, 0x00); // fgColourAlpha // FontTableBox avio_wb32(pb, 0x0D); // box size ffio_wfourcc(pb, "ftab"); // box atom name avio_wb16(pb, 0x01); // entry count // FontRecord avio_wb16(pb, 0x01); // font ID avio_w8(pb, 0x00); // font name length if ((size = avio_close_dyn_buf(pb, &buf)) > 0) { track->par->extradata = buf; track->par->extradata_size = size; } else { av_freep(&buf); } } #endif for (i = 0; i < s->nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.duration = end - pkt.dts; if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { static const char encd[12] = { 0x00, 0x00, 0x00, 0x0C, 'e', 'n', 'c', 'd', 0x00, 0x00, 0x01, 0x00 }; len = strlen(t->value); pkt.size = len + 2 + 12; pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB16(pkt.data, len); memcpy(pkt.data + 2, t->value, len); memcpy(pkt.data + len + 2, encd, sizeof(encd)); ff_mov_write_packet(s, &pkt); av_freep(&pkt.data); } } return 0; } static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr) { int ret; /* compute the frame number */ ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s); return ret; } static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc) { int ret; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[index]; AVStream *src_st = s->streams[src_index]; AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4}; AVRational rate = find_fps(s, src_st); /* tmcd track based on video stream */ track->mode = mov->mode; track->tag = MKTAG('t','m','c','d'); track->src_track = src_index; track->timescale = mov->tracks[src_index].timescale; if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME) track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME; /* set st to src_st for metadata access*/ track->st = src_st; /* encode context: tmcd data stream */ track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_DATA; track->par->codec_tag = track->tag; track->st->avg_frame_rate = av_inv_q(rate); /* the tmcd track just contains one packet with the frame number */ pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB32(pkt.data, tc.start); ret = ff_mov_write_packet(s, &pkt); av_free(pkt.data); return ret; } /* * st->disposition controls the "enabled" flag in the tkhd tag. * QuickTime will not play a track if it is not enabled. So make sure * that one track of each type (audio, video, subtitle) is enabled. * * Subtitles are special. For audio and video, setting "enabled" also * makes the track "default" (i.e. it is rendered when played). For * subtitles, an "enabled" subtitle is not rendered by default, but * if no subtitle is enabled, the subtitle menu in QuickTime will be * empty! */ static void enable_tracks(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; int enabled[AVMEDIA_TYPE_NB]; int first[AVMEDIA_TYPE_NB]; for (i = 0; i < AVMEDIA_TYPE_NB; i++) { enabled[i] = 0; first[i] = -1; } for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN || st->codecpar->codec_type >= AVMEDIA_TYPE_NB || is_cover_image(st)) continue; if (first[st->codecpar->codec_type] < 0) first[st->codecpar->codec_type] = i; if (st->disposition & AV_DISPOSITION_DEFAULT) { mov->tracks[i].flags |= MOV_TRACK_ENABLED; enabled[st->codecpar->codec_type]++; } } for (i = 0; i < AVMEDIA_TYPE_NB; i++) { switch (i) { case AVMEDIA_TYPE_VIDEO: case AVMEDIA_TYPE_AUDIO: case AVMEDIA_TYPE_SUBTITLE: if (enabled[i] > 1) mov->per_stream_grouping = 1; if (!enabled[i] && first[i] >= 0) mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED; break; } } } static void mov_free(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; if (mov->chapter_track) { if (mov->tracks[mov->chapter_track].par) av_freep(&mov->tracks[mov->chapter_track].par->extradata); av_freep(&mov->tracks[mov->chapter_track].par); } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) ff_mov_close_hinting(&mov->tracks[i]); else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd) av_freep(&mov->tracks[i].par); av_freep(&mov->tracks[i].cluster); av_freep(&mov->tracks[i].frag_info); av_packet_unref(&mov->tracks[i].cover_image); if (mov->tracks[i].vos_len) av_freep(&mov->tracks[i].vos_data); ff_mov_cenc_free(&mov->tracks[i].cenc); } av_freep(&mov->tracks); } static uint32_t rgb_to_yuv(uint32_t rgb) { uint8_t r, g, b; int y, cb, cr; r = (rgb >> 16) & 0xFF; g = (rgb >> 8) & 0xFF; b = (rgb ) & 0xFF; y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000); cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000); cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000); return (y << 16) | (cr << 8) | cb; } static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track, AVStream *st) { int i, width = 720, height = 480; int have_palette = 0, have_size = 0; uint32_t palette[16]; char *cur = st->codecpar->extradata; while (cur && *cur) { if (strncmp("palette:", cur, 8) == 0) { int i, count; count = sscanf(cur + 8, "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"", &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3], &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7], &palette[ 8], &palette[ 9], &palette[10], &palette[11], &palette[12], &palette[13], &palette[14], &palette[15]); for (i = 0; i < count; i++) { palette[i] = rgb_to_yuv(palette[i]); } have_palette = 1; } else if (!strncmp("size:", cur, 5)) { sscanf(cur + 5, "%dx%d", &width, &height); have_size = 1; } if (have_palette && have_size) break; cur += strcspn(cur, "\n\r"); cur += strspn(cur, "\n\r"); } if (have_palette) { track->vos_data = av_malloc(16*4); if (!track->vos_data) return AVERROR(ENOMEM); for (i = 0; i < 16; i++) { AV_WB32(track->vos_data + i * 4, palette[i]); } track->vos_len = 16 * 4; } st->codecpar->width = width; st->codecpar->height = track->height = height; return 0; } static int mov_init(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret; mov->fc = s; /* Default mode == MP4 */ mov->mode = MODE_MP4; if (s->oformat) { if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP; else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2; else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV; else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP; else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD; else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM; else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V; } if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV; /* Set the FRAGMENT flag if any of the fragmentation methods are * enabled. */ if (mov->max_fragment_duration || mov->max_fragment_size || mov->flags & (FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) mov->flags |= FF_MOV_FLAG_FRAGMENT; /* Set other implicit flags immediately */ if (mov->mode == MODE_ISM) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF | FF_MOV_FLAG_FRAGMENT; if (mov->flags & FF_MOV_FLAG_DASH) mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_DEFAULT_BASE_MOOF; if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) { av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n"); s->flags &= ~AVFMT_FLAG_AUTO_BSF; } if (mov->flags & FF_MOV_FLAG_FASTSTART) { mov->reserved_moov_size = -1; } if (mov->use_editlist < 0) { mov->use_editlist = 1; if (mov->flags & FF_MOV_FLAG_FRAGMENT && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { // If we can avoid needing an edit list by shifting the // tracks, prefer that over (trying to) write edit lists // in fragmented output. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) mov->use_editlist = 0; } } if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist) av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n"); if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO) s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO; /* Clear the omit_tfhd_offset flag if default_base_moof is set; * if the latter is set that's enough and omit_tfhd_offset doesn't * add anything extra on top of that. */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET; if (mov->frag_interleave && mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) { av_log(s, AV_LOG_ERROR, "Sample interleaving in fragments is mutually exclusive with " "omit_tfhd_offset and separate_moof\n"); return AVERROR(EINVAL); } /* Non-seekable output is ok if using fragmentation. If ism_lookahead * is enabled, we don't support non-seekable output at all. */ if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) { av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n"); return AVERROR(EINVAL); } mov->nb_streams = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) mov->chapter_track = mov->nb_streams++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) mov->nb_streams++; } if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4) || mov->write_tmcd == 1) { /* +1 tmcd track for each video stream with a timecode */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; AVDictionaryEntry *t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) { AVTimecode tc; ret = mov_check_timecode_track(s, &tc, i, t->value); if (ret >= 0) mov->nb_meta_tmcd++; } } /* check if there is already a tmcd track to remux */ if (mov->nb_meta_tmcd) { for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) { av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track " "so timecode metadata are now ignored\n"); mov->nb_meta_tmcd = 0; } } } mov->nb_streams += mov->nb_meta_tmcd; } // Reserve an extra stream for chapters for the case where chapters // are written in the trailer mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks)); if (!mov->tracks) return AVERROR(ENOMEM); if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) { if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) { mov->encryption_scheme = MOV_ENC_CENC_AES_CTR; if (mov->encryption_key_len != AES_CTR_KEY_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n", mov->encryption_key_len, AES_CTR_KEY_SIZE); return AVERROR(EINVAL); } if (mov->encryption_kid_len != CENC_KID_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n", mov->encryption_kid_len, CENC_KID_SIZE); return AVERROR(EINVAL); } } else { av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n", mov->encryption_scheme_str); return AVERROR(EINVAL); } } for (i = 0; i < s->nb_streams; i++) { AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); track->st = st; track->par = st->codecpar; track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV); if (track->language < 0) track->language = 0; track->mode = mov->mode; track->tag = mov_find_codec_tag(s, track); if (!track->tag) { av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, " "codec not currently supported in container\n", avcodec_get_name(st->codecpar->codec_id), i); return AVERROR(EINVAL); } /* If hinting of this track is enabled by a later hint track, * this is updated. */ track->hint_track = -1; track->start_dts = AV_NOPTS_VALUE; track->start_cts = AV_NOPTS_VALUE; track->end_pts = AV_NOPTS_VALUE; track->dts_shift = AV_NOPTS_VALUE; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') || track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') || track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) { if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) { av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n"); return AVERROR(EINVAL); } track->height = track->tag >> 24 == 'n' ? 486 : 576; } if (mov->video_track_timescale) { track->timescale = mov->video_track_timescale; } else { track->timescale = st->time_base.den; while(track->timescale < 10000) track->timescale *= 2; } if (st->codecpar->width > 65535 || st->codecpar->height > 65535) { av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height); return AVERROR(EINVAL); } if (track->mode == MODE_MOV && track->timescale > 100000) av_log(s, AV_LOG_WARNING, "WARNING codec timebase is very high. If duration is too long,\n" "file may not be playable by quicktime. Specify a shorter timebase\n" "or choose different container.\n"); if (track->mode == MODE_MOV && track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->tag == MKTAG('r','a','w',' ')) { enum AVPixelFormat pix_fmt = track->par->format; if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1) pix_fmt = AV_PIX_FMT_MONOWHITE; track->is_unaligned_qt_rgb = pix_fmt == AV_PIX_FMT_RGB24 || pix_fmt == AV_PIX_FMT_BGR24 || pix_fmt == AV_PIX_FMT_PAL8 || pix_fmt == AV_PIX_FMT_GRAY8 || pix_fmt == AV_PIX_FMT_MONOWHITE || pix_fmt == AV_PIX_FMT_MONOBLACK; } if (track->par->codec_id == AV_CODEC_ID_VP9) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n"); return AVERROR(EINVAL); } } else if (track->par->codec_id == AV_CODEC_ID_AV1) { /* spec is not finished, so forbid for now */ av_log(s, AV_LOG_ERROR, "AV1 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } else if (track->par->codec_id == AV_CODEC_ID_VP8) { /* altref frames handling is not defined in the spec as of version v1.0, * so just forbid muxing VP8 streams altogether until a new version does */ av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { track->timescale = st->codecpar->sample_rate; if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) { av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i); track->audio_vbr = 1; }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || st->codecpar->codec_id == AV_CODEC_ID_ILBC){ if (!st->codecpar->block_align) { av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i); return AVERROR(EINVAL); } track->sample_size = st->codecpar->block_align; }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */ track->audio_vbr = 1; }else{ track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels; } if (st->codecpar->codec_id == AV_CODEC_ID_ILBC || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) { track->audio_vbr = 1; } if (track->mode != MODE_MOV && track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) { if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) { av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n", i, track->par->sample_rate); return AVERROR(EINVAL); } else { av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n", i, track->par->sample_rate); } } if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id)); return AVERROR(EINVAL); } if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { av_log(s, AV_LOG_ERROR, "%s in MP4 support is experimental, add " "'-strict %d' if you want to use it.\n", avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL); return AVERROR_EXPERIMENTAL; } } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { track->timescale = st->time_base.den; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { track->timescale = st->time_base.den; } else { track->timescale = MOV_TIMESCALE; } if (!track->height) track->height = st->codecpar->height; /* The ism specific timescale isn't mandatory, but is assumed by * some tools, such as mp4split. */ if (mov->mode == MODE_ISM) track->timescale = 10000000; avpriv_set_pts_info(st, 64, 1, track->timescale); if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) { ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key, track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT); if (ret) return ret; } } enable_tracks(s); return 0; } static int mov_write_header(AVFormatContext *s) { AVIOContext *pb = s->pb; MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) nb_tracks++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { hint_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) nb_tracks++; } if (mov->mode == MODE_MOV || mov->mode == MODE_MP4) tmcd_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) { int j; AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; /* copy extradata if it exists */ if (st->codecpar->extradata_size) { if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_create_dvd_sub_decoder_specific_info(track, st); else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) { track->vos_len = st->codecpar->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) { return AVERROR(ENOMEM); } memcpy(track->vos_data, st->codecpar->extradata, track->vos_len); } } if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || track->par->channel_layout != AV_CH_LAYOUT_MONO) continue; for (j = 0; j < s->nb_streams; j++) { AVStream *stj= s->streams[j]; MOVTrack *trackj= &mov->tracks[j]; if (j == i) continue; if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || trackj->par->channel_layout != AV_CH_LAYOUT_MONO || trackj->language != track->language || trackj->tag != track->tag ) continue; track->multichannel_as_mono++; } } if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_identification(pb, s)) < 0) return ret; } if (mov->reserved_moov_size){ mov->reserved_header_pos = avio_tell(pb); if (mov->reserved_moov_size > 0) avio_skip(pb, mov->reserved_moov_size); } if (mov->flags & FF_MOV_FLAG_FRAGMENT) { /* If no fragmentation options have been set, set a default. */ if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) && !mov->max_fragment_duration && !mov->max_fragment_size) mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME; } else { if (mov->flags & FF_MOV_FLAG_FASTSTART) mov->reserved_header_pos = avio_tell(pb); mov_write_mdat_tag(pb, mov); } ff_parse_creation_time_metadata(s, &mov->time, 1); if (mov->time) mov->time += 0x7C25B080; // 1970 based -> 1904 based if (mov->chapter_track) if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) { if (rtp_hinting_needed(s->streams[i])) { if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0) return ret; hint_track++; } } } if (mov->nb_meta_tmcd) { /* Initialize the tmcd tracks */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { AVTimecode tc; if (!t) t = av_dict_get(st->metadata, "timecode", NULL, 0); if (!t) continue; if (mov_check_timecode_track(s, &tc, i, t->value) < 0) continue; if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0) return ret; tmcd_track++; } } } avio_flush(pb); if (mov->flags & FF_MOV_FLAG_ISML) mov_write_isml_manifest(pb, mov, s); if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_moov_tag(pb, mov, s)) < 0) return ret; avio_flush(pb); mov->moov_written = 1; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(pb); } return 0; } static int get_moov_size(AVFormatContext *s) { int ret; AVIOContext *moov_buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&moov_buf)) < 0) return ret; if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0) return ret; return ffio_close_null_buf(moov_buf); } static int get_sidx_size(AVFormatContext *s) { int ret; AVIOContext *buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&buf)) < 0) return ret; mov_write_sidx_tags(buf, mov, -1, 0); return ffio_close_null_buf(buf); } /* * This function gets the moov size if moved to the top of the file: the chunk * offset table can switch between stco (32-bit entries) to co64 (64-bit * entries) when the moov is moved to the beginning, so the size of the moov * would change. It also updates the chunk offset tables. */ static int compute_moov_size(AVFormatContext *s) { int i, moov_size, moov_size2; MOVMuxContext *mov = s->priv_data; moov_size = get_moov_size(s); if (moov_size < 0) return moov_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size; moov_size2 = get_moov_size(s); if (moov_size2 < 0) return moov_size2; /* if the size changed, we just switched from stco to co64 and need to * update the offsets */ if (moov_size2 != moov_size) for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size2 - moov_size; return moov_size2; } static int compute_sidx_size(AVFormatContext *s) { int i, sidx_size; MOVMuxContext *mov = s->priv_data; sidx_size = get_sidx_size(s); if (sidx_size < 0) return sidx_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += sidx_size; return sidx_size; } static int shift_data(AVFormatContext *s) { int ret = 0, moov_size; MOVMuxContext *mov = s->priv_data; int64_t pos, pos_end = avio_tell(s->pb); uint8_t *buf, *read_buf[2]; int read_buf_id = 0; int read_size[2]; AVIOContext *read_pb; if (mov->flags & FF_MOV_FLAG_FRAGMENT) moov_size = compute_sidx_size(s); else moov_size = compute_moov_size(s); if (moov_size < 0) return moov_size; buf = av_malloc(moov_size * 2); if (!buf) return AVERROR(ENOMEM); read_buf[0] = buf; read_buf[1] = buf + moov_size; /* Shift the data: the AVIO context of the output can only be used for * writing, so we re-open the same output, but for reading. It also avoids * a read/seek/write/seek back and forth. */ avio_flush(s->pb); ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL); if (ret < 0) { av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for " "the second pass (faststart)\n", s->url); goto end; } /* mark the end of the shift to up to the last data we wrote, and get ready * for writing */ pos_end = avio_tell(s->pb); avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET); /* start reading at where the new moov will be placed */ avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET); pos = avio_tell(read_pb); #define READ_BLOCK do { \ read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \ read_buf_id ^= 1; \ } while (0) /* shift data by chunk of at most moov_size */ READ_BLOCK; do { int n; READ_BLOCK; n = read_size[read_buf_id]; if (n <= 0) break; avio_write(s->pb, read_buf[read_buf_id], n); pos += n; } while (pos < pos_end); ff_format_io_close(s, &read_pb); end: av_free(buf); return ret; } static int mov_write_trailer(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; int res = 0; int i; int64_t moov_pos; if (mov->need_rewrite_extradata) { for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; AVCodecParameters *par = track->par; track->vos_len = par->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) return AVERROR(ENOMEM); memcpy(track->vos_data, par->extradata, track->vos_len); } mov->need_rewrite_extradata = 0; } /* * Before actually writing the trailer, make sure that there are no * dangling subtitles, that need a terminating sample. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && !trk->last_sample_is_subtitle_end) { mov_write_subtitle_end_packet(s, i, trk->track_duration); trk->last_sample_is_subtitle_end = 1; } } // If there were no chapters when the header was written, but there // are chapters now, write them in the trailer. This only works // when we are not doing fragments. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) { if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) { mov->chapter_track = mov->nb_streams++; if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0) return res; } } if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) { moov_pos = avio_tell(pb); /* Write size of mdat tag */ if (mov->mdat_size + 8 <= UINT32_MAX) { avio_seek(pb, mov->mdat_pos, SEEK_SET); avio_wb32(pb, mov->mdat_size + 8); } else { /* overwrite 'wide' placeholder atom */ avio_seek(pb, mov->mdat_pos - 8, SEEK_SET); /* special value: real atom size will be 64 bit value after * tag field */ avio_wb32(pb, 1); ffio_wfourcc(pb, "mdat"); avio_wb64(pb, mov->mdat_size + 16); } avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET); if (mov->flags & FF_MOV_FLAG_FASTSTART) { av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n"); res = shift_data(s); if (res < 0) return res; avio_seek(pb, mov->reserved_header_pos, SEEK_SET); if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } else if (mov->reserved_moov_size > 0) { int64_t size; if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos); if (size < 8){ av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size); return AVERROR(EINVAL); } avio_wb32(pb, size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, size - 8); avio_seek(pb, moov_pos, SEEK_SET); } else { if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } res = 0; } else { mov_auto_flush_fragment(s, 1); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = 0; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) { int64_t end; av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n"); res = shift_data(s); if (res < 0) return res; end = avio_tell(pb); avio_seek(pb, mov->reserved_header_pos, SEEK_SET); mov_write_sidx_tags(pb, mov, -1, 0); avio_seek(pb, end, SEEK_SET); avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) { avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } } return res; } static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt) { int ret = 1; AVStream *st = s->streams[pkt->stream_index]; if (st->codecpar->codec_id == AV_CODEC_ID_AAC) { if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL); } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) { ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL); } return ret; } static const AVCodecTag codec_3gp_tags[] = { { AV_CODEC_ID_H263, MKTAG('s','2','6','3') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') }, { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_NONE, 0 }, }; const AVCodecTag codec_mp4_tags[] = { { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') }, { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') }, { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') }, { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') }, { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') }, { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') }, { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') }, { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') }, { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') }, { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') }, { AV_CODEC_ID_NONE , 0 }, }; const AVCodecTag codec_ism_tags[] = { { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') }, { AV_CODEC_ID_NONE , 0 }, }; static const AVCodecTag codec_ipod_tags[] = { { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') }, { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') }, { AV_CODEC_ID_NONE, 0 }, }; static const AVCodecTag codec_f4v_tags[] = { { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') }, { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') }, { AV_CODEC_ID_NONE, 0 }, }; #if CONFIG_MOV_MUXER MOV_CLASS(mov) AVOutputFormat ff_mov_muxer = { .name = "mov", .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"), .extensions = "mov", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mov_muxer_class, }; #endif #if CONFIG_TGP_MUXER MOV_CLASS(tgp) AVOutputFormat ff_tgp_muxer = { .name = "3gp", .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"), .extensions = "3gp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tgp_muxer_class, }; #endif #if CONFIG_MP4_MUXER MOV_CLASS(mp4) AVOutputFormat ff_mp4_muxer = { .name = "mp4", .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "mp4", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mp4_muxer_class, }; #endif #if CONFIG_PSP_MUXER MOV_CLASS(psp) AVOutputFormat ff_psp_muxer = { .name = "psp", .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"), .extensions = "mp4,psp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &psp_muxer_class, }; #endif #if CONFIG_TG2_MUXER MOV_CLASS(tg2) AVOutputFormat ff_tg2_muxer = { .name = "3g2", .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"), .extensions = "3g2", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tg2_muxer_class, }; #endif #if CONFIG_IPOD_MUXER MOV_CLASS(ipod) AVOutputFormat ff_ipod_muxer = { .name = "ipod", .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "m4v,m4a,m4b", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ipod_muxer_class, }; #endif #if CONFIG_ISMV_MUXER MOV_CLASS(ismv) AVOutputFormat ff_ismv_muxer = { .name = "ismv", .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"), .mime_type = "video/mp4", .extensions = "ismv,isma", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, codec_ism_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ismv_muxer_class, }; #endif #if CONFIG_F4V_MUXER MOV_CLASS(f4v) AVOutputFormat ff_f4v_muxer = { .name = "f4v", .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"), .mime_type = "application/f4v", .extensions = "f4v", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH, .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &f4v_muxer_class, }; #endif
./CrossVul/dataset_final_sorted/CWE-369/c/good_257_0
crossvul-cpp_data_bad_817_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % X X W W DDDD % % X X W W D D % % X W W D D % % X X W W W D D % % X X W W DDDD % % % % % % Read/Write X Windows System Window Dump Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 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://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/colormap-private.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/property.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #if defined(MAGICKCORE_X11_DELEGATE) #include "magick/xwindow-private.h" #if !defined(vms) #include <X11/XWDFile.h> #else #include "XWDFile.h" #endif #endif /* Forward declarations. */ #if defined(MAGICKCORE_X11_DELEGATE) static MagickBooleanType WriteXWDImage(const ImageInfo *,Image *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s X W D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsXWD() returns MagickTrue if the image format type, identified by the % magick string, is XWD. % % The format of the IsXWD method is: % % MagickBooleanType IsXWD(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 IsXWD(const unsigned char *magick,const size_t length) { if (length < 8) return(MagickFalse); if (memcmp(magick+1,"\000\000",2) == 0) { if (memcmp(magick+4,"\007\000\000",3) == 0) return(MagickTrue); if (memcmp(magick+5,"\000\000\007",3) == 0) return(MagickTrue); } return(MagickFalse); } #if defined(MAGICKCORE_X11_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadXWDImage() reads an X Window System window dump 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 ReadXWDImage method is: % % Image *ReadXWDImage(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 *ReadXWDImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define CheckOverflowException(length,width,height) \ (((height) != 0) && ((length)/((size_t) height) != ((size_t) width))) char *comment; Image *image; IndexPacket index; int x_status; MagickBooleanType authentic_colormap; MagickStatusType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; register ssize_t i; register size_t pixel; size_t length; ssize_t count, y; unsigned long lsb_first; XColor *colors; XImage *ximage; XWDFileHeader header; /* 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); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read in header information. */ count=ReadBlob(image,sz_XWDheader,(unsigned char *) &header); if (count != sz_XWDheader) ThrowReaderException(CorruptImageError,"UnableToReadImageHeader"); /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &header,sz_XWDheader); /* Check to see if the dump file is in the proper format. */ if (header.file_version != XWD_FILE_VERSION) ThrowReaderException(CorruptImageError,"FileFormatVersionMismatch"); if (header.header_size < sz_XWDheader) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if ((header.bits_per_pixel == 0) || (header.bits_per_pixel > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (((header.bitmap_pad % 8) != 0) || (header.bitmap_pad > 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (header.bitmap_unit > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (header.ncolors > 256) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); switch (header.visual_class) { case StaticGray: case GrayScale: case StaticColor: case PseudoColor: case TrueColor: case DirectColor: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } switch (header.pixmap_format) { case XYBitmap: case XYPixmap: case ZPixmap: break; default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } length=(size_t) (header.header_size-sz_XWDheader); if ((length+1) != ((size_t) ((CARD32) (length+1)))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); comment=(char *) AcquireQuantumMemory(length+1,sizeof(*comment)); if (comment == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,length,(unsigned char *) comment); comment[length]='\0'; (void) SetImageProperty(image,"comment",comment); comment=DestroyString(comment); if (count != (ssize_t) length) ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); /* Initialize the X image. */ ximage=(XImage *) AcquireMagickMemory(sizeof(*ximage)); if (ximage == (XImage *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); ximage->depth=(int) header.pixmap_depth; ximage->format=(int) header.pixmap_format; ximage->xoffset=(int) header.xoffset; ximage->data=(char *) NULL; ximage->width=(int) header.pixmap_width; ximage->height=(int) header.pixmap_height; ximage->bitmap_pad=(int) header.bitmap_pad; ximage->bytes_per_line=(int) header.bytes_per_line; ximage->byte_order=(int) header.byte_order; ximage->bitmap_unit=(int) header.bitmap_unit; ximage->bitmap_bit_order=(int) header.bitmap_bit_order; ximage->bits_per_pixel=(int) header.bits_per_pixel; ximage->red_mask=header.red_mask; ximage->green_mask=header.green_mask; ximage->blue_mask=header.blue_mask; if ((ximage->width < 0) || (ximage->height < 0) || (ximage->depth < 0) || (ximage->format < 0) || (ximage->byte_order < 0) || (ximage->bitmap_bit_order < 0) || (ximage->bitmap_pad < 0) || (ximage->bytes_per_line < 0)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->width > 65535) || (ximage->height > 65535)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if ((ximage->bits_per_pixel > 32) || (ximage->bitmap_unit > 32)) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } x_status=XInitImage(ximage); if (x_status == 0) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } /* Read colormap. */ authentic_colormap=MagickFalse; colors=(XColor *) NULL; if (header.ncolors != 0) { XWDColor color; length=(size_t) header.ncolors; if (length > ((~0UL)/sizeof(*colors))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); colors=(XColor *) AcquireQuantumMemory(length,sizeof(*colors)); if (colors == (XColor *) NULL) { ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) header.ncolors; i++) { count=ReadBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != sz_XWDColor) { colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } colors[i].pixel=color.pixel; colors[i].red=color.red; colors[i].green=color.green; colors[i].blue=color.blue; colors[i].flags=(char) color.flags; if (color.flags != 0) authentic_colormap=MagickTrue; } /* Ensure the header byte-order is most-significant byte first. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) for (i=0; i < (ssize_t) header.ncolors; i++) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } /* Allocate the pixel buffer. */ length=(size_t) ximage->bytes_per_line*ximage->height; if (CheckOverflowException(length,ximage->bytes_per_line,ximage->height)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (ximage->format != ZPixmap) { size_t extent; extent=length; length*=ximage->depth; if (CheckOverflowException(length,extent,ximage->depth)) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } ximage->data=(char *) AcquireQuantumMemory(length,sizeof(*ximage->data)); if (ximage->data == (char *) NULL) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } count=ReadBlob(image,length,(unsigned char *) ximage->data); if (count != (ssize_t) length) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(CorruptImageError,"UnableToReadImageData"); } /* Convert image to MIFF format. */ image->columns=(size_t) ximage->width; image->rows=(size_t) ximage->height; image->depth=8; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((header.ncolors == 0U) || (ximage->red_mask != 0) || (ximage->green_mask != 0) || (ximage->blue_mask != 0)) image->storage_class=DirectClass; else image->storage_class=PseudoClass; image->colors=header.ncolors; if (image_info->ping == MagickFalse) switch (image->storage_class) { case DirectClass: default: { register size_t color; size_t blue_mask, blue_shift, green_mask, green_shift, red_mask, red_shift; /* Determine shift and mask for red, green, and blue. */ red_mask=ximage->red_mask; red_shift=0; while ((red_mask != 0) && ((red_mask & 0x01) == 0)) { red_mask>>=1; red_shift++; } green_mask=ximage->green_mask; green_shift=0; while ((green_mask != 0) && ((green_mask & 0x01) == 0)) { green_mask>>=1; green_shift++; } blue_mask=ximage->blue_mask; blue_shift=0; while ((blue_mask != 0) && ((blue_mask & 0x01) == 0)) { blue_mask>>=1; blue_shift++; } /* Convert X image to DirectClass packets. */ if ((image->colors != 0) && (authentic_colormap != MagickFalse)) for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> red_shift) & red_mask); SetPixelRed(q,ScaleShortToQuantum(colors[(ssize_t) index].red)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> green_shift) & green_mask); SetPixelGreen(q,ScaleShortToQuantum(colors[(ssize_t) index].green)); index=ConstrainColormapIndex(image,(ssize_t) (pixel >> blue_shift) & blue_mask); SetPixelBlue(q,ScaleShortToQuantum(colors[(ssize_t) index].blue)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=XGetPixel(ximage,(int) x,(int) y); color=(pixel >> red_shift) & red_mask; if (red_mask != 0) color=(color*65535UL)/red_mask; SetPixelRed(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> green_shift) & green_mask; if (green_mask != 0) color=(color*65535UL)/green_mask; SetPixelGreen(q,ScaleShortToQuantum((unsigned short) color)); color=(pixel >> blue_shift) & blue_mask; if (blue_mask != 0) color=(color*65535UL)/blue_mask; SetPixelBlue(q,ScaleShortToQuantum((unsigned short) color)); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } case PseudoClass: { /* Convert X image to PseudoClass packets. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) { if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleShortToQuantum(colors[i].red); image->colormap[i].green=ScaleShortToQuantum(colors[i].green); image->colormap[i].blue=ScaleShortToQuantum(colors[i].blue); } 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++) { index=ConstrainColormapIndex(image,(ssize_t) XGetPixel(ximage,(int) x,(int) y)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } break; } } /* Free image and colormap. */ if (header.ncolors != 0) colors=(XColor *) RelinquishMagickMemory(colors); ximage->data=DestroyString(ximage->data); ximage=(XImage *) RelinquishMagickMemory(ximage); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterXWDImage() adds properties for the XWD 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 RegisterXWDImage method is: % % size_t RegisterXWDImage(void) % */ ModuleExport size_t RegisterXWDImage(void) { MagickInfo *entry; entry=SetMagickInfo("XWD"); #if defined(MAGICKCORE_X11_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadXWDImage; entry->encoder=(EncodeImageHandler *) WriteXWDImage; #endif entry->magick=(IsImageFormatHandler *) IsXWD; entry->adjoin=MagickFalse; entry->description=ConstantString("X Windows system window dump (color)"); entry->module=ConstantString("XWD"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterXWDImage() removes format registrations made by the % XWD module from the list of supported formats. % % The format of the UnregisterXWDImage method is: % % UnregisterXWDImage(void) % */ ModuleExport void UnregisterXWDImage(void) { (void) UnregisterMagickInfo("XWD"); } #if defined(MAGICKCORE_X11_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e X W D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteXWDImage() writes an image to a file in X window dump % rasterfile format. % % The format of the WriteXWDImage method is: % % MagickBooleanType WriteXWDImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteXWDImage(const ImageInfo *image_info,Image *image) { const char *value; MagickBooleanType status; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t x; register unsigned char *q; size_t bits_per_pixel, bytes_per_line, length, scanline_pad; ssize_t count, y; unsigned char *pixels; unsigned long lsb_first; XWDFileHeader xwd_info; /* Open output image 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); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); if ((image->columns != (CARD32) image->columns) || (image->rows != (CARD32) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageType(image,TrueColorType); (void) TransformImageColorspace(image,sRGBColorspace); /* Initialize XWD file header. */ (void) memset(&xwd_info,0,sizeof(xwd_info)); xwd_info.header_size=(CARD32) sz_XWDheader; value=GetImageProperty(image,"comment"); if (value != (const char *) NULL) xwd_info.header_size+=(CARD32) strlen(value); xwd_info.header_size++; xwd_info.file_version=(CARD32) XWD_FILE_VERSION; xwd_info.pixmap_format=(CARD32) ZPixmap; xwd_info.pixmap_depth=(CARD32) (image->storage_class == DirectClass ? 24 : 8); xwd_info.pixmap_width=(CARD32) image->columns; xwd_info.pixmap_height=(CARD32) image->rows; xwd_info.xoffset=(CARD32) 0; xwd_info.byte_order=(CARD32) MSBFirst; xwd_info.bitmap_unit=(CARD32) (image->storage_class == DirectClass ? 32 : 8); xwd_info.bitmap_bit_order=(CARD32) MSBFirst; xwd_info.bitmap_pad=(CARD32) (image->storage_class == DirectClass ? 32 : 8); bits_per_pixel=(size_t) (image->storage_class == DirectClass ? 24 : 8); xwd_info.bits_per_pixel=(CARD32) bits_per_pixel; bytes_per_line=(CARD32) ((((xwd_info.bits_per_pixel* xwd_info.pixmap_width)+((xwd_info.bitmap_pad)-1))/ (xwd_info.bitmap_pad))*((xwd_info.bitmap_pad) >> 3)); xwd_info.bytes_per_line=(CARD32) bytes_per_line; xwd_info.visual_class=(CARD32) (image->storage_class == DirectClass ? DirectColor : PseudoColor); xwd_info.red_mask=(CARD32) (image->storage_class == DirectClass ? 0xff0000 : 0); xwd_info.green_mask=(CARD32) (image->storage_class == DirectClass ? 0xff00 : 0); xwd_info.blue_mask=(CARD32) (image->storage_class == DirectClass ? 0xff : 0); xwd_info.bits_per_rgb=(CARD32) (image->storage_class == DirectClass ? 24 : 8); xwd_info.colormap_entries=(CARD32) (image->storage_class == DirectClass ? 256 : image->colors); xwd_info.ncolors=(unsigned int) (image->storage_class == DirectClass ? 0 : image->colors); xwd_info.window_width=(CARD32) image->columns; xwd_info.window_height=(CARD32) image->rows; xwd_info.window_x=0; xwd_info.window_y=0; xwd_info.window_bdrwidth=(CARD32) 0; /* Write XWD header. */ lsb_first=1; if ((int) (*(char *) &lsb_first) != 0) MSBOrderLong((unsigned char *) &xwd_info,sizeof(xwd_info)); (void) WriteBlob(image,sz_XWDheader,(unsigned char *) &xwd_info); if (value != (const char *) NULL) (void) WriteBlob(image,strlen(value),(unsigned char *) value); (void) WriteBlob(image,1,(const unsigned char *) "\0"); if (image->storage_class == PseudoClass) { register ssize_t i; XColor *colors; XWDColor color; /* Dump colormap to file. */ (void) memset(&color,0,sizeof(color)); colors=(XColor *) AcquireQuantumMemory((size_t) image->colors, sizeof(*colors)); if (colors == (XColor *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) { colors[i].pixel=(unsigned long) i; colors[i].red=ScaleQuantumToShort(image->colormap[i].red); colors[i].green=ScaleQuantumToShort(image->colormap[i].green); colors[i].blue=ScaleQuantumToShort(image->colormap[i].blue); colors[i].flags=(char) (DoRed | DoGreen | DoBlue); colors[i].pad='\0'; if ((int) (*(char *) &lsb_first) != 0) { MSBOrderLong((unsigned char *) &colors[i].pixel, sizeof(colors[i].pixel)); MSBOrderShort((unsigned char *) &colors[i].red,3* sizeof(colors[i].red)); } } for (i=0; i < (ssize_t) image->colors; i++) { color.pixel=(CARD32) colors[i].pixel; color.red=colors[i].red; color.green=colors[i].green; color.blue=colors[i].blue; color.flags=(CARD8) colors[i].flags; count=WriteBlob(image,sz_XWDColor,(unsigned char *) &color); if (count != (ssize_t) sz_XWDColor) break; } colors=(XColor *) RelinquishMagickMemory(colors); } /* Allocate memory for pixels. */ length=3*bytes_per_line; if (image->storage_class == PseudoClass) length=bytes_per_line; pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(pixels,0,length); /* Convert MIFF to XWD raster pixels. */ scanline_pad=(bytes_per_line-((image->columns*bits_per_pixel) >> 3)); 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; q=pixels; if (image->storage_class == PseudoClass) { indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) *q++=(unsigned char) GetPixelIndex(indexes+x); } else for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); p++; } for (x=0; x < (ssize_t) scanline_pad; x++) *q++='\0'; length=(size_t) (q-pixels); count=WriteBlob(image,length,pixels); if (count != (ssize_t) length) break; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); (void) CloseBlob(image); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-369/c/bad_817_0
crossvul-cpp_data_bad_952_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % L AAA Y Y EEEEE RRRR % % L A A Y Y E R R % % L AAAAA Y EEE RRRR % % L A A Y E R R % % LLLLL A A Y EEEEE R R % % % % MagickCore Image Layering Methods % % % % Software Design % % Cristy % % Anthony Thyssen % % January 2006 % % % % % % Copyright 1999-2019 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://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/cache.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/composite.h" #include "magick/effect.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/layer.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/property.h" #include "magick/profile.h" #include "magick/resource_.h" #include "magick/resize.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l e a r B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClearBounds() Clear the area specified by the bounds in an image to % transparency. This typically used to handle Background Disposal for the % previous frame in an animation sequence. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % void ClearBounds(Image *image,RectangleInfo *bounds) % % A description of each parameter follows: % % o image: the image to had the area cleared in % % o bounds: the area to be clear within the imag image % */ static void ClearBounds(Image *image,RectangleInfo *bounds) { ExceptionInfo *exception; ssize_t y; if (bounds->x < 0) return; if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); exception=(&image->exception); for (y=0; y < (ssize_t) bounds->height; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=GetAuthenticPixels(image,bounds->x,bounds->y+y,bounds->width,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) bounds->width; x++) { q->opacity=(Quantum) TransparentOpacity; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s B o u n d s C l e a r e d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsBoundsCleared() tests whether any pixel in the bounds given, gets cleared % when going from the first image to the second image. This typically used % to check if a proposed disposal method will work successfully to generate % the second frame image from the first disposed form of the previous frame. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % MagickBooleanType IsBoundsCleared(const Image *image1, % const Image *image2,RectangleInfo bounds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image1, image 2: the images to check for cleared pixels % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsBoundsCleared(const Image *image1, const Image *image2,RectangleInfo *bounds,ExceptionInfo *exception) { register const PixelPacket *p, *q; register ssize_t x; ssize_t y; if (bounds->x < 0) return(MagickFalse); for (y=0; y < (ssize_t) bounds->height; y++) { p=GetVirtualPixels(image1,bounds->x,bounds->y+y,bounds->width,1, exception); q=GetVirtualPixels(image2,bounds->x,bounds->y+y,bounds->width,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) bounds->width; x++) { if ((GetPixelOpacity(p) <= (Quantum) (QuantumRange/2)) && (GetPixelOpacity(q) > (Quantum) (QuantumRange/2))) break; p++; q++; } if (x < (ssize_t) bounds->width) break; } return(y < (ssize_t) bounds->height ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o a l e s c e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CoalesceImages() composites a set of images while respecting any page % offsets and disposal methods. GIF, MIFF, and MNG animation sequences % typically start with an image background and each subsequent image % varies in size and offset. A new image sequence is returned with all % images the same size as the first images virtual canvas and composited % with the next image in the sequence. % % The format of the CoalesceImages method is: % % Image *CoalesceImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CoalesceImages(const Image *image,ExceptionInfo *exception) { Image *coalesce_image, *dispose_image, *previous; register Image *next; RectangleInfo bounds; /* Coalesce the image sequence. */ 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); /* initialise first image */ next=GetFirstImageInList(image); bounds=next->page; if (bounds.width == 0) { bounds.width=next->columns; if (bounds.x > 0) bounds.width+=bounds.x; } if (bounds.height == 0) { bounds.height=next->rows; if (bounds.y > 0) bounds.height+=bounds.y; } bounds.x=0; bounds.y=0; coalesce_image=CloneImage(next,bounds.width,bounds.height,MagickTrue, exception); if (coalesce_image == (Image *) NULL) return((Image *) NULL); coalesce_image->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(coalesce_image); coalesce_image->matte=next->matte; coalesce_image->page=bounds; coalesce_image->dispose=NoneDispose; /* Coalesce rest of the images. */ dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); (void) CompositeImage(coalesce_image,CopyCompositeOp,next,next->page.x, next->page.y); next=GetNextImageInList(next); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { /* Determine the bounds that was overlaid in the previous image. */ previous=GetPreviousImageInList(next); bounds=previous->page; bounds.width=previous->columns; bounds.height=previous->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) coalesce_image->columns) bounds.width=coalesce_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) coalesce_image->rows) bounds.height=coalesce_image->rows-bounds.y; /* Replace the dispose image with the new coalesced image. */ if (GetPreviousImageInList(next)->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); if (dispose_image == (Image *) NULL) { coalesce_image=DestroyImageList(coalesce_image); return((Image *) NULL); } } /* Clear the overlaid area of the coalesced bounds for background disposal */ if (next->previous->dispose == BackgroundDispose) ClearBounds(dispose_image,&bounds); /* Next image is the dispose image, overlaid with next frame in sequence. */ coalesce_image->next=CloneImage(dispose_image,0,0,MagickTrue,exception); if (coalesce_image->next != NULL) coalesce_image->next->previous=coalesce_image; previous=coalesce_image; coalesce_image=GetNextImageInList(coalesce_image); (void) CompositeImage(coalesce_image,next->matte != MagickFalse ? OverCompositeOp : CopyCompositeOp,next,next->page.x,next->page.y); (void) CloneImageProfiles(coalesce_image,next); (void) CloneImageProperties(coalesce_image,next); (void) CloneImageArtifacts(coalesce_image,next); coalesce_image->page=previous->page; /* If a pixel goes opaque to transparent, use background dispose. */ if (IsBoundsCleared(previous,coalesce_image,&bounds,exception) != MagickFalse) coalesce_image->dispose=BackgroundDispose; else coalesce_image->dispose=NoneDispose; previous->dispose=coalesce_image->dispose; } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(coalesce_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D i s p o s e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisposeImages() returns the coalesced frames of a GIF animation as it would % appear after the GIF dispose method of that frame has been applied. That is % it returned the appearance of each frame before the next is overlaid. % % The format of the DisposeImages method is: % % Image *DisposeImages(Image *images,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *DisposeImages(const Image *images,ExceptionInfo *exception) { Image *dispose_image, *dispose_images; RectangleInfo bounds; register Image *image, *next; /* Run the image through the animation sequence */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(images); dispose_image=CloneImage(image,image->page.width,image->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return((Image *) NULL); dispose_image->page=image->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(dispose_image); dispose_images=NewImageList(); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { Image *current_image; /* Overlay this frame's image over the previous disposal image. */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } (void) CompositeImage(current_image,next->matte != MagickFalse ? OverCompositeOp : CopyCompositeOp,next,next->page.x,next->page.y); /* Handle Background dispose: image is displayed for the delay period. */ if (next->dispose == BackgroundDispose) { bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds); } /* Select the appropriate previous/disposed image. */ if (next->dispose == PreviousDispose) current_image=DestroyImage(current_image); else { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; current_image=(Image *) NULL; } /* Save the dispose image just calculated for return. */ { Image *dispose; dispose=CloneImage(dispose_image,0,0,MagickTrue,exception); if (dispose == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } (void) CloneImageProfiles(dispose,next); (void) CloneImageProperties(dispose,next); (void) CloneImageArtifacts(dispose,next); dispose->page.x=0; dispose->page.y=0; dispose->dispose=next->dispose; AppendImageToList(&dispose_images,dispose); } } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(dispose_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComparePixels() Compare the two pixels and return true if the pixels % differ according to the given LayerType comparision method. % % This currently only used internally by CompareImageBounds(). It is % doubtful that this sub-routine will be useful outside this module. % % The format of the ComparePixels method is: % % MagickBooleanType *ComparePixels(const ImageLayerMethod method, % const MagickPixelPacket *p,const MagickPixelPacket *q) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o p, q: the pixels to test for appropriate differences. % */ static MagickBooleanType ComparePixels(const ImageLayerMethod method, const MagickPixelPacket *p,const MagickPixelPacket *q) { MagickRealType o1, o2; /* Any change in pixel values */ if (method == CompareAnyLayer) return((MagickBooleanType)(IsMagickColorSimilar(p,q) == MagickFalse)); o1 = (p->matte != MagickFalse) ? GetPixelOpacity(p) : OpaqueOpacity; o2 = (q->matte != MagickFalse) ? q->opacity : OpaqueOpacity; /* Pixel goes from opaque to transprency */ if (method == CompareClearLayer) return((MagickBooleanType) ( (o1 <= ((MagickRealType) QuantumRange/2.0)) && (o2 > ((MagickRealType) QuantumRange/2.0)) ) ); /* overlay would change first pixel by second */ if (method == CompareOverlayLayer) { if (o2 > ((MagickRealType) QuantumRange/2.0)) return MagickFalse; return((MagickBooleanType) (IsMagickColorSimilar(p,q) == MagickFalse)); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e I m a g e B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImageBounds() Given two images return the smallest rectangular area % by which the two images differ, accourding to the given 'Compare...' % layer method. % % This currently only used internally in this module, but may eventually % be used by other modules. % % The format of the CompareImageBounds method is: % % RectangleInfo *CompareImageBounds(const ImageLayerMethod method, % const Image *image1,const Image *image2,ExceptionInfo *exception) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o image1, image2: the two images to compare. % % o exception: return any errors or warnings in this structure. % */ static RectangleInfo CompareImageBounds(const Image *image1,const Image *image2, const ImageLayerMethod method,ExceptionInfo *exception) { RectangleInfo bounds; MagickPixelPacket pixel1, pixel2; register const IndexPacket *indexes1, *indexes2; register const PixelPacket *p, *q; register ssize_t x; ssize_t y; #if 0 /* only same sized images can be compared */ assert(image1->columns == image2->columns); assert(image1->rows == image2->rows); #endif /* Set bounding box of the differences between images */ GetMagickPixelPacket(image1,&pixel1); GetMagickPixelPacket(image2,&pixel2); for (x=0; x < (ssize_t) image1->columns; x++) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const PixelPacket *) NULL) || (q == (const PixelPacket *) NULL)) break; indexes1=GetVirtualIndexQueue(image1); indexes2=GetVirtualIndexQueue(image2); for (y=0; y < (ssize_t) image1->rows; y++) { SetMagickPixelPacket(image1,p,indexes1+x,&pixel1); SetMagickPixelPacket(image2,q,indexes2+x,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p++; q++; } if (y < (ssize_t) image1->rows) break; } if (x >= (ssize_t) image1->columns) { /* Images are identical, return a null image. */ bounds.x=-1; bounds.y=-1; bounds.width=1; bounds.height=1; return(bounds); } bounds.x=x; for (x=(ssize_t) image1->columns-1; x >= 0; x--) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const PixelPacket *) NULL) || (q == (const PixelPacket *) NULL)) break; indexes1=GetVirtualIndexQueue(image1); indexes2=GetVirtualIndexQueue(image2); for (y=0; y < (ssize_t) image1->rows; y++) { SetMagickPixelPacket(image1,p,indexes1+x,&pixel1); SetMagickPixelPacket(image2,q,indexes2+x,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p++; q++; } if (y < (ssize_t) image1->rows) break; } bounds.width=(size_t) (x-bounds.x+1); for (y=0; y < (ssize_t) image1->rows; y++) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (const PixelPacket *) NULL)) break; indexes1=GetVirtualIndexQueue(image1); indexes2=GetVirtualIndexQueue(image2); for (x=0; x < (ssize_t) image1->columns; x++) { SetMagickPixelPacket(image1,p,indexes1+x,&pixel1); SetMagickPixelPacket(image2,q,indexes2+x,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p++; q++; } if (x < (ssize_t) image1->columns) break; } bounds.y=y; for (y=(ssize_t) image1->rows-1; y >= 0; y--) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (const PixelPacket *) NULL)) break; indexes1=GetVirtualIndexQueue(image1); indexes2=GetVirtualIndexQueue(image2); for (x=0; x < (ssize_t) image1->columns; x++) { SetMagickPixelPacket(image1,p,indexes1+x,&pixel1); SetMagickPixelPacket(image2,q,indexes2+x,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p++; q++; } if (x < (ssize_t) image1->columns) break; } bounds.height=(size_t) (y-bounds.y+1); return(bounds); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p a r e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImageLayers() compares each image with the next in a sequence and % returns the minimum bounding region of all the pixel differences (of the % ImageLayerMethod specified) it discovers. % % Images do NOT have to be the same size, though it is best that all the % images are 'coalesced' (images are all the same size, on a flattened % canvas, so as to represent exactly how an specific frame should look). % % No GIF dispose methods are applied, so GIF animations must be coalesced % before applying this image operator to find differences to them. % % The format of the CompareImageLayers method is: % % Image *CompareImageLayers(const Image *images, % const ImageLayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers type to compare images with. Must be one of... % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CompareImageLayers(const Image *image, const ImageLayerMethod method,ExceptionInfo *exception) { Image *image_a, *image_b, *layers; RectangleInfo *bounds; register const Image *next; register ssize_t i; assert(image != (const 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); assert((method == CompareAnyLayer) || (method == CompareClearLayer) || (method == CompareOverlayLayer)); /* Allocate bounds memory. */ next=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(next),sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Set up first comparision images. */ image_a=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (image_a == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_a->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(image_a); image_a->page=next->page; image_a->page.x=0; image_a->page.y=0; (void) CompositeImage(image_a,CopyCompositeOp,next,next->page.x,next->page.y); /* Compute the bounding box of changes for the later images */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { image_b=CloneImage(image_a,0,0,MagickTrue,exception); if (image_b == (Image *) NULL) { image_a=DestroyImage(image_a); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } (void) CompositeImage(image_a,CopyCompositeOp,next,next->page.x, next->page.y); bounds[i]=CompareImageBounds(image_b,image_a,method,exception); image_b=DestroyImage(image_b); i++; } image_a=DestroyImage(image_a); /* Clone first image in sequence. */ next=GetFirstImageInList(image); layers=CloneImage(next,0,0,MagickTrue,exception); if (layers == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } /* Deconstruct the image sequence. */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { if ((bounds[i].x == -1) && (bounds[i].y == -1) && (bounds[i].width == 1) && (bounds[i].height == 1)) { /* An empty frame is returned from CompareImageBounds(), which means the current frame is identical to the previous frame. */ i++; continue; } image_a=CloneImage(next,0,0,MagickTrue,exception); if (image_a == (Image *) NULL) break; image_b=CropImage(image_a,&bounds[i],exception); image_a=DestroyImage(image_a); if (image_b == (Image *) NULL) break; AppendImageToList(&layers,image_b); i++; } bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); if (next != (Image *) NULL) { layers=DestroyImageList(layers); return((Image *) NULL); } return(GetFirstImageInList(layers)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o n s t r u c t I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeconstructImages() compares each image with the next in a sequence and % returns the minimum bounding region of all differences from the first image. % % This function is deprecated in favor of the more universal % CompareImageLayers() function. % % The format of the DeconstructImages method is: % % Image *DeconstructImages(const Image *images,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *DeconstructImages(const Image *images, ExceptionInfo *exception) { return(CompareImageLayers(images,CompareAnyLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p t i m i z e L a y e r F r a m e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeLayerFrames() takes a coalesced GIF animation, and compares each % frame against the three different 'disposal' forms of the previous frame. % From this it then attempts to select the smallest cropped image and % disposal method needed to reproduce the resulting image. % % Note that this not easy, and may require the expansion of the bounds % of previous frame, simply clear pixels for the next animation frame to % transparency according to the selected dispose method. % % The format of the OptimizeLayerFrames method is: % % static Image *OptimizeLayerFrames(const Image *image, % const ImageLayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers technique to optimize with. Must be one of... % OptimizeImageLayer, or OptimizePlusLayer. The Plus form allows % the addition of extra 'zero delay' frames to clear pixels from % the previous frame, and the removal of frames that done change, % merging the delay times together. % % o exception: return any errors or warnings in this structure. % */ /* Define a 'fake' dispose method where the frame is duplicated, (for OptimizePlusLayer) with a extra zero time delay frame which does a BackgroundDisposal to clear the pixels that need to be cleared. */ #define DupDispose ((DisposeType)9) /* Another 'fake' dispose method used to removed frames that don't change. */ #define DelDispose ((DisposeType)8) #define DEBUG_OPT_FRAME 0 static Image *OptimizeLayerFrames(const Image *image, const ImageLayerMethod method,ExceptionInfo *exception) { ExceptionInfo *sans_exception; Image *prev_image, *dup_image, *bgnd_image, *optimized_image; RectangleInfo try_bounds, bgnd_bounds, dup_bounds, *bounds; MagickBooleanType add_frames, try_cleared, cleared; DisposeType *disposals; register const Image *curr; register ssize_t i; assert(image != (const 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); assert(method == OptimizeLayer || method == OptimizeImageLayer || method == OptimizePlusLayer); /* Are we allowed to add/remove frames from animation */ add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse; /* Ensure all the images are the same size */ curr=GetFirstImageInList(image); for (; curr != (Image *) NULL; curr=GetNextImageInList(curr)) { if ((curr->columns != image->columns) || (curr->rows != image->rows)) ThrowImageException(OptionError,"ImagesAreNotTheSameSize"); if ((curr->page.x != 0) || (curr->page.y != 0) || (curr->page.width != image->page.width) || (curr->page.height != image->page.height)) ThrowImageException(OptionError,"ImagePagesAreNotCoalesced"); } /* Allocate memory (times 2 if we allow the use of frame duplications) */ curr=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); disposals=(DisposeType *) AcquireQuantumMemory((size_t) GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*disposals)); if (disposals == (DisposeType *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialise Previous Image as fully transparent */ prev_image=CloneImage(curr,curr->page.width,curr->page.height, MagickTrue,exception); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */ prev_image->page.x=0; prev_image->page.y=0; prev_image->dispose=NoneDispose; prev_image->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(prev_image); /* Figure out the area of overlay of the first frame No pixel could be cleared as all pixels are already cleared. */ #if DEBUG_OPT_FRAME i=0; (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif disposals[0]=NoneDispose; bounds[0]=CompareImageBounds(prev_image,curr,CompareAnyLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g\n\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); #endif /* Compute the bounding box of changes for each pair of images. */ i=1; bgnd_image=(Image *) NULL; dup_image=(Image *) NULL; dup_bounds.width=0; dup_bounds.height=0; dup_bounds.x=0; dup_bounds.y=0; curr=GetNextImageInList(curr); for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr)) { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif /* Assume none disposal is the best */ bounds[i]=CompareImageBounds(curr->previous,curr,CompareAnyLayer,exception); cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception); disposals[i-1]=NoneDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g%s%s\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y, bounds[i].x < 0?" (unchanged)":"", cleared?" (pixels cleared)":""); #endif if ( bounds[i].x < 0 ) { /* Image frame is exactly the same as the previous frame! If not adding frames leave it to be cropped down to a null image. Otherwise mark previous image for deleted, transfering its crop bounds to the current image. */ if ( add_frames && i>=2 ) { disposals[i-1]=DelDispose; disposals[i]=NoneDispose; bounds[i]=bounds[i-1]; i++; continue; } } else { /* Compare a none disposal against a previous disposal */ try_bounds=CompareImageBounds(prev_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "test_prev: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels were cleared)":""); #endif if ( (!try_cleared && cleared ) || try_bounds.width * try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=try_cleared; bounds[i]=try_bounds; disposals[i-1]=PreviousDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"previous: accepted\n"); } else { (void) FormatLocaleFile(stderr,"previous: rejected\n"); #endif } /* If we are allowed lets try a complex frame duplication. It is useless if the previous image already clears pixels correctly. This method will always clear all the pixels that need to be cleared. */ dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */ if ( add_frames ) { dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (dup_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); return((Image *) NULL); } dup_bounds=CompareImageBounds(dup_image,curr,CompareClearLayer,exception); ClearBounds(dup_image,&dup_bounds); try_bounds=CompareImageBounds(dup_image,curr,CompareAnyLayer,exception); if ( cleared || dup_bounds.width*dup_bounds.height +try_bounds.width*try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=MagickFalse; bounds[i]=try_bounds; disposals[i-1]=DupDispose; /* to be finalised later, if found to be optimial */ } else dup_bounds.width=dup_bounds.height=0; } /* Now compare against a simple background disposal */ bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (bgnd_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); return((Image *) NULL); } bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */ ClearBounds(bgnd_image,&bgnd_bounds); try_bounds=CompareImageBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "background: %s\n", try_cleared?"(pixels cleared)":""); #endif if ( try_cleared ) { /* Straight background disposal failed to clear pixels needed! Lets try expanding the disposal area of the previous frame, to include the pixels that are cleared. This guaranteed to work, though may not be the most optimized solution. */ try_bounds=CompareImageBounds(curr->previous,curr,CompareClearLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_clear: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_bounds.x<0?" (no expand nessary)":""); #endif if ( bgnd_bounds.x < 0 ) bgnd_bounds = try_bounds; else { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_bgnd: %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif if ( try_bounds.x < bgnd_bounds.x ) { bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; bgnd_bounds.x = try_bounds.x; } else { try_bounds.width += try_bounds.x - bgnd_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; } if ( try_bounds.y < bgnd_bounds.y ) { bgnd_bounds.height += bgnd_bounds.y - try_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; bgnd_bounds.y = try_bounds.y; } else { try_bounds.height += try_bounds.y - bgnd_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; } #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, " to : %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif } ClearBounds(bgnd_image,&bgnd_bounds); #if DEBUG_OPT_FRAME /* Something strange is happening with a specific animation * CompareAnyLayers (normal method) and CompareClearLayers returns the whole * image, which is not posibly correct! As verified by previous tests. * Something changed beyond the bgnd_bounds clearing. But without being able * to see, or writet he image at this point it is hard to tell what is wrong! * Only CompareOverlay seemed to return something sensible. */ try_bounds=CompareImageBounds(bgnd_image,curr,CompareClearLayer,exception); (void) FormatLocaleFile(stderr, "expand_ctst: %.20gx%.20g%+.20g%+.20g\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y ); try_bounds=CompareImageBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_any : %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif try_bounds=CompareImageBounds(bgnd_image,curr,CompareOverlayLayer,exception); #if DEBUG_OPT_FRAME try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_test: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif } /* Test if this background dispose is smaller than any of the other methods we tryed before this (including duplicated frame) */ if ( cleared || bgnd_bounds.width*bgnd_bounds.height +try_bounds.width*try_bounds.height < bounds[i-1].width*bounds[i-1].height +dup_bounds.width*dup_bounds.height +bounds[i].width*bounds[i].height ) { cleared=MagickFalse; bounds[i-1]=bgnd_bounds; bounds[i]=try_bounds; if ( disposals[i-1] == DupDispose ) dup_image=DestroyImage(dup_image); disposals[i-1]=BackgroundDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"expand_bgnd: accepted\n"); } else { (void) FormatLocaleFile(stderr,"expand_bgnd: reject\n"); #endif } } /* Finalise choice of dispose, set new prev_image, and junk any extra images as appropriate, */ if ( disposals[i-1] == DupDispose ) { if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); prev_image=DestroyImage(prev_image); prev_image=dup_image, dup_image=(Image *) NULL; bounds[i+1]=bounds[i]; bounds[i]=dup_bounds; disposals[i-1]=DupDispose; disposals[i]=BackgroundDispose; i++; } else { if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); if ( disposals[i-1] != PreviousDispose ) prev_image=DestroyImage(prev_image); if ( disposals[i-1] == BackgroundDispose ) prev_image=bgnd_image, bgnd_image=(Image *) NULL; if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); if ( disposals[i-1] == NoneDispose ) { prev_image=ReferenceImage(curr->previous); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } } } assert(prev_image != (Image *) NULL); disposals[i]=disposals[i-1]; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "final %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i-1, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]), (double) bounds[i-1].width,(double) bounds[i-1].height, (double) bounds[i-1].x,(double) bounds[i-1].y ); #endif #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "interum %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]), (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); (void) FormatLocaleFile(stderr,"\n"); #endif i++; } prev_image=DestroyImage(prev_image); /* Optimize all images in sequence. */ sans_exception=AcquireExceptionInfo(); i=0; curr=GetFirstImageInList(image); optimized_image=NewImageList(); while ( curr != (const Image *) NULL ) { prev_image=CloneImage(curr,0,0,MagickTrue,exception); if (prev_image == (Image *) NULL) break; if ( disposals[i] == DelDispose ) { size_t time = 0; while ( disposals[i] == DelDispose ) { time += curr->delay*1000/curr->ticks_per_second; curr=GetNextImageInList(curr); i++; } time += curr->delay*1000/curr->ticks_per_second; prev_image->ticks_per_second = 100L; prev_image->delay = time*prev_image->ticks_per_second/1000; } bgnd_image=CropImage(prev_image,&bounds[i],sans_exception); prev_image=DestroyImage(prev_image); if (bgnd_image == (Image *) NULL) break; bgnd_image->dispose=disposals[i]; if ( disposals[i] == DupDispose ) { bgnd_image->delay=0; bgnd_image->dispose=NoneDispose; } else curr=GetNextImageInList(curr); AppendImageToList(&optimized_image,bgnd_image); i++; } sans_exception=DestroyExceptionInfo(sans_exception); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); if (curr != (Image *) NULL) { optimized_image=DestroyImageList(optimized_image); return((Image *) NULL); } return(GetFirstImageInList(optimized_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageLayers() compares each image the GIF disposed forms of the % previous image in the sequence. From this it attempts to select the % smallest cropped image to replace each frame, while preserving the results % of the GIF animation. % % The format of the OptimizeImageLayers method is: % % Image *OptimizeImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizeImageLayers(const Image *image, ExceptionInfo *exception) { return(OptimizeLayerFrames(image,OptimizeImageLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e P l u s I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImagePlusLayers() is exactly as OptimizeImageLayers(), but may % also add or even remove extra frames in the animation, if it improves % the total number of pixels in the resulting GIF animation. % % The format of the OptimizePlusImageLayers method is: % % Image *OptimizePlusImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizePlusImageLayers(const Image *image, ExceptionInfo *exception) { return OptimizeLayerFrames(image,OptimizePlusLayer,exception); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e T r a n s p a r e n c y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageTransparency() takes a frame optimized GIF animation, and % compares the overlayed pixels against the disposal image resulting from all % the previous frames in the animation. Any pixel that does not change the % disposal image (and thus does not effect the outcome of an overlay) is made % transparent. % % WARNING: This modifies the current images directly, rather than generate % a new image sequence. % % The format of the OptimizeImageTransperency method is: % % void OptimizeImageTransperency(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence % % o exception: return any errors or warnings in this structure. % */ MagickExport void OptimizeImageTransparency(const Image *image, ExceptionInfo *exception) { Image *dispose_image; register Image *next; /* Run the image through the animation sequence */ 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); next=GetFirstImageInList(image); dispose_image=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return; dispose_image->page=next->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(dispose_image); while ( next != (Image *) NULL ) { Image *current_image; /* Overlay this frame's image over the previous disposal image */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_image=DestroyImage(dispose_image); return; } (void) CompositeImage(current_image,next->matte != MagickFalse ? OverCompositeOp : CopyCompositeOp,next,next->page.x,next->page.y); /* At this point the image would be displayed, for the delay period ** Work out the disposal of the previous image */ if (next->dispose == BackgroundDispose) { RectangleInfo bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds); } if (next->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; } else current_image=DestroyImage(current_image); /* Optimize Transparency of the next frame (if present) */ next=GetNextImageInList(next); if (next != (Image *) NULL) { (void) CompositeImage(next,ChangeMaskCompositeOp,dispose_image, -(next->page.x),-(next->page.y)); } } dispose_image=DestroyImage(dispose_image); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e D u p l i c a t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveDuplicateLayers() removes any image that is exactly the same as the % next image in the given image list. Image size and virtual canvas offset % must also match, though not the virtual canvas size itself. % % No check is made with regards to image disposal setting, though it is the % dispose setting of later image that is kept. Also any time delays are also % added together. As such coalesced image animations should still produce the % same result, though with duplicte frames merged into a single frame. % % The format of the RemoveDuplicateLayers method is: % % void RemoveDuplicateLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveDuplicateLayers(Image **images, ExceptionInfo *exception) { register Image *curr, *next; RectangleInfo bounds; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); curr=GetFirstImageInList(*images); for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next) { if ( curr->columns != next->columns || curr->rows != next->rows || curr->page.x != next->page.x || curr->page.y != next->page.y ) continue; bounds=CompareImageBounds(curr,next,CompareAnyLayer,exception); if ( bounds.x < 0 ) { /* the two images are the same, merge time delays and delete one. */ size_t time; time = curr->delay*1000/curr->ticks_per_second; time += next->delay*1000/next->ticks_per_second; next->ticks_per_second = 100L; next->delay = time*curr->ticks_per_second/1000; next->iterations = curr->iterations; *images = curr; (void) DeleteImageFromList(images); } } *images = GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e Z e r o D e l a y L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveZeroDelayLayers() removes any image that as a zero delay time. Such % images generally represent intermediate or partial updates in GIF % animations used for file optimization. They are not ment to be displayed % to users of the animation. Viewable images in an animation should have a % time delay of 3 or more centi-seconds (hundredths of a second). % % However if all the frames have a zero time delay, then either the animation % is as yet incomplete, or it is not a GIF animation. This a non-sensible % situation, so no image will be removed and a 'Zero Time Animation' warning % (exception) given. % % No warning will be given if no image was removed because all images had an % appropriate non-zero time delay set. % % Due to the special requirements of GIF disposal handling, GIF animations % should be coalesced first, before calling this function, though that is not % a requirement. % % The format of the RemoveZeroDelayLayers method is: % % void RemoveZeroDelayLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveZeroDelayLayers(Image **images, ExceptionInfo *exception) { Image *i; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); i=GetFirstImageInList(*images); for ( ; i != (Image *) NULL; i=GetNextImageInList(i)) if ( i->delay != 0L ) break; if ( i == (Image *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ZeroTimeAnimation","`%s'",GetFirstImageInList(*images)->filename); return; } i=GetFirstImageInList(*images); while ( i != (Image *) NULL ) { if ( i->delay == 0L ) { (void) DeleteImageFromList(&i); *images=i; } else i=GetNextImageInList(i); } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeLayers() compose the source image sequence over the destination % image sequence, starting with the current image in both lists. % % Each layer from the two image lists are composted together until the end of % one of the image lists is reached. The offset of each composition is also % adjusted to match the virtual canvas offsets of each layer. As such the % given offset is relative to the virtual canvas, and not the actual image. % % Composition uses given x and y offsets, as the 'origin' location of the % source images virtual canvas (not the real image) allowing you to compose a % list of 'layer images' into the destiantioni images. This makes it well % sutiable for directly composing 'Clears Frame Animations' or 'Coaleased % Animations' onto a static or other 'Coaleased Animation' destination image % list. GIF disposal handling is not looked at. % % Special case:- If one of the image sequences is the last image (just a % single image remaining), that image is repeatally composed with all the % images in the other image list. Either the source or destination lists may % be the single image, for this situation. % % In the case of a single destination image (or last image given), that image % will ve cloned to match the number of images remaining in the source image % list. % % This is equivelent to the "-layer Composite" Shell API operator. % % % The format of the CompositeLayers method is: % % void CompositeLayers(Image *destination, % const CompositeOperator compose, Image *source, % const ssize_t x_offset, const ssize_t y_offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o destination: the destination images and results % % o source: source image(s) for the layer composition % % o compose, x_offset, y_offset: arguments passed on to CompositeImages() % % o exception: return any errors or warnings in this structure. % */ static inline void CompositeCanvas(Image *destination, const CompositeOperator compose, Image *source,ssize_t x_offset, ssize_t y_offset ) { x_offset+=source->page.x-destination->page.x; y_offset+=source->page.y-destination->page.y; (void) CompositeImage(destination,compose,source,x_offset,y_offset); } MagickExport void CompositeLayers(Image *destination, const CompositeOperator compose, Image *source,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { assert(destination != (Image *) NULL); assert(destination->signature == MagickCoreSignature); assert(source != (Image *) NULL); assert(source->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (source->debug != MagickFalse || destination->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s - %s", source->filename,destination->filename); /* Overlay single source image over destation image/list */ if ( source->next == (Image *) NULL ) while ( destination != (Image *) NULL ) { CompositeCanvas(destination,compose,source,x_offset,y_offset); destination=GetNextImageInList(destination); } /* Overlay source image list over single destination Generating multiple clones of destination image to match source list. Original Destination image becomes first image of generated list. As such the image list pointer does not require any change in caller. Some animation attributes however also needs coping in this case. */ else if ( destination->next == (Image *) NULL ) { Image *dest = CloneImage(destination,0,0,MagickTrue,exception); CompositeCanvas(destination,compose,source,x_offset,y_offset); /* copy source image attributes ? */ if ( source->next != (Image *) NULL ) { destination->delay = source->delay; destination->iterations = source->iterations; } source=GetNextImageInList(source); while ( source != (Image *) NULL ) { AppendImageToList(&destination, CloneImage(dest,0,0,MagickTrue,exception)); destination=GetLastImageInList(destination); CompositeCanvas(destination,compose,source,x_offset,y_offset); destination->delay = source->delay; destination->iterations = source->iterations; source=GetNextImageInList(source); } dest=DestroyImage(dest); } /* Overlay a source image list over a destination image list until either list runs out of images. (Does not repeat) */ else while ( source != (Image *) NULL && destination != (Image *) NULL ) { CompositeCanvas(destination,compose,source,x_offset,y_offset); source=GetNextImageInList(source); destination=GetNextImageInList(destination); } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e r g e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MergeImageLayers() composes all the image layers from the current given % image onward to produce a single image of the merged layers. % % The inital canvas's size depends on the given ImageLayerMethod, and is % initialized using the first images background color. The images % are then compositied onto that image in sequence using the given % composition that has been assigned to each individual image. % % The format of the MergeImageLayers is: % % Image *MergeImageLayers(const Image *image, % const ImageLayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image list to be composited together % % o method: the method of selecting the size of the initial canvas. % % MergeLayer: Merge all layers onto a canvas just large enough % to hold all the actual images. The virtual canvas of the % first image is preserved but otherwise ignored. % % FlattenLayer: Use the virtual canvas size of first image. % Images which fall outside this canvas is clipped. % This can be used to 'fill out' a given virtual canvas. % % MosaicLayer: Start with the virtual canvas of the first image, % enlarging left and right edges to contain all images. % Images with negative offsets will be clipped. % % TrimBoundsLayer: Determine the overall bounds of all the image % layers just as in "MergeLayer", then adjust the the canvas % and offsets to be relative to those bounds, without overlaying % the images. % % WARNING: a new image is not returned, the original image % sequence page data is modified instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MergeImageLayers(Image *image, const ImageLayerMethod method,ExceptionInfo *exception) { #define MergeLayersTag "Merge/Layers" Image *canvas; MagickBooleanType proceed; RectangleInfo page; register const Image *next; size_t number_images, height, width; ssize_t scene; 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); /* Determine canvas image size, and its virtual canvas size and offset. */ page=image->page; width=image->columns; height=image->rows; switch (method) { case TrimBoundsLayer: case MergeLayer: default: { next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (page.x > next->page.x) { width+=page.x-next->page.x; page.x=next->page.x; } if (page.y > next->page.y) { height+=page.y-next->page.y; page.y=next->page.y; } if ((ssize_t) width < (next->page.x+(ssize_t) next->columns-page.x)) width=(size_t) next->page.x+(ssize_t) next->columns-page.x; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows-page.y)) height=(size_t) next->page.y+(ssize_t) next->rows-page.y; } break; } case FlattenLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; page.x=0; page.y=0; break; } case MosaicLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { if ((ssize_t) width < (next->page.x+(ssize_t) next->columns)) width=(size_t) next->page.x+next->columns; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows)) height=(size_t) next->page.y+next->rows; } page.width=width; page.height=height; page.x=0; page.y=0; break; } } /* Set virtual canvas size if not defined. */ if (page.width == 0) page.width=page.x < 0 ? width : width+page.x; if (page.height == 0) page.height=page.y < 0 ? height : height+page.y; /* Handle "TrimBoundsLayer" method separately to normal 'layer merge'. */ if (method == TrimBoundsLayer) { number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { image->page.x-=page.x; image->page.y-=page.y; image->page.width=width; image->page.height=height; proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return((Image *) NULL); } /* Create canvas size of width and height, and background color. */ canvas=CloneImage(image,width,height,MagickTrue,exception); if (canvas == (Image *) NULL) return((Image *) NULL); (void) SetImageBackgroundColor(canvas); canvas->page=page; canvas->dispose=UndefinedDispose; /* Compose images onto canvas, with progress monitor */ number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { (void) CompositeImage(canvas,image->compose,image,image->page.x- canvas->page.x,image->page.y-canvas->page.y); proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return(canvas); }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_952_0
crossvul-cpp_data_bad_3035_0
/* * Edgeport USB Serial Converter driver * * Copyright (C) 2000-2002 Inside Out Networks, All rights reserved. * Copyright (C) 2001-2002 Greg Kroah-Hartman <greg@kroah.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. * * Supports the following devices: * EP/1 EP/2 EP/4 EP/21 EP/22 EP/221 EP/42 EP/421 WATCHPORT * * For questions or problems with this driver, contact Inside Out * Networks technical support, or Peter Berger <pberger@brimson.com>, * or Al Borchers <alborchers@steinerpoint.com>. */ #include <linux/kernel.h> #include <linux/jiffies.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/mutex.h> #include <linux/serial.h> #include <linux/swab.h> #include <linux/kfifo.h> #include <linux/ioctl.h> #include <linux/firmware.h> #include <linux/uaccess.h> #include <linux/usb.h> #include <linux/usb/serial.h> #include "io_16654.h" #include "io_usbvend.h" #include "io_ti.h" #define DRIVER_AUTHOR "Greg Kroah-Hartman <greg@kroah.com> and David Iacovelli" #define DRIVER_DESC "Edgeport USB Serial Driver" #define EPROM_PAGE_SIZE 64 /* different hardware types */ #define HARDWARE_TYPE_930 0 #define HARDWARE_TYPE_TIUMP 1 /* IOCTL_PRIVATE_TI_GET_MODE Definitions */ #define TI_MODE_CONFIGURING 0 /* Device has not entered start device */ #define TI_MODE_BOOT 1 /* Staying in boot mode */ #define TI_MODE_DOWNLOAD 2 /* Made it to download mode */ #define TI_MODE_TRANSITIONING 3 /* * Currently in boot mode but * transitioning to download mode */ /* read urb state */ #define EDGE_READ_URB_RUNNING 0 #define EDGE_READ_URB_STOPPING 1 #define EDGE_READ_URB_STOPPED 2 #define EDGE_CLOSING_WAIT 4000 /* in .01 sec */ /* Product information read from the Edgeport */ struct product_info { int TiMode; /* Current TI Mode */ __u8 hardware_type; /* Type of hardware */ } __attribute__((packed)); /* * Edgeport firmware header * * "build_number" has been set to 0 in all three of the images I have * seen, and Digi Tech Support suggests that it is safe to ignore it. * * "length" is the number of bytes of actual data following the header. * * "checksum" is the low order byte resulting from adding the values of * all the data bytes. */ struct edgeport_fw_hdr { u8 major_version; u8 minor_version; __le16 build_number; __le16 length; u8 checksum; } __packed; struct edgeport_port { __u16 uart_base; __u16 dma_address; __u8 shadow_msr; __u8 shadow_mcr; __u8 shadow_lsr; __u8 lsr_mask; __u32 ump_read_timeout; /* * Number of milliseconds the UMP will * wait without data before completing * a read short */ int baud_rate; int close_pending; int lsr_event; struct edgeport_serial *edge_serial; struct usb_serial_port *port; __u8 bUartMode; /* Port type, 0: RS232, etc. */ spinlock_t ep_lock; int ep_read_urb_state; int ep_write_urb_in_use; }; struct edgeport_serial { struct product_info product_info; u8 TI_I2C_Type; /* Type of I2C in UMP */ u8 TiReadI2C; /* * Set to TRUE if we have read the * I2c in Boot Mode */ struct mutex es_lock; int num_ports_open; struct usb_serial *serial; struct delayed_work heartbeat_work; int fw_version; bool use_heartbeat; }; /* Devices that this driver supports */ static const struct usb_device_id edgeport_1port_id_table[] = { { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROXIMITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOTION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOISTURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_TEMPERATURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_HUMIDITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_POWER) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_LIGHT) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_RADIATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_DISTANCE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_ACCELERATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROX_DIST) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_HP4CD) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_PCI) }, { } }; static const struct usb_device_id edgeport_2port_id_table[] = { { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_421) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_42) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_221C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21C) }, /* The 4, 8 and 16 port devices show up as multiple 2 port devices */ { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416B) }, { } }; /* Devices that this driver supports */ static const struct usb_device_id id_table_combined[] = { { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROXIMITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOTION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOISTURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_TEMPERATURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_HUMIDITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_POWER) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_LIGHT) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_RADIATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_DISTANCE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_ACCELERATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROX_DIST) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_HP4CD) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_PCI) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_421) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_42) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_221C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416B) }, { } }; MODULE_DEVICE_TABLE(usb, id_table_combined); static int closing_wait = EDGE_CLOSING_WAIT; static bool ignore_cpu_rev; static int default_uart_mode; /* RS232 */ static void edge_tty_recv(struct usb_serial_port *port, unsigned char *data, int length); static void stop_read(struct edgeport_port *edge_port); static int restart_read(struct edgeport_port *edge_port); static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios); static void edge_send(struct usb_serial_port *port, struct tty_struct *tty); static int do_download_mode(struct edgeport_serial *serial, const struct firmware *fw); static int do_boot_mode(struct edgeport_serial *serial, const struct firmware *fw); /* sysfs attributes */ static int edge_create_sysfs_attrs(struct usb_serial_port *port); static int edge_remove_sysfs_attrs(struct usb_serial_port *port); /* * Some release of Edgeport firmware "down3.bin" after version 4.80 * introduced code to automatically disconnect idle devices on some * Edgeport models after periods of inactivity, typically ~60 seconds. * This occurs without regard to whether ports on the device are open * or not. Digi International Tech Support suggested: * * 1. Adding driver "heartbeat" code to reset the firmware timer by * requesting a descriptor record every 15 seconds, which should be * effective with newer firmware versions that require it, and benign * with older versions that do not. In practice 40 seconds seems often * enough. * 2. The heartbeat code is currently required only on Edgeport/416 models. */ #define FW_HEARTBEAT_VERSION_CUTOFF ((4 << 8) + 80) #define FW_HEARTBEAT_SECS 40 /* Timeouts in msecs: firmware downloads take longer */ #define TI_VSEND_TIMEOUT_DEFAULT 1000 #define TI_VSEND_TIMEOUT_FW_DOWNLOAD 10000 static int ti_vread_sync(struct usb_device *dev, __u8 request, __u16 value, __u16 index, u8 *data, int size) { int status; status = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), request, (USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN), value, index, data, size, 1000); if (status < 0) return status; if (status != size) { dev_dbg(&dev->dev, "%s - wanted to write %d, but only wrote %d\n", __func__, size, status); return -ECOMM; } return 0; } static int ti_vsend_sync(struct usb_device *dev, u8 request, u16 value, u16 index, u8 *data, int size, int timeout) { int status; status = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), request, (USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT), value, index, data, size, timeout); if (status < 0) return status; if (status != size) { dev_dbg(&dev->dev, "%s - wanted to write %d, but only wrote %d\n", __func__, size, status); return -ECOMM; } return 0; } static int send_cmd(struct usb_device *dev, __u8 command, __u8 moduleid, __u16 value, u8 *data, int size) { return ti_vsend_sync(dev, command, value, moduleid, data, size, TI_VSEND_TIMEOUT_DEFAULT); } /* clear tx/rx buffers and fifo in TI UMP */ static int purge_port(struct usb_serial_port *port, __u16 mask) { int port_number = port->port_number; dev_dbg(&port->dev, "%s - port %d, mask %x\n", __func__, port_number, mask); return send_cmd(port->serial->dev, UMPC_PURGE_PORT, (__u8)(UMPM_UART1_PORT + port_number), mask, NULL, 0); } /** * read_download_mem - Read edgeport memory from TI chip * @dev: usb device pointer * @start_address: Device CPU address at which to read * @length: Length of above data * @address_type: Can read both XDATA and I2C * @buffer: pointer to input data buffer */ static int read_download_mem(struct usb_device *dev, int start_address, int length, __u8 address_type, __u8 *buffer) { int status = 0; __u8 read_length; u16 be_start_address; dev_dbg(&dev->dev, "%s - @ %x for %d\n", __func__, start_address, length); /* * Read in blocks of 64 bytes * (TI firmware can't handle more than 64 byte reads) */ while (length) { if (length > 64) read_length = 64; else read_length = (__u8)length; if (read_length > 1) { dev_dbg(&dev->dev, "%s - @ %x for %d\n", __func__, start_address, read_length); } /* * NOTE: Must use swab as wIndex is sent in little-endian * byte order regardless of host byte order. */ be_start_address = swab16((u16)start_address); status = ti_vread_sync(dev, UMPC_MEMORY_READ, (__u16)address_type, be_start_address, buffer, read_length); if (status) { dev_dbg(&dev->dev, "%s - ERROR %x\n", __func__, status); return status; } if (read_length > 1) usb_serial_debug_data(&dev->dev, __func__, read_length, buffer); /* Update pointers/length */ start_address += read_length; buffer += read_length; length -= read_length; } return status; } static int read_ram(struct usb_device *dev, int start_address, int length, __u8 *buffer) { return read_download_mem(dev, start_address, length, DTK_ADDR_SPACE_XDATA, buffer); } /* Read edgeport memory to a given block */ static int read_boot_mem(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { int status = 0; int i; for (i = 0; i < length; i++) { status = ti_vread_sync(serial->serial->dev, UMPC_MEMORY_READ, serial->TI_I2C_Type, (__u16)(start_address+i), &buffer[i], 0x01); if (status) { dev_dbg(&serial->serial->dev->dev, "%s - ERROR %x\n", __func__, status); return status; } } dev_dbg(&serial->serial->dev->dev, "%s - start_address = %x, length = %d\n", __func__, start_address, length); usb_serial_debug_data(&serial->serial->dev->dev, __func__, length, buffer); serial->TiReadI2C = 1; return status; } /* Write given block to TI EPROM memory */ static int write_boot_mem(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { int status = 0; int i; u8 *temp; /* Must do a read before write */ if (!serial->TiReadI2C) { temp = kmalloc(1, GFP_KERNEL); if (!temp) return -ENOMEM; status = read_boot_mem(serial, 0, 1, temp); kfree(temp); if (status) return status; } for (i = 0; i < length; ++i) { status = ti_vsend_sync(serial->serial->dev, UMPC_MEMORY_WRITE, buffer[i], (u16)(i + start_address), NULL, 0, TI_VSEND_TIMEOUT_DEFAULT); if (status) return status; } dev_dbg(&serial->serial->dev->dev, "%s - start_sddr = %x, length = %d\n", __func__, start_address, length); usb_serial_debug_data(&serial->serial->dev->dev, __func__, length, buffer); return status; } /* Write edgeport I2C memory to TI chip */ static int write_i2c_mem(struct edgeport_serial *serial, int start_address, int length, __u8 address_type, __u8 *buffer) { struct device *dev = &serial->serial->dev->dev; int status = 0; int write_length; u16 be_start_address; /* We can only send a maximum of 1 aligned byte page at a time */ /* calculate the number of bytes left in the first page */ write_length = EPROM_PAGE_SIZE - (start_address & (EPROM_PAGE_SIZE - 1)); if (write_length > length) write_length = length; dev_dbg(dev, "%s - BytesInFirstPage Addr = %x, length = %d\n", __func__, start_address, write_length); usb_serial_debug_data(dev, __func__, write_length, buffer); /* * Write first page. * * NOTE: Must use swab as wIndex is sent in little-endian byte order * regardless of host byte order. */ be_start_address = swab16((u16)start_address); status = ti_vsend_sync(serial->serial->dev, UMPC_MEMORY_WRITE, (u16)address_type, be_start_address, buffer, write_length, TI_VSEND_TIMEOUT_DEFAULT); if (status) { dev_dbg(dev, "%s - ERROR %d\n", __func__, status); return status; } length -= write_length; start_address += write_length; buffer += write_length; /* * We should be aligned now -- can write max page size bytes at a * time. */ while (length) { if (length > EPROM_PAGE_SIZE) write_length = EPROM_PAGE_SIZE; else write_length = length; dev_dbg(dev, "%s - Page Write Addr = %x, length = %d\n", __func__, start_address, write_length); usb_serial_debug_data(dev, __func__, write_length, buffer); /* * Write next page. * * NOTE: Must use swab as wIndex is sent in little-endian byte * order regardless of host byte order. */ be_start_address = swab16((u16)start_address); status = ti_vsend_sync(serial->serial->dev, UMPC_MEMORY_WRITE, (u16)address_type, be_start_address, buffer, write_length, TI_VSEND_TIMEOUT_DEFAULT); if (status) { dev_err(dev, "%s - ERROR %d\n", __func__, status); return status; } length -= write_length; start_address += write_length; buffer += write_length; } return status; } /* * Examine the UMP DMA registers and LSR * * Check the MSBit of the X and Y DMA byte count registers. * A zero in this bit indicates that the TX DMA buffers are empty * then check the TX Empty bit in the UART. */ static int tx_active(struct edgeport_port *port) { int status; struct out_endpoint_desc_block *oedb; __u8 *lsr; int bytes_left = 0; oedb = kmalloc(sizeof(*oedb), GFP_KERNEL); if (!oedb) return -ENOMEM; /* * Sigh, that's right, just one byte, as not all platforms can * do DMA from stack */ lsr = kmalloc(1, GFP_KERNEL); if (!lsr) { kfree(oedb); return -ENOMEM; } /* Read the DMA Count Registers */ status = read_ram(port->port->serial->dev, port->dma_address, sizeof(*oedb), (void *)oedb); if (status) goto exit_is_tx_active; dev_dbg(&port->port->dev, "%s - XByteCount 0x%X\n", __func__, oedb->XByteCount); /* and the LSR */ status = read_ram(port->port->serial->dev, port->uart_base + UMPMEM_OFFS_UART_LSR, 1, lsr); if (status) goto exit_is_tx_active; dev_dbg(&port->port->dev, "%s - LSR = 0x%X\n", __func__, *lsr); /* If either buffer has data or we are transmitting then return TRUE */ if ((oedb->XByteCount & 0x80) != 0) bytes_left += 64; if ((*lsr & UMP_UART_LSR_TX_MASK) == 0) bytes_left += 1; /* We return Not Active if we get any kind of error */ exit_is_tx_active: dev_dbg(&port->port->dev, "%s - return %d\n", __func__, bytes_left); kfree(lsr); kfree(oedb); return bytes_left; } static int choose_config(struct usb_device *dev) { /* * There may be multiple configurations on this device, in which case * we would need to read and parse all of them to find out which one * we want. However, we just support one config at this point, * configuration # 1, which is Config Descriptor 0. */ dev_dbg(&dev->dev, "%s - Number of Interfaces = %d\n", __func__, dev->config->desc.bNumInterfaces); dev_dbg(&dev->dev, "%s - MAX Power = %d\n", __func__, dev->config->desc.bMaxPower * 2); if (dev->config->desc.bNumInterfaces != 1) { dev_err(&dev->dev, "%s - bNumInterfaces is not 1, ERROR!\n", __func__); return -ENODEV; } return 0; } static int read_rom(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { int status; if (serial->product_info.TiMode == TI_MODE_DOWNLOAD) { status = read_download_mem(serial->serial->dev, start_address, length, serial->TI_I2C_Type, buffer); } else { status = read_boot_mem(serial, start_address, length, buffer); } return status; } static int write_rom(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { if (serial->product_info.TiMode == TI_MODE_BOOT) return write_boot_mem(serial, start_address, length, buffer); if (serial->product_info.TiMode == TI_MODE_DOWNLOAD) return write_i2c_mem(serial, start_address, length, serial->TI_I2C_Type, buffer); return -EINVAL; } /* Read a descriptor header from I2C based on type */ static int get_descriptor_addr(struct edgeport_serial *serial, int desc_type, struct ti_i2c_desc *rom_desc) { int start_address; int status; /* Search for requested descriptor in I2C */ start_address = 2; do { status = read_rom(serial, start_address, sizeof(struct ti_i2c_desc), (__u8 *)rom_desc); if (status) return 0; if (rom_desc->Type == desc_type) return start_address; start_address = start_address + sizeof(struct ti_i2c_desc) + le16_to_cpu(rom_desc->Size); } while ((start_address < TI_MAX_I2C_SIZE) && rom_desc->Type); return 0; } /* Validate descriptor checksum */ static int valid_csum(struct ti_i2c_desc *rom_desc, __u8 *buffer) { __u16 i; __u8 cs = 0; for (i = 0; i < le16_to_cpu(rom_desc->Size); i++) cs = (__u8)(cs + buffer[i]); if (cs != rom_desc->CheckSum) { pr_debug("%s - Mismatch %x - %x", __func__, rom_desc->CheckSum, cs); return -EINVAL; } return 0; } /* Make sure that the I2C image is good */ static int check_i2c_image(struct edgeport_serial *serial) { struct device *dev = &serial->serial->dev->dev; int status = 0; struct ti_i2c_desc *rom_desc; int start_address = 2; __u8 *buffer; __u16 ttype; rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL); if (!rom_desc) return -ENOMEM; buffer = kmalloc(TI_MAX_I2C_SIZE, GFP_KERNEL); if (!buffer) { kfree(rom_desc); return -ENOMEM; } /* Read the first byte (Signature0) must be 0x52 or 0x10 */ status = read_rom(serial, 0, 1, buffer); if (status) goto out; if (*buffer != UMP5152 && *buffer != UMP3410) { dev_err(dev, "%s - invalid buffer signature\n", __func__); status = -ENODEV; goto out; } do { /* Validate the I2C */ status = read_rom(serial, start_address, sizeof(struct ti_i2c_desc), (__u8 *)rom_desc); if (status) break; if ((start_address + sizeof(struct ti_i2c_desc) + le16_to_cpu(rom_desc->Size)) > TI_MAX_I2C_SIZE) { status = -ENODEV; dev_dbg(dev, "%s - structure too big, erroring out.\n", __func__); break; } dev_dbg(dev, "%s Type = 0x%x\n", __func__, rom_desc->Type); /* Skip type 2 record */ ttype = rom_desc->Type & 0x0f; if (ttype != I2C_DESC_TYPE_FIRMWARE_BASIC && ttype != I2C_DESC_TYPE_FIRMWARE_AUTO) { /* Read the descriptor data */ status = read_rom(serial, start_address + sizeof(struct ti_i2c_desc), le16_to_cpu(rom_desc->Size), buffer); if (status) break; status = valid_csum(rom_desc, buffer); if (status) break; } start_address = start_address + sizeof(struct ti_i2c_desc) + le16_to_cpu(rom_desc->Size); } while ((rom_desc->Type != I2C_DESC_TYPE_ION) && (start_address < TI_MAX_I2C_SIZE)); if ((rom_desc->Type != I2C_DESC_TYPE_ION) || (start_address > TI_MAX_I2C_SIZE)) status = -ENODEV; out: kfree(buffer); kfree(rom_desc); return status; } static int get_manuf_info(struct edgeport_serial *serial, __u8 *buffer) { int status; int start_address; struct ti_i2c_desc *rom_desc; struct edge_ti_manuf_descriptor *desc; struct device *dev = &serial->serial->dev->dev; rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL); if (!rom_desc) return -ENOMEM; start_address = get_descriptor_addr(serial, I2C_DESC_TYPE_ION, rom_desc); if (!start_address) { dev_dbg(dev, "%s - Edge Descriptor not found in I2C\n", __func__); status = -ENODEV; goto exit; } /* Read the descriptor data */ status = read_rom(serial, start_address+sizeof(struct ti_i2c_desc), le16_to_cpu(rom_desc->Size), buffer); if (status) goto exit; status = valid_csum(rom_desc, buffer); desc = (struct edge_ti_manuf_descriptor *)buffer; dev_dbg(dev, "%s - IonConfig 0x%x\n", __func__, desc->IonConfig); dev_dbg(dev, "%s - Version %d\n", __func__, desc->Version); dev_dbg(dev, "%s - Cpu/Board 0x%x\n", __func__, desc->CpuRev_BoardRev); dev_dbg(dev, "%s - NumPorts %d\n", __func__, desc->NumPorts); dev_dbg(dev, "%s - NumVirtualPorts %d\n", __func__, desc->NumVirtualPorts); dev_dbg(dev, "%s - TotalPorts %d\n", __func__, desc->TotalPorts); exit: kfree(rom_desc); return status; } /* Build firmware header used for firmware update */ static int build_i2c_fw_hdr(u8 *header, const struct firmware *fw) { __u8 *buffer; int buffer_size; int i; __u8 cs = 0; struct ti_i2c_desc *i2c_header; struct ti_i2c_image_header *img_header; struct ti_i2c_firmware_rec *firmware_rec; struct edgeport_fw_hdr *fw_hdr = (struct edgeport_fw_hdr *)fw->data; /* * In order to update the I2C firmware we must change the type 2 record * to type 0xF2. This will force the UMP to come up in Boot Mode. * Then while in boot mode, the driver will download the latest * firmware (padded to 15.5k) into the UMP ram. And finally when the * device comes back up in download mode the driver will cause the new * firmware to be copied from the UMP Ram to I2C and the firmware will * update the record type from 0xf2 to 0x02. */ /* * Allocate a 15.5k buffer + 2 bytes for version number (Firmware * Record) */ buffer_size = (((1024 * 16) - 512 ) + sizeof(struct ti_i2c_firmware_rec)); buffer = kmalloc(buffer_size, GFP_KERNEL); if (!buffer) return -ENOMEM; /* Set entire image of 0xffs */ memset(buffer, 0xff, buffer_size); /* Copy version number into firmware record */ firmware_rec = (struct ti_i2c_firmware_rec *)buffer; firmware_rec->Ver_Major = fw_hdr->major_version; firmware_rec->Ver_Minor = fw_hdr->minor_version; /* Pointer to fw_down memory image */ img_header = (struct ti_i2c_image_header *)&fw->data[4]; memcpy(buffer + sizeof(struct ti_i2c_firmware_rec), &fw->data[4 + sizeof(struct ti_i2c_image_header)], le16_to_cpu(img_header->Length)); for (i=0; i < buffer_size; i++) { cs = (__u8)(cs + buffer[i]); } kfree(buffer); /* Build new header */ i2c_header = (struct ti_i2c_desc *)header; firmware_rec = (struct ti_i2c_firmware_rec*)i2c_header->Data; i2c_header->Type = I2C_DESC_TYPE_FIRMWARE_BLANK; i2c_header->Size = cpu_to_le16(buffer_size); i2c_header->CheckSum = cs; firmware_rec->Ver_Major = fw_hdr->major_version; firmware_rec->Ver_Minor = fw_hdr->minor_version; return 0; } /* Try to figure out what type of I2c we have */ static int i2c_type_bootmode(struct edgeport_serial *serial) { struct device *dev = &serial->serial->dev->dev; int status; u8 *data; data = kmalloc(1, GFP_KERNEL); if (!data) return -ENOMEM; /* Try to read type 2 */ status = ti_vread_sync(serial->serial->dev, UMPC_MEMORY_READ, DTK_ADDR_SPACE_I2C_TYPE_II, 0, data, 0x01); if (status) dev_dbg(dev, "%s - read 2 status error = %d\n", __func__, status); else dev_dbg(dev, "%s - read 2 data = 0x%x\n", __func__, *data); if ((!status) && (*data == UMP5152 || *data == UMP3410)) { dev_dbg(dev, "%s - ROM_TYPE_II\n", __func__); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; goto out; } /* Try to read type 3 */ status = ti_vread_sync(serial->serial->dev, UMPC_MEMORY_READ, DTK_ADDR_SPACE_I2C_TYPE_III, 0, data, 0x01); if (status) dev_dbg(dev, "%s - read 3 status error = %d\n", __func__, status); else dev_dbg(dev, "%s - read 2 data = 0x%x\n", __func__, *data); if ((!status) && (*data == UMP5152 || *data == UMP3410)) { dev_dbg(dev, "%s - ROM_TYPE_III\n", __func__); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_III; goto out; } dev_dbg(dev, "%s - Unknown\n", __func__); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; status = -ENODEV; out: kfree(data); return status; } static int bulk_xfer(struct usb_serial *serial, void *buffer, int length, int *num_sent) { int status; status = usb_bulk_msg(serial->dev, usb_sndbulkpipe(serial->dev, serial->port[0]->bulk_out_endpointAddress), buffer, length, num_sent, 1000); return status; } /* Download given firmware image to the device (IN BOOT MODE) */ static int download_code(struct edgeport_serial *serial, __u8 *image, int image_length) { int status = 0; int pos; int transfer; int done; /* Transfer firmware image */ for (pos = 0; pos < image_length; ) { /* Read the next buffer from file */ transfer = image_length - pos; if (transfer > EDGE_FW_BULK_MAX_PACKET_SIZE) transfer = EDGE_FW_BULK_MAX_PACKET_SIZE; /* Transfer data */ status = bulk_xfer(serial->serial, &image[pos], transfer, &done); if (status) break; /* Advance buffer pointer */ pos += done; } return status; } /* FIXME!!! */ static int config_boot_dev(struct usb_device *dev) { return 0; } static int ti_cpu_rev(struct edge_ti_manuf_descriptor *desc) { return TI_GET_CPU_REVISION(desc->CpuRev_BoardRev); } static int check_fw_sanity(struct edgeport_serial *serial, const struct firmware *fw) { u16 length_total; u8 checksum = 0; int pos; struct device *dev = &serial->serial->interface->dev; struct edgeport_fw_hdr *fw_hdr = (struct edgeport_fw_hdr *)fw->data; if (fw->size < sizeof(struct edgeport_fw_hdr)) { dev_err(dev, "incomplete fw header\n"); return -EINVAL; } length_total = le16_to_cpu(fw_hdr->length) + sizeof(struct edgeport_fw_hdr); if (fw->size != length_total) { dev_err(dev, "bad fw size (expected: %u, got: %zu)\n", length_total, fw->size); return -EINVAL; } for (pos = sizeof(struct edgeport_fw_hdr); pos < fw->size; ++pos) checksum += fw->data[pos]; if (checksum != fw_hdr->checksum) { dev_err(dev, "bad fw checksum (expected: 0x%x, got: 0x%x)\n", fw_hdr->checksum, checksum); return -EINVAL; } return 0; } /* * DownloadTIFirmware - Download run-time operating firmware to the TI5052 * * This routine downloads the main operating code into the TI5052, using the * boot code already burned into E2PROM or ROM. */ static int download_fw(struct edgeport_serial *serial) { struct device *dev = &serial->serial->interface->dev; int status = 0; struct usb_interface_descriptor *interface; const struct firmware *fw; const char *fw_name = "edgeport/down3.bin"; struct edgeport_fw_hdr *fw_hdr; status = request_firmware(&fw, fw_name, dev); if (status) { dev_err(dev, "Failed to load image \"%s\" err %d\n", fw_name, status); return status; } if (check_fw_sanity(serial, fw)) { status = -EINVAL; goto out; } fw_hdr = (struct edgeport_fw_hdr *)fw->data; /* If on-board version is newer, "fw_version" will be updated later. */ serial->fw_version = (fw_hdr->major_version << 8) + fw_hdr->minor_version; /* * This routine is entered by both the BOOT mode and the Download mode * We can determine which code is running by the reading the config * descriptor and if we have only one bulk pipe it is in boot mode */ serial->product_info.hardware_type = HARDWARE_TYPE_TIUMP; /* Default to type 2 i2c */ serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; status = choose_config(serial->serial->dev); if (status) goto out; interface = &serial->serial->interface->cur_altsetting->desc; if (!interface) { dev_err(dev, "%s - no interface set, error!\n", __func__); status = -ENODEV; goto out; } /* * Setup initial mode -- the default mode 0 is TI_MODE_CONFIGURING * if we have more than one endpoint we are definitely in download * mode */ if (interface->bNumEndpoints > 1) { serial->product_info.TiMode = TI_MODE_DOWNLOAD; status = do_download_mode(serial, fw); } else { /* Otherwise we will remain in configuring mode */ serial->product_info.TiMode = TI_MODE_CONFIGURING; status = do_boot_mode(serial, fw); } out: release_firmware(fw); return status; } static int do_download_mode(struct edgeport_serial *serial, const struct firmware *fw) { struct device *dev = &serial->serial->interface->dev; int status = 0; int start_address; struct edge_ti_manuf_descriptor *ti_manuf_desc; int download_cur_ver; int download_new_ver; struct edgeport_fw_hdr *fw_hdr = (struct edgeport_fw_hdr *)fw->data; struct ti_i2c_desc *rom_desc; dev_dbg(dev, "%s - RUNNING IN DOWNLOAD MODE\n", __func__); status = check_i2c_image(serial); if (status) { dev_dbg(dev, "%s - DOWNLOAD MODE -- BAD I2C\n", __func__); return status; } /* * Validate Hardware version number * Read Manufacturing Descriptor from TI Based Edgeport */ ti_manuf_desc = kmalloc(sizeof(*ti_manuf_desc), GFP_KERNEL); if (!ti_manuf_desc) return -ENOMEM; status = get_manuf_info(serial, (__u8 *)ti_manuf_desc); if (status) { kfree(ti_manuf_desc); return status; } /* Check version number of ION descriptor */ if (!ignore_cpu_rev && ti_cpu_rev(ti_manuf_desc) < 2) { dev_dbg(dev, "%s - Wrong CPU Rev %d (Must be 2)\n", __func__, ti_cpu_rev(ti_manuf_desc)); kfree(ti_manuf_desc); return -EINVAL; } rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL); if (!rom_desc) { kfree(ti_manuf_desc); return -ENOMEM; } /* Search for type 2 record (firmware record) */ start_address = get_descriptor_addr(serial, I2C_DESC_TYPE_FIRMWARE_BASIC, rom_desc); if (start_address != 0) { struct ti_i2c_firmware_rec *firmware_version; u8 *record; dev_dbg(dev, "%s - Found Type FIRMWARE (Type 2) record\n", __func__); firmware_version = kmalloc(sizeof(*firmware_version), GFP_KERNEL); if (!firmware_version) { kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } /* * Validate version number * Read the descriptor data */ status = read_rom(serial, start_address + sizeof(struct ti_i2c_desc), sizeof(struct ti_i2c_firmware_rec), (__u8 *)firmware_version); if (status) { kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return status; } /* * Check version number of download with current * version in I2c */ download_cur_ver = (firmware_version->Ver_Major << 8) + (firmware_version->Ver_Minor); download_new_ver = (fw_hdr->major_version << 8) + (fw_hdr->minor_version); dev_dbg(dev, "%s - >> FW Versions Device %d.%d Driver %d.%d\n", __func__, firmware_version->Ver_Major, firmware_version->Ver_Minor, fw_hdr->major_version, fw_hdr->minor_version); /* * Check if we have an old version in the I2C and * update if necessary */ if (download_cur_ver < download_new_ver) { dev_dbg(dev, "%s - Update I2C dld from %d.%d to %d.%d\n", __func__, firmware_version->Ver_Major, firmware_version->Ver_Minor, fw_hdr->major_version, fw_hdr->minor_version); record = kmalloc(1, GFP_KERNEL); if (!record) { kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } /* * In order to update the I2C firmware we must * change the type 2 record to type 0xF2. This * will force the UMP to come up in Boot Mode. * Then while in boot mode, the driver will * download the latest firmware (padded to * 15.5k) into the UMP ram. Finally when the * device comes back up in download mode the * driver will cause the new firmware to be * copied from the UMP Ram to I2C and the * firmware will update the record type from * 0xf2 to 0x02. */ *record = I2C_DESC_TYPE_FIRMWARE_BLANK; /* * Change the I2C Firmware record type to * 0xf2 to trigger an update */ status = write_rom(serial, start_address, sizeof(*record), record); if (status) { kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return status; } /* * verify the write -- must do this in order * for write to complete before we do the * hardware reset */ status = read_rom(serial, start_address, sizeof(*record), record); if (status) { kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return status; } if (*record != I2C_DESC_TYPE_FIRMWARE_BLANK) { dev_err(dev, "%s - error resetting device\n", __func__); kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return -ENODEV; } dev_dbg(dev, "%s - HARDWARE RESET\n", __func__); /* Reset UMP -- Back to BOOT MODE */ status = ti_vsend_sync(serial->serial->dev, UMPC_HARDWARE_RESET, 0, 0, NULL, 0, TI_VSEND_TIMEOUT_DEFAULT); dev_dbg(dev, "%s - HARDWARE RESET return %d\n", __func__, status); /* return an error on purpose. */ kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return -ENODEV; } /* Same or newer fw version is already loaded */ serial->fw_version = download_cur_ver; kfree(firmware_version); } /* Search for type 0xF2 record (firmware blank record) */ else { start_address = get_descriptor_addr(serial, I2C_DESC_TYPE_FIRMWARE_BLANK, rom_desc); if (start_address != 0) { #define HEADER_SIZE (sizeof(struct ti_i2c_desc) + \ sizeof(struct ti_i2c_firmware_rec)) __u8 *header; __u8 *vheader; header = kmalloc(HEADER_SIZE, GFP_KERNEL); if (!header) { kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } vheader = kmalloc(HEADER_SIZE, GFP_KERNEL); if (!vheader) { kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } dev_dbg(dev, "%s - Found Type BLANK FIRMWARE (Type F2) record\n", __func__); /* * In order to update the I2C firmware we must change * the type 2 record to type 0xF2. This will force the * UMP to come up in Boot Mode. Then while in boot * mode, the driver will download the latest firmware * (padded to 15.5k) into the UMP ram. Finally when the * device comes back up in download mode the driver * will cause the new firmware to be copied from the * UMP Ram to I2C and the firmware will update the * record type from 0xf2 to 0x02. */ status = build_i2c_fw_hdr(header, fw); if (status) { kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -EINVAL; } /* * Update I2C with type 0xf2 record with correct * size and checksum */ status = write_rom(serial, start_address, HEADER_SIZE, header); if (status) { kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -EINVAL; } /* * verify the write -- must do this in order for * write to complete before we do the hardware reset */ status = read_rom(serial, start_address, HEADER_SIZE, vheader); if (status) { dev_dbg(dev, "%s - can't read header back\n", __func__); kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return status; } if (memcmp(vheader, header, HEADER_SIZE)) { dev_dbg(dev, "%s - write download record failed\n", __func__); kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -EINVAL; } kfree(vheader); kfree(header); dev_dbg(dev, "%s - Start firmware update\n", __func__); /* Tell firmware to copy download image into I2C */ status = ti_vsend_sync(serial->serial->dev, UMPC_COPY_DNLD_TO_I2C, 0, 0, NULL, 0, TI_VSEND_TIMEOUT_FW_DOWNLOAD); dev_dbg(dev, "%s - Update complete 0x%x\n", __func__, status); if (status) { dev_err(dev, "%s - UMPC_COPY_DNLD_TO_I2C failed\n", __func__); kfree(rom_desc); kfree(ti_manuf_desc); return status; } } } /* The device is running the download code */ kfree(rom_desc); kfree(ti_manuf_desc); return 0; } static int do_boot_mode(struct edgeport_serial *serial, const struct firmware *fw) { struct device *dev = &serial->serial->interface->dev; int status = 0; struct edge_ti_manuf_descriptor *ti_manuf_desc; struct edgeport_fw_hdr *fw_hdr = (struct edgeport_fw_hdr *)fw->data; dev_dbg(dev, "%s - RUNNING IN BOOT MODE\n", __func__); /* Configure the TI device so we can use the BULK pipes for download */ status = config_boot_dev(serial->serial->dev); if (status) return status; if (le16_to_cpu(serial->serial->dev->descriptor.idVendor) != USB_VENDOR_ID_ION) { dev_dbg(dev, "%s - VID = 0x%x\n", __func__, le16_to_cpu(serial->serial->dev->descriptor.idVendor)); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; goto stayinbootmode; } /* * We have an ION device (I2c Must be programmed) * Determine I2C image type */ if (i2c_type_bootmode(serial)) goto stayinbootmode; /* Check for ION Vendor ID and that the I2C is valid */ if (!check_i2c_image(serial)) { struct ti_i2c_image_header *header; int i; __u8 cs = 0; __u8 *buffer; int buffer_size; /* * Validate Hardware version number * Read Manufacturing Descriptor from TI Based Edgeport */ ti_manuf_desc = kmalloc(sizeof(*ti_manuf_desc), GFP_KERNEL); if (!ti_manuf_desc) return -ENOMEM; status = get_manuf_info(serial, (__u8 *)ti_manuf_desc); if (status) { kfree(ti_manuf_desc); goto stayinbootmode; } /* Check for version 2 */ if (!ignore_cpu_rev && ti_cpu_rev(ti_manuf_desc) < 2) { dev_dbg(dev, "%s - Wrong CPU Rev %d (Must be 2)\n", __func__, ti_cpu_rev(ti_manuf_desc)); kfree(ti_manuf_desc); goto stayinbootmode; } kfree(ti_manuf_desc); /* * In order to update the I2C firmware we must change the type * 2 record to type 0xF2. This will force the UMP to come up * in Boot Mode. Then while in boot mode, the driver will * download the latest firmware (padded to 15.5k) into the * UMP ram. Finally when the device comes back up in download * mode the driver will cause the new firmware to be copied * from the UMP Ram to I2C and the firmware will update the * record type from 0xf2 to 0x02. * * Do we really have to copy the whole firmware image, * or could we do this in place! */ /* Allocate a 15.5k buffer + 3 byte header */ buffer_size = (((1024 * 16) - 512) + sizeof(struct ti_i2c_image_header)); buffer = kmalloc(buffer_size, GFP_KERNEL); if (!buffer) return -ENOMEM; /* Initialize the buffer to 0xff (pad the buffer) */ memset(buffer, 0xff, buffer_size); memcpy(buffer, &fw->data[4], fw->size - 4); for (i = sizeof(struct ti_i2c_image_header); i < buffer_size; i++) { cs = (__u8)(cs + buffer[i]); } header = (struct ti_i2c_image_header *)buffer; /* update length and checksum after padding */ header->Length = cpu_to_le16((__u16)(buffer_size - sizeof(struct ti_i2c_image_header))); header->CheckSum = cs; /* Download the operational code */ dev_dbg(dev, "%s - Downloading operational code image version %d.%d (TI UMP)\n", __func__, fw_hdr->major_version, fw_hdr->minor_version); status = download_code(serial, buffer, buffer_size); kfree(buffer); if (status) { dev_dbg(dev, "%s - Error downloading operational code image\n", __func__); return status; } /* Device will reboot */ serial->product_info.TiMode = TI_MODE_TRANSITIONING; dev_dbg(dev, "%s - Download successful -- Device rebooting...\n", __func__); return 1; } stayinbootmode: /* Eprom is invalid or blank stay in boot mode */ dev_dbg(dev, "%s - STAYING IN BOOT MODE\n", __func__); serial->product_info.TiMode = TI_MODE_BOOT; return 1; } static int ti_do_config(struct edgeport_port *port, int feature, int on) { int port_number = port->port->port_number; on = !!on; /* 1 or 0 not bitmask */ return send_cmd(port->port->serial->dev, feature, (__u8)(UMPM_UART1_PORT + port_number), on, NULL, 0); } static int restore_mcr(struct edgeport_port *port, __u8 mcr) { int status = 0; dev_dbg(&port->port->dev, "%s - %x\n", __func__, mcr); status = ti_do_config(port, UMPC_SET_CLR_DTR, mcr & MCR_DTR); if (status) return status; status = ti_do_config(port, UMPC_SET_CLR_RTS, mcr & MCR_RTS); if (status) return status; return ti_do_config(port, UMPC_SET_CLR_LOOPBACK, mcr & MCR_LOOPBACK); } /* Convert TI LSR to standard UART flags */ static __u8 map_line_status(__u8 ti_lsr) { __u8 lsr = 0; #define MAP_FLAG(flagUmp, flagUart) \ if (ti_lsr & flagUmp) \ lsr |= flagUart; MAP_FLAG(UMP_UART_LSR_OV_MASK, LSR_OVER_ERR) /* overrun */ MAP_FLAG(UMP_UART_LSR_PE_MASK, LSR_PAR_ERR) /* parity error */ MAP_FLAG(UMP_UART_LSR_FE_MASK, LSR_FRM_ERR) /* framing error */ MAP_FLAG(UMP_UART_LSR_BR_MASK, LSR_BREAK) /* break detected */ MAP_FLAG(UMP_UART_LSR_RX_MASK, LSR_RX_AVAIL) /* rx data available */ MAP_FLAG(UMP_UART_LSR_TX_MASK, LSR_TX_EMPTY) /* tx hold reg empty */ #undef MAP_FLAG return lsr; } static void handle_new_msr(struct edgeport_port *edge_port, __u8 msr) { struct async_icount *icount; struct tty_struct *tty; dev_dbg(&edge_port->port->dev, "%s - %02x\n", __func__, msr); if (msr & (EDGEPORT_MSR_DELTA_CTS | EDGEPORT_MSR_DELTA_DSR | EDGEPORT_MSR_DELTA_RI | EDGEPORT_MSR_DELTA_CD)) { icount = &edge_port->port->icount; /* update input line counters */ if (msr & EDGEPORT_MSR_DELTA_CTS) icount->cts++; if (msr & EDGEPORT_MSR_DELTA_DSR) icount->dsr++; if (msr & EDGEPORT_MSR_DELTA_CD) icount->dcd++; if (msr & EDGEPORT_MSR_DELTA_RI) icount->rng++; wake_up_interruptible(&edge_port->port->port.delta_msr_wait); } /* Save the new modem status */ edge_port->shadow_msr = msr & 0xf0; tty = tty_port_tty_get(&edge_port->port->port); /* handle CTS flow control */ if (tty && C_CRTSCTS(tty)) { if (msr & EDGEPORT_MSR_CTS) tty_wakeup(tty); } tty_kref_put(tty); } static void handle_new_lsr(struct edgeport_port *edge_port, int lsr_data, __u8 lsr, __u8 data) { struct async_icount *icount; __u8 new_lsr = (__u8)(lsr & (__u8)(LSR_OVER_ERR | LSR_PAR_ERR | LSR_FRM_ERR | LSR_BREAK)); dev_dbg(&edge_port->port->dev, "%s - %02x\n", __func__, new_lsr); edge_port->shadow_lsr = lsr; if (new_lsr & LSR_BREAK) /* * Parity and Framing errors only count if they * occur exclusive of a break being received. */ new_lsr &= (__u8)(LSR_OVER_ERR | LSR_BREAK); /* Place LSR data byte into Rx buffer */ if (lsr_data) edge_tty_recv(edge_port->port, &data, 1); /* update input line counters */ icount = &edge_port->port->icount; if (new_lsr & LSR_BREAK) icount->brk++; if (new_lsr & LSR_OVER_ERR) icount->overrun++; if (new_lsr & LSR_PAR_ERR) icount->parity++; if (new_lsr & LSR_FRM_ERR) icount->frame++; } static void edge_interrupt_callback(struct urb *urb) { struct edgeport_serial *edge_serial = urb->context; struct usb_serial_port *port; struct edgeport_port *edge_port; struct device *dev; unsigned char *data = urb->transfer_buffer; int length = urb->actual_length; int port_number; int function; int retval; __u8 lsr; __u8 msr; int status = urb->status; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_err(&urb->dev->dev, "%s - nonzero urb status received: " "%d\n", __func__, status); goto exit; } if (!length) { dev_dbg(&urb->dev->dev, "%s - no data in urb\n", __func__); goto exit; } dev = &edge_serial->serial->dev->dev; usb_serial_debug_data(dev, __func__, length, data); if (length != 2) { dev_dbg(dev, "%s - expecting packet of size 2, got %d\n", __func__, length); goto exit; } port_number = TIUMP_GET_PORT_FROM_CODE(data[0]); function = TIUMP_GET_FUNC_FROM_CODE(data[0]); dev_dbg(dev, "%s - port_number %d, function %d, info 0x%x\n", __func__, port_number, function, data[1]); if (port_number >= edge_serial->serial->num_ports) { dev_err(dev, "bad port number %d\n", port_number); goto exit; } port = edge_serial->serial->port[port_number]; edge_port = usb_get_serial_port_data(port); if (!edge_port) { dev_dbg(dev, "%s - edge_port not found\n", __func__); return; } switch (function) { case TIUMP_INTERRUPT_CODE_LSR: lsr = map_line_status(data[1]); if (lsr & UMP_UART_LSR_DATA_MASK) { /* * Save the LSR event for bulk read completion routine */ dev_dbg(dev, "%s - LSR Event Port %u LSR Status = %02x\n", __func__, port_number, lsr); edge_port->lsr_event = 1; edge_port->lsr_mask = lsr; } else { dev_dbg(dev, "%s - ===== Port %d LSR Status = %02x ======\n", __func__, port_number, lsr); handle_new_lsr(edge_port, 0, lsr, 0); } break; case TIUMP_INTERRUPT_CODE_MSR: /* MSR */ /* Copy MSR from UMP */ msr = data[1]; dev_dbg(dev, "%s - ===== Port %u MSR Status = %02x ======\n", __func__, port_number, msr); handle_new_msr(edge_port, msr); break; default: dev_err(&urb->dev->dev, "%s - Unknown Interrupt code from UMP %x\n", __func__, data[1]); break; } exit: retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval) dev_err(&urb->dev->dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval); } static void edge_bulk_in_callback(struct urb *urb) { struct edgeport_port *edge_port = urb->context; struct device *dev = &edge_port->port->dev; unsigned char *data = urb->transfer_buffer; int retval = 0; int port_number; int status = urb->status; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_err(&urb->dev->dev, "%s - nonzero read bulk status received: %d\n", __func__, status); } if (status == -EPIPE) goto exit; if (status) { dev_err(&urb->dev->dev, "%s - stopping read!\n", __func__); return; } port_number = edge_port->port->port_number; if (urb->actual_length > 0 && edge_port->lsr_event) { edge_port->lsr_event = 0; dev_dbg(dev, "%s ===== Port %u LSR Status = %02x, Data = %02x ======\n", __func__, port_number, edge_port->lsr_mask, *data); handle_new_lsr(edge_port, 1, edge_port->lsr_mask, *data); /* Adjust buffer length/pointer */ --urb->actual_length; ++data; } if (urb->actual_length) { usb_serial_debug_data(dev, __func__, urb->actual_length, data); if (edge_port->close_pending) dev_dbg(dev, "%s - close pending, dropping data on the floor\n", __func__); else edge_tty_recv(edge_port->port, data, urb->actual_length); edge_port->port->icount.rx += urb->actual_length; } exit: /* continue read unless stopped */ spin_lock(&edge_port->ep_lock); if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING) retval = usb_submit_urb(urb, GFP_ATOMIC); else if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPING) edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPED; spin_unlock(&edge_port->ep_lock); if (retval) dev_err(dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval); } static void edge_tty_recv(struct usb_serial_port *port, unsigned char *data, int length) { int queued; queued = tty_insert_flip_string(&port->port, data, length); if (queued < length) dev_err(&port->dev, "%s - dropping data, %d bytes lost\n", __func__, length - queued); tty_flip_buffer_push(&port->port); } static void edge_bulk_out_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status = urb->status; struct tty_struct *tty; edge_port->ep_write_urb_in_use = 0; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_err_console(port, "%s - nonzero write bulk status " "received: %d\n", __func__, status); } /* send any buffered data */ tty = tty_port_tty_get(&port->port); edge_send(port, tty); tty_kref_put(tty); } static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) { struct edgeport_port *edge_port = usb_get_serial_port_data(port); struct edgeport_serial *edge_serial; struct usb_device *dev; struct urb *urb; int port_number; int status; u16 open_settings; u8 transaction_timeout; if (edge_port == NULL) return -ENODEV; port_number = port->port_number; dev = port->serial->dev; /* turn off loopback */ status = ti_do_config(edge_port, UMPC_SET_CLR_LOOPBACK, 0); if (status) { dev_err(&port->dev, "%s - cannot send clear loopback command, %d\n", __func__, status); return status; } /* set up the port settings */ if (tty) edge_set_termios(tty, port, &tty->termios); /* open up the port */ /* milliseconds to timeout for DMA transfer */ transaction_timeout = 2; edge_port->ump_read_timeout = max(20, ((transaction_timeout * 3) / 2)); /* milliseconds to timeout for DMA transfer */ open_settings = (u8)(UMP_DMA_MODE_CONTINOUS | UMP_PIPE_TRANS_TIMEOUT_ENA | (transaction_timeout << 2)); dev_dbg(&port->dev, "%s - Sending UMPC_OPEN_PORT\n", __func__); /* Tell TI to open and start the port */ status = send_cmd(dev, UMPC_OPEN_PORT, (u8)(UMPM_UART1_PORT + port_number), open_settings, NULL, 0); if (status) { dev_err(&port->dev, "%s - cannot send open command, %d\n", __func__, status); return status; } /* Start the DMA? */ status = send_cmd(dev, UMPC_START_PORT, (u8)(UMPM_UART1_PORT + port_number), 0, NULL, 0); if (status) { dev_err(&port->dev, "%s - cannot send start DMA command, %d\n", __func__, status); return status; } /* Clear TX and RX buffers in UMP */ status = purge_port(port, UMP_PORT_DIR_OUT | UMP_PORT_DIR_IN); if (status) { dev_err(&port->dev, "%s - cannot send clear buffers command, %d\n", __func__, status); return status; } /* Read Initial MSR */ status = ti_vread_sync(dev, UMPC_READ_MSR, 0, (__u16)(UMPM_UART1_PORT + port_number), &edge_port->shadow_msr, 1); if (status) { dev_err(&port->dev, "%s - cannot send read MSR command, %d\n", __func__, status); return status; } dev_dbg(&port->dev, "ShadowMSR 0x%X\n", edge_port->shadow_msr); /* Set Initial MCR */ edge_port->shadow_mcr = MCR_RTS | MCR_DTR; dev_dbg(&port->dev, "ShadowMCR 0x%X\n", edge_port->shadow_mcr); edge_serial = edge_port->edge_serial; if (mutex_lock_interruptible(&edge_serial->es_lock)) return -ERESTARTSYS; if (edge_serial->num_ports_open == 0) { /* we are the first port to open, post the interrupt urb */ urb = edge_serial->serial->port[0]->interrupt_in_urb; urb->context = edge_serial; status = usb_submit_urb(urb, GFP_KERNEL); if (status) { dev_err(&port->dev, "%s - usb_submit_urb failed with value %d\n", __func__, status); goto release_es_lock; } } /* * reset the data toggle on the bulk endpoints to work around bug in * host controllers where things get out of sync some times */ usb_clear_halt(dev, port->write_urb->pipe); usb_clear_halt(dev, port->read_urb->pipe); /* start up our bulk read urb */ urb = port->read_urb; edge_port->ep_read_urb_state = EDGE_READ_URB_RUNNING; urb->context = edge_port; status = usb_submit_urb(urb, GFP_KERNEL); if (status) { dev_err(&port->dev, "%s - read bulk usb_submit_urb failed with value %d\n", __func__, status); goto unlink_int_urb; } ++edge_serial->num_ports_open; goto release_es_lock; unlink_int_urb: if (edge_port->edge_serial->num_ports_open == 0) usb_kill_urb(port->serial->port[0]->interrupt_in_urb); release_es_lock: mutex_unlock(&edge_serial->es_lock); return status; } static void edge_close(struct usb_serial_port *port) { struct edgeport_serial *edge_serial; struct edgeport_port *edge_port; struct usb_serial *serial = port->serial; unsigned long flags; int port_number; edge_serial = usb_get_serial_data(port->serial); edge_port = usb_get_serial_port_data(port); if (edge_serial == NULL || edge_port == NULL) return; /* * The bulkreadcompletion routine will check * this flag and dump add read data */ edge_port->close_pending = 1; usb_kill_urb(port->read_urb); usb_kill_urb(port->write_urb); edge_port->ep_write_urb_in_use = 0; spin_lock_irqsave(&edge_port->ep_lock, flags); kfifo_reset_out(&port->write_fifo); spin_unlock_irqrestore(&edge_port->ep_lock, flags); dev_dbg(&port->dev, "%s - send umpc_close_port\n", __func__); port_number = port->port_number; send_cmd(serial->dev, UMPC_CLOSE_PORT, (__u8)(UMPM_UART1_PORT + port_number), 0, NULL, 0); mutex_lock(&edge_serial->es_lock); --edge_port->edge_serial->num_ports_open; if (edge_port->edge_serial->num_ports_open <= 0) { /* last port is now closed, let's shut down our interrupt urb */ usb_kill_urb(port->serial->port[0]->interrupt_in_urb); edge_port->edge_serial->num_ports_open = 0; } mutex_unlock(&edge_serial->es_lock); edge_port->close_pending = 0; } static int edge_write(struct tty_struct *tty, struct usb_serial_port *port, const unsigned char *data, int count) { struct edgeport_port *edge_port = usb_get_serial_port_data(port); if (count == 0) { dev_dbg(&port->dev, "%s - write request of 0 bytes\n", __func__); return 0; } if (edge_port == NULL) return -ENODEV; if (edge_port->close_pending == 1) return -ENODEV; count = kfifo_in_locked(&port->write_fifo, data, count, &edge_port->ep_lock); edge_send(port, tty); return count; } static void edge_send(struct usb_serial_port *port, struct tty_struct *tty) { int count, result; struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); if (edge_port->ep_write_urb_in_use) { spin_unlock_irqrestore(&edge_port->ep_lock, flags); return; } count = kfifo_out(&port->write_fifo, port->write_urb->transfer_buffer, port->bulk_out_size); if (count == 0) { spin_unlock_irqrestore(&edge_port->ep_lock, flags); return; } edge_port->ep_write_urb_in_use = 1; spin_unlock_irqrestore(&edge_port->ep_lock, flags); usb_serial_debug_data(&port->dev, __func__, count, port->write_urb->transfer_buffer); /* set up our urb */ port->write_urb->transfer_buffer_length = count; /* send the data out the bulk port */ result = usb_submit_urb(port->write_urb, GFP_ATOMIC); if (result) { dev_err_console(port, "%s - failed submitting write urb, error %d\n", __func__, result); edge_port->ep_write_urb_in_use = 0; /* TODO: reschedule edge_send */ } else edge_port->port->icount.tx += count; /* * wakeup any process waiting for writes to complete * there is now more room in the buffer for new writes */ if (tty) tty_wakeup(tty); } static int edge_write_room(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int room = 0; unsigned long flags; if (edge_port == NULL) return 0; if (edge_port->close_pending == 1) return 0; spin_lock_irqsave(&edge_port->ep_lock, flags); room = kfifo_avail(&port->write_fifo); spin_unlock_irqrestore(&edge_port->ep_lock, flags); dev_dbg(&port->dev, "%s - returns %d\n", __func__, room); return room; } static int edge_chars_in_buffer(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int chars = 0; unsigned long flags; if (edge_port == NULL) return 0; spin_lock_irqsave(&edge_port->ep_lock, flags); chars = kfifo_len(&port->write_fifo); spin_unlock_irqrestore(&edge_port->ep_lock, flags); dev_dbg(&port->dev, "%s - returns %d\n", __func__, chars); return chars; } static bool edge_tx_empty(struct usb_serial_port *port) { struct edgeport_port *edge_port = usb_get_serial_port_data(port); int ret; ret = tx_active(edge_port); if (ret > 0) return false; return true; } static void edge_throttle(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status; if (edge_port == NULL) return; /* if we are implementing XON/XOFF, send the stop character */ if (I_IXOFF(tty)) { unsigned char stop_char = STOP_CHAR(tty); status = edge_write(tty, port, &stop_char, 1); if (status <= 0) { dev_err(&port->dev, "%s - failed to write stop character, %d\n", __func__, status); } } /* * if we are implementing RTS/CTS, stop reads * and the Edgeport will clear the RTS line */ if (C_CRTSCTS(tty)) stop_read(edge_port); } static void edge_unthrottle(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status; if (edge_port == NULL) return; /* if we are implementing XON/XOFF, send the start character */ if (I_IXOFF(tty)) { unsigned char start_char = START_CHAR(tty); status = edge_write(tty, port, &start_char, 1); if (status <= 0) { dev_err(&port->dev, "%s - failed to write start character, %d\n", __func__, status); } } /* * if we are implementing RTS/CTS, restart reads * are the Edgeport will assert the RTS line */ if (C_CRTSCTS(tty)) { status = restart_read(edge_port); if (status) dev_err(&port->dev, "%s - read bulk usb_submit_urb failed: %d\n", __func__, status); } } static void stop_read(struct edgeport_port *edge_port) { unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING) edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPING; edge_port->shadow_mcr &= ~MCR_RTS; spin_unlock_irqrestore(&edge_port->ep_lock, flags); } static int restart_read(struct edgeport_port *edge_port) { struct urb *urb; int status = 0; unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPED) { urb = edge_port->port->read_urb; status = usb_submit_urb(urb, GFP_ATOMIC); } edge_port->ep_read_urb_state = EDGE_READ_URB_RUNNING; edge_port->shadow_mcr |= MCR_RTS; spin_unlock_irqrestore(&edge_port->ep_lock, flags); return status; } static void change_port_settings(struct tty_struct *tty, struct edgeport_port *edge_port, struct ktermios *old_termios) { struct device *dev = &edge_port->port->dev; struct ump_uart_config *config; int baud; unsigned cflag; int status; int port_number = edge_port->port->port_number; config = kmalloc (sizeof (*config), GFP_KERNEL); if (!config) { tty->termios = *old_termios; return; } cflag = tty->termios.c_cflag; config->wFlags = 0; /* These flags must be set */ config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT; config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR; config->bUartMode = (__u8)(edge_port->bUartMode); switch (cflag & CSIZE) { case CS5: config->bDataBits = UMP_UART_CHAR5BITS; dev_dbg(dev, "%s - data bits = 5\n", __func__); break; case CS6: config->bDataBits = UMP_UART_CHAR6BITS; dev_dbg(dev, "%s - data bits = 6\n", __func__); break; case CS7: config->bDataBits = UMP_UART_CHAR7BITS; dev_dbg(dev, "%s - data bits = 7\n", __func__); break; default: case CS8: config->bDataBits = UMP_UART_CHAR8BITS; dev_dbg(dev, "%s - data bits = 8\n", __func__); break; } if (cflag & PARENB) { if (cflag & PARODD) { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_ODDPARITY; dev_dbg(dev, "%s - parity = odd\n", __func__); } else { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_EVENPARITY; dev_dbg(dev, "%s - parity = even\n", __func__); } } else { config->bParity = UMP_UART_NOPARITY; dev_dbg(dev, "%s - parity = none\n", __func__); } if (cflag & CSTOPB) { config->bStopBits = UMP_UART_STOPBIT2; dev_dbg(dev, "%s - stop bits = 2\n", __func__); } else { config->bStopBits = UMP_UART_STOPBIT1; dev_dbg(dev, "%s - stop bits = 1\n", __func__); } /* figure out the flow control settings */ if (cflag & CRTSCTS) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW; config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW; dev_dbg(dev, "%s - RTS/CTS is enabled\n", __func__); } else { dev_dbg(dev, "%s - RTS/CTS is disabled\n", __func__); restart_read(edge_port); } /* * if we are implementing XON/XOFF, set the start and stop * character in the device */ config->cXon = START_CHAR(tty); config->cXoff = STOP_CHAR(tty); /* if we are implementing INBOUND XON/XOFF */ if (I_IXOFF(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_IN_X; dev_dbg(dev, "%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - INBOUND XON/XOFF is disabled\n", __func__); /* if we are implementing OUTBOUND XON/XOFF */ if (I_IXON(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X; dev_dbg(dev, "%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - OUTBOUND XON/XOFF is disabled\n", __func__); tty->termios.c_cflag &= ~CMSPAR; /* Round the baud rate */ baud = tty_get_baud_rate(tty); if (!baud) { /* pick a default, any default... */ baud = 9600; } else tty_encode_baud_rate(tty, baud, baud); edge_port->baud_rate = baud; config->wBaudRate = (__u16)((461550L + baud/2) / baud); /* FIXME: Recompute actual baud from divisor here */ dev_dbg(dev, "%s - baud rate = %d, wBaudRate = %d\n", __func__, baud, config->wBaudRate); dev_dbg(dev, "wBaudRate: %d\n", (int)(461550L / config->wBaudRate)); dev_dbg(dev, "wFlags: 0x%x\n", config->wFlags); dev_dbg(dev, "bDataBits: %d\n", config->bDataBits); dev_dbg(dev, "bParity: %d\n", config->bParity); dev_dbg(dev, "bStopBits: %d\n", config->bStopBits); dev_dbg(dev, "cXon: %d\n", config->cXon); dev_dbg(dev, "cXoff: %d\n", config->cXoff); dev_dbg(dev, "bUartMode: %d\n", config->bUartMode); /* move the word values into big endian mode */ cpu_to_be16s(&config->wFlags); cpu_to_be16s(&config->wBaudRate); status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG, (__u8)(UMPM_UART1_PORT + port_number), 0, (__u8 *)config, sizeof(*config)); if (status) dev_dbg(dev, "%s - error %d when trying to write config to device\n", __func__, status); kfree(config); } static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios) { struct edgeport_port *edge_port = usb_get_serial_port_data(port); if (edge_port == NULL) return; /* change the port settings to the new ones specified */ change_port_settings(tty, edge_port, old_termios); } static int edge_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int mcr; unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); mcr = edge_port->shadow_mcr; if (set & TIOCM_RTS) mcr |= MCR_RTS; if (set & TIOCM_DTR) mcr |= MCR_DTR; if (set & TIOCM_LOOP) mcr |= MCR_LOOPBACK; if (clear & TIOCM_RTS) mcr &= ~MCR_RTS; if (clear & TIOCM_DTR) mcr &= ~MCR_DTR; if (clear & TIOCM_LOOP) mcr &= ~MCR_LOOPBACK; edge_port->shadow_mcr = mcr; spin_unlock_irqrestore(&edge_port->ep_lock, flags); restore_mcr(edge_port, mcr); return 0; } static int edge_tiocmget(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int result = 0; unsigned int msr; unsigned int mcr; unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); msr = edge_port->shadow_msr; mcr = edge_port->shadow_mcr; result = ((mcr & MCR_DTR) ? TIOCM_DTR: 0) /* 0x002 */ | ((mcr & MCR_RTS) ? TIOCM_RTS: 0) /* 0x004 */ | ((msr & EDGEPORT_MSR_CTS) ? TIOCM_CTS: 0) /* 0x020 */ | ((msr & EDGEPORT_MSR_CD) ? TIOCM_CAR: 0) /* 0x040 */ | ((msr & EDGEPORT_MSR_RI) ? TIOCM_RI: 0) /* 0x080 */ | ((msr & EDGEPORT_MSR_DSR) ? TIOCM_DSR: 0); /* 0x100 */ dev_dbg(&port->dev, "%s -- %x\n", __func__, result); spin_unlock_irqrestore(&edge_port->ep_lock, flags); return result; } static int get_serial_info(struct edgeport_port *edge_port, struct serial_struct __user *retinfo) { struct serial_struct tmp; unsigned cwait; cwait = edge_port->port->port.closing_wait; if (cwait != ASYNC_CLOSING_WAIT_NONE) cwait = jiffies_to_msecs(cwait) / 10; memset(&tmp, 0, sizeof(tmp)); tmp.type = PORT_16550A; tmp.line = edge_port->port->minor; tmp.port = edge_port->port->port_number; tmp.irq = 0; tmp.xmit_fifo_size = edge_port->port->bulk_out_size; tmp.baud_base = 9600; tmp.close_delay = 5*HZ; tmp.closing_wait = cwait; if (copy_to_user(retinfo, &tmp, sizeof(*retinfo))) return -EFAULT; return 0; } static int edge_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); switch (cmd) { case TIOCGSERIAL: dev_dbg(&port->dev, "%s - TIOCGSERIAL\n", __func__); return get_serial_info(edge_port, (struct serial_struct __user *) arg); } return -ENOIOCTLCMD; } static void edge_break(struct tty_struct *tty, int break_state) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status; int bv = 0; /* Off */ if (break_state == -1) bv = 1; /* On */ status = ti_do_config(edge_port, UMPC_SET_CLR_BREAK, bv); if (status) dev_dbg(&port->dev, "%s - error %d sending break set/clear command.\n", __func__, status); } static void edge_heartbeat_schedule(struct edgeport_serial *edge_serial) { if (!edge_serial->use_heartbeat) return; schedule_delayed_work(&edge_serial->heartbeat_work, FW_HEARTBEAT_SECS * HZ); } static void edge_heartbeat_work(struct work_struct *work) { struct edgeport_serial *serial; struct ti_i2c_desc *rom_desc; serial = container_of(work, struct edgeport_serial, heartbeat_work.work); rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL); /* Descriptor address request is enough to reset the firmware timer */ if (!rom_desc || !get_descriptor_addr(serial, I2C_DESC_TYPE_ION, rom_desc)) { dev_err(&serial->serial->interface->dev, "%s - Incomplete heartbeat\n", __func__); } kfree(rom_desc); edge_heartbeat_schedule(serial); } static int edge_calc_num_ports(struct usb_serial *serial, struct usb_serial_endpoints *epds) { struct device *dev = &serial->interface->dev; unsigned char num_ports = serial->type->num_ports; /* Make sure we have the required endpoints when in download mode. */ if (serial->interface->cur_altsetting->desc.bNumEndpoints > 1) { if (epds->num_bulk_in < num_ports || epds->num_bulk_out < num_ports || epds->num_interrupt_in < 1) { dev_err(dev, "required endpoints missing\n"); return -ENODEV; } } return num_ports; } static int edge_startup(struct usb_serial *serial) { struct edgeport_serial *edge_serial; int status; u16 product_id; /* create our private serial structure */ edge_serial = kzalloc(sizeof(struct edgeport_serial), GFP_KERNEL); if (!edge_serial) return -ENOMEM; mutex_init(&edge_serial->es_lock); edge_serial->serial = serial; INIT_DELAYED_WORK(&edge_serial->heartbeat_work, edge_heartbeat_work); usb_set_serial_data(serial, edge_serial); status = download_fw(edge_serial); if (status < 0) { kfree(edge_serial); return status; } if (status > 0) return 1; /* bind but do not register any ports */ product_id = le16_to_cpu( edge_serial->serial->dev->descriptor.idProduct); /* Currently only the EP/416 models require heartbeat support */ if (edge_serial->fw_version > FW_HEARTBEAT_VERSION_CUTOFF) { if (product_id == ION_DEVICE_ID_TI_EDGEPORT_416 || product_id == ION_DEVICE_ID_TI_EDGEPORT_416B) { edge_serial->use_heartbeat = true; } } edge_heartbeat_schedule(edge_serial); return 0; } static void edge_disconnect(struct usb_serial *serial) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); cancel_delayed_work_sync(&edge_serial->heartbeat_work); } static void edge_release(struct usb_serial *serial) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); cancel_delayed_work_sync(&edge_serial->heartbeat_work); kfree(edge_serial); } static int edge_port_probe(struct usb_serial_port *port) { struct edgeport_port *edge_port; int ret; edge_port = kzalloc(sizeof(*edge_port), GFP_KERNEL); if (!edge_port) return -ENOMEM; spin_lock_init(&edge_port->ep_lock); edge_port->port = port; edge_port->edge_serial = usb_get_serial_data(port->serial); edge_port->bUartMode = default_uart_mode; switch (port->port_number) { case 0: edge_port->uart_base = UMPMEM_BASE_UART1; edge_port->dma_address = UMPD_OEDB1_ADDRESS; break; case 1: edge_port->uart_base = UMPMEM_BASE_UART2; edge_port->dma_address = UMPD_OEDB2_ADDRESS; break; default: dev_err(&port->dev, "unknown port number\n"); ret = -ENODEV; goto err; } dev_dbg(&port->dev, "%s - port_number = %d, uart_base = %04x, dma_address = %04x\n", __func__, port->port_number, edge_port->uart_base, edge_port->dma_address); usb_set_serial_port_data(port, edge_port); ret = edge_create_sysfs_attrs(port); if (ret) goto err; port->port.closing_wait = msecs_to_jiffies(closing_wait * 10); port->port.drain_delay = 1; return 0; err: kfree(edge_port); return ret; } static int edge_port_remove(struct usb_serial_port *port) { struct edgeport_port *edge_port; edge_port = usb_get_serial_port_data(port); edge_remove_sysfs_attrs(port); kfree(edge_port); return 0; } /* Sysfs Attributes */ static ssize_t uart_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { struct usb_serial_port *port = to_usb_serial_port(dev); struct edgeport_port *edge_port = usb_get_serial_port_data(port); return sprintf(buf, "%d\n", edge_port->bUartMode); } static ssize_t uart_mode_store(struct device *dev, struct device_attribute *attr, const char *valbuf, size_t count) { struct usb_serial_port *port = to_usb_serial_port(dev); struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int v = simple_strtoul(valbuf, NULL, 0); dev_dbg(dev, "%s: setting uart_mode = %d\n", __func__, v); if (v < 256) edge_port->bUartMode = v; else dev_err(dev, "%s - uart_mode %d is invalid\n", __func__, v); return count; } static DEVICE_ATTR_RW(uart_mode); static int edge_create_sysfs_attrs(struct usb_serial_port *port) { return device_create_file(&port->dev, &dev_attr_uart_mode); } static int edge_remove_sysfs_attrs(struct usb_serial_port *port) { device_remove_file(&port->dev, &dev_attr_uart_mode); return 0; } #ifdef CONFIG_PM static int edge_suspend(struct usb_serial *serial, pm_message_t message) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); cancel_delayed_work_sync(&edge_serial->heartbeat_work); return 0; } static int edge_resume(struct usb_serial *serial) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); edge_heartbeat_schedule(edge_serial); return 0; } #endif static struct usb_serial_driver edgeport_1port_device = { .driver = { .owner = THIS_MODULE, .name = "edgeport_ti_1", }, .description = "Edgeport TI 1 port adapter", .id_table = edgeport_1port_id_table, .num_ports = 1, .num_bulk_out = 1, .open = edge_open, .close = edge_close, .throttle = edge_throttle, .unthrottle = edge_unthrottle, .attach = edge_startup, .calc_num_ports = edge_calc_num_ports, .disconnect = edge_disconnect, .release = edge_release, .port_probe = edge_port_probe, .port_remove = edge_port_remove, .ioctl = edge_ioctl, .set_termios = edge_set_termios, .tiocmget = edge_tiocmget, .tiocmset = edge_tiocmset, .tiocmiwait = usb_serial_generic_tiocmiwait, .get_icount = usb_serial_generic_get_icount, .write = edge_write, .write_room = edge_write_room, .chars_in_buffer = edge_chars_in_buffer, .tx_empty = edge_tx_empty, .break_ctl = edge_break, .read_int_callback = edge_interrupt_callback, .read_bulk_callback = edge_bulk_in_callback, .write_bulk_callback = edge_bulk_out_callback, #ifdef CONFIG_PM .suspend = edge_suspend, .resume = edge_resume, #endif }; static struct usb_serial_driver edgeport_2port_device = { .driver = { .owner = THIS_MODULE, .name = "edgeport_ti_2", }, .description = "Edgeport TI 2 port adapter", .id_table = edgeport_2port_id_table, .num_ports = 2, .num_bulk_out = 1, .open = edge_open, .close = edge_close, .throttle = edge_throttle, .unthrottle = edge_unthrottle, .attach = edge_startup, .calc_num_ports = edge_calc_num_ports, .disconnect = edge_disconnect, .release = edge_release, .port_probe = edge_port_probe, .port_remove = edge_port_remove, .ioctl = edge_ioctl, .set_termios = edge_set_termios, .tiocmget = edge_tiocmget, .tiocmset = edge_tiocmset, .tiocmiwait = usb_serial_generic_tiocmiwait, .get_icount = usb_serial_generic_get_icount, .write = edge_write, .write_room = edge_write_room, .chars_in_buffer = edge_chars_in_buffer, .tx_empty = edge_tx_empty, .break_ctl = edge_break, .read_int_callback = edge_interrupt_callback, .read_bulk_callback = edge_bulk_in_callback, .write_bulk_callback = edge_bulk_out_callback, #ifdef CONFIG_PM .suspend = edge_suspend, .resume = edge_resume, #endif }; static struct usb_serial_driver * const serial_drivers[] = { &edgeport_1port_device, &edgeport_2port_device, NULL }; module_usb_serial_driver(serial_drivers, id_table_combined); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); MODULE_FIRMWARE("edgeport/down3.bin"); module_param(closing_wait, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(closing_wait, "Maximum wait for data to drain, in .01 secs"); module_param(ignore_cpu_rev, bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(ignore_cpu_rev, "Ignore the cpu revision when connecting to a device"); module_param(default_uart_mode, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(default_uart_mode, "Default uart_mode, 0=RS232, ...");
./CrossVul/dataset_final_sorted/CWE-369/c/bad_3035_0
crossvul-cpp_data_good_952_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % L AAA Y Y EEEEE RRRR % % L A A Y Y E R R % % L AAAAA Y EEE RRRR % % L A A Y E R R % % LLLLL A A Y EEEEE R R % % % % MagickCore Image Layering Methods % % % % Software Design % % Cristy % % Anthony Thyssen % % January 2006 % % % % % % Copyright 1999-2019 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://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/cache.h" #include "magick/channel.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/composite.h" #include "magick/effect.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/layer.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/property.h" #include "magick/profile.h" #include "magick/resource_.h" #include "magick/resize.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l e a r B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClearBounds() Clear the area specified by the bounds in an image to % transparency. This typically used to handle Background Disposal for the % previous frame in an animation sequence. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % void ClearBounds(Image *image,RectangleInfo *bounds) % % A description of each parameter follows: % % o image: the image to had the area cleared in % % o bounds: the area to be clear within the imag image % */ static void ClearBounds(Image *image,RectangleInfo *bounds) { ExceptionInfo *exception; ssize_t y; if (bounds->x < 0) return; if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); exception=(&image->exception); for (y=0; y < (ssize_t) bounds->height; y++) { register ssize_t x; register PixelPacket *magick_restrict q; q=GetAuthenticPixels(image,bounds->x,bounds->y+y,bounds->width,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) bounds->width; x++) { q->opacity=(Quantum) TransparentOpacity; q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s B o u n d s C l e a r e d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsBoundsCleared() tests whether any pixel in the bounds given, gets cleared % when going from the first image to the second image. This typically used % to check if a proposed disposal method will work successfully to generate % the second frame image from the first disposed form of the previous frame. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % MagickBooleanType IsBoundsCleared(const Image *image1, % const Image *image2,RectangleInfo bounds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image1, image 2: the images to check for cleared pixels % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsBoundsCleared(const Image *image1, const Image *image2,RectangleInfo *bounds,ExceptionInfo *exception) { register const PixelPacket *p, *q; register ssize_t x; ssize_t y; if (bounds->x < 0) return(MagickFalse); for (y=0; y < (ssize_t) bounds->height; y++) { p=GetVirtualPixels(image1,bounds->x,bounds->y+y,bounds->width,1, exception); q=GetVirtualPixels(image2,bounds->x,bounds->y+y,bounds->width,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) break; for (x=0; x < (ssize_t) bounds->width; x++) { if ((GetPixelOpacity(p) <= (Quantum) (QuantumRange/2)) && (GetPixelOpacity(q) > (Quantum) (QuantumRange/2))) break; p++; q++; } if (x < (ssize_t) bounds->width) break; } return(y < (ssize_t) bounds->height ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o a l e s c e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CoalesceImages() composites a set of images while respecting any page % offsets and disposal methods. GIF, MIFF, and MNG animation sequences % typically start with an image background and each subsequent image % varies in size and offset. A new image sequence is returned with all % images the same size as the first images virtual canvas and composited % with the next image in the sequence. % % The format of the CoalesceImages method is: % % Image *CoalesceImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CoalesceImages(const Image *image,ExceptionInfo *exception) { Image *coalesce_image, *dispose_image, *previous; register Image *next; RectangleInfo bounds; /* Coalesce the image sequence. */ 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); /* initialise first image */ next=GetFirstImageInList(image); bounds=next->page; if (bounds.width == 0) { bounds.width=next->columns; if (bounds.x > 0) bounds.width+=bounds.x; } if (bounds.height == 0) { bounds.height=next->rows; if (bounds.y > 0) bounds.height+=bounds.y; } bounds.x=0; bounds.y=0; coalesce_image=CloneImage(next,bounds.width,bounds.height,MagickTrue, exception); if (coalesce_image == (Image *) NULL) return((Image *) NULL); coalesce_image->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(coalesce_image); coalesce_image->matte=next->matte; coalesce_image->page=bounds; coalesce_image->dispose=NoneDispose; /* Coalesce rest of the images. */ dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); (void) CompositeImage(coalesce_image,CopyCompositeOp,next,next->page.x, next->page.y); next=GetNextImageInList(next); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { /* Determine the bounds that was overlaid in the previous image. */ previous=GetPreviousImageInList(next); bounds=previous->page; bounds.width=previous->columns; bounds.height=previous->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) coalesce_image->columns) bounds.width=coalesce_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) coalesce_image->rows) bounds.height=coalesce_image->rows-bounds.y; /* Replace the dispose image with the new coalesced image. */ if (GetPreviousImageInList(next)->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); if (dispose_image == (Image *) NULL) { coalesce_image=DestroyImageList(coalesce_image); return((Image *) NULL); } } /* Clear the overlaid area of the coalesced bounds for background disposal */ if (next->previous->dispose == BackgroundDispose) ClearBounds(dispose_image,&bounds); /* Next image is the dispose image, overlaid with next frame in sequence. */ coalesce_image->next=CloneImage(dispose_image,0,0,MagickTrue,exception); if (coalesce_image->next != NULL) coalesce_image->next->previous=coalesce_image; previous=coalesce_image; coalesce_image=GetNextImageInList(coalesce_image); (void) CompositeImage(coalesce_image,next->matte != MagickFalse ? OverCompositeOp : CopyCompositeOp,next,next->page.x,next->page.y); (void) CloneImageProfiles(coalesce_image,next); (void) CloneImageProperties(coalesce_image,next); (void) CloneImageArtifacts(coalesce_image,next); coalesce_image->page=previous->page; /* If a pixel goes opaque to transparent, use background dispose. */ if (IsBoundsCleared(previous,coalesce_image,&bounds,exception) != MagickFalse) coalesce_image->dispose=BackgroundDispose; else coalesce_image->dispose=NoneDispose; previous->dispose=coalesce_image->dispose; } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(coalesce_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D i s p o s e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisposeImages() returns the coalesced frames of a GIF animation as it would % appear after the GIF dispose method of that frame has been applied. That is % it returned the appearance of each frame before the next is overlaid. % % The format of the DisposeImages method is: % % Image *DisposeImages(Image *images,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *DisposeImages(const Image *images,ExceptionInfo *exception) { Image *dispose_image, *dispose_images; RectangleInfo bounds; register Image *image, *next; /* Run the image through the animation sequence */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(images); dispose_image=CloneImage(image,image->page.width,image->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return((Image *) NULL); dispose_image->page=image->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(dispose_image); dispose_images=NewImageList(); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { Image *current_image; /* Overlay this frame's image over the previous disposal image. */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } (void) CompositeImage(current_image,next->matte != MagickFalse ? OverCompositeOp : CopyCompositeOp,next,next->page.x,next->page.y); /* Handle Background dispose: image is displayed for the delay period. */ if (next->dispose == BackgroundDispose) { bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds); } /* Select the appropriate previous/disposed image. */ if (next->dispose == PreviousDispose) current_image=DestroyImage(current_image); else { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; current_image=(Image *) NULL; } /* Save the dispose image just calculated for return. */ { Image *dispose; dispose=CloneImage(dispose_image,0,0,MagickTrue,exception); if (dispose == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } (void) CloneImageProfiles(dispose,next); (void) CloneImageProperties(dispose,next); (void) CloneImageArtifacts(dispose,next); dispose->page.x=0; dispose->page.y=0; dispose->dispose=next->dispose; AppendImageToList(&dispose_images,dispose); } } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(dispose_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComparePixels() Compare the two pixels and return true if the pixels % differ according to the given LayerType comparision method. % % This currently only used internally by CompareImageBounds(). It is % doubtful that this sub-routine will be useful outside this module. % % The format of the ComparePixels method is: % % MagickBooleanType *ComparePixels(const ImageLayerMethod method, % const MagickPixelPacket *p,const MagickPixelPacket *q) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o p, q: the pixels to test for appropriate differences. % */ static MagickBooleanType ComparePixels(const ImageLayerMethod method, const MagickPixelPacket *p,const MagickPixelPacket *q) { MagickRealType o1, o2; /* Any change in pixel values */ if (method == CompareAnyLayer) return((MagickBooleanType)(IsMagickColorSimilar(p,q) == MagickFalse)); o1 = (p->matte != MagickFalse) ? GetPixelOpacity(p) : OpaqueOpacity; o2 = (q->matte != MagickFalse) ? q->opacity : OpaqueOpacity; /* Pixel goes from opaque to transprency */ if (method == CompareClearLayer) return((MagickBooleanType) ( (o1 <= ((MagickRealType) QuantumRange/2.0)) && (o2 > ((MagickRealType) QuantumRange/2.0)) ) ); /* overlay would change first pixel by second */ if (method == CompareOverlayLayer) { if (o2 > ((MagickRealType) QuantumRange/2.0)) return MagickFalse; return((MagickBooleanType) (IsMagickColorSimilar(p,q) == MagickFalse)); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e I m a g e B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImageBounds() Given two images return the smallest rectangular area % by which the two images differ, accourding to the given 'Compare...' % layer method. % % This currently only used internally in this module, but may eventually % be used by other modules. % % The format of the CompareImageBounds method is: % % RectangleInfo *CompareImageBounds(const ImageLayerMethod method, % const Image *image1,const Image *image2,ExceptionInfo *exception) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o image1, image2: the two images to compare. % % o exception: return any errors or warnings in this structure. % */ static RectangleInfo CompareImageBounds(const Image *image1,const Image *image2, const ImageLayerMethod method,ExceptionInfo *exception) { RectangleInfo bounds; MagickPixelPacket pixel1, pixel2; register const IndexPacket *indexes1, *indexes2; register const PixelPacket *p, *q; register ssize_t x; ssize_t y; #if 0 /* only same sized images can be compared */ assert(image1->columns == image2->columns); assert(image1->rows == image2->rows); #endif /* Set bounding box of the differences between images */ GetMagickPixelPacket(image1,&pixel1); GetMagickPixelPacket(image2,&pixel2); for (x=0; x < (ssize_t) image1->columns; x++) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const PixelPacket *) NULL) || (q == (const PixelPacket *) NULL)) break; indexes1=GetVirtualIndexQueue(image1); indexes2=GetVirtualIndexQueue(image2); for (y=0; y < (ssize_t) image1->rows; y++) { SetMagickPixelPacket(image1,p,indexes1+x,&pixel1); SetMagickPixelPacket(image2,q,indexes2+x,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p++; q++; } if (y < (ssize_t) image1->rows) break; } if (x >= (ssize_t) image1->columns) { /* Images are identical, return a null image. */ bounds.x=-1; bounds.y=-1; bounds.width=1; bounds.height=1; return(bounds); } bounds.x=x; for (x=(ssize_t) image1->columns-1; x >= 0; x--) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const PixelPacket *) NULL) || (q == (const PixelPacket *) NULL)) break; indexes1=GetVirtualIndexQueue(image1); indexes2=GetVirtualIndexQueue(image2); for (y=0; y < (ssize_t) image1->rows; y++) { SetMagickPixelPacket(image1,p,indexes1+x,&pixel1); SetMagickPixelPacket(image2,q,indexes2+x,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p++; q++; } if (y < (ssize_t) image1->rows) break; } bounds.width=(size_t) (x-bounds.x+1); for (y=0; y < (ssize_t) image1->rows; y++) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (const PixelPacket *) NULL)) break; indexes1=GetVirtualIndexQueue(image1); indexes2=GetVirtualIndexQueue(image2); for (x=0; x < (ssize_t) image1->columns; x++) { SetMagickPixelPacket(image1,p,indexes1+x,&pixel1); SetMagickPixelPacket(image2,q,indexes2+x,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p++; q++; } if (x < (ssize_t) image1->columns) break; } bounds.y=y; for (y=(ssize_t) image1->rows-1; y >= 0; y--) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (const PixelPacket *) NULL)) break; indexes1=GetVirtualIndexQueue(image1); indexes2=GetVirtualIndexQueue(image2); for (x=0; x < (ssize_t) image1->columns; x++) { SetMagickPixelPacket(image1,p,indexes1+x,&pixel1); SetMagickPixelPacket(image2,q,indexes2+x,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p++; q++; } if (x < (ssize_t) image1->columns) break; } bounds.height=(size_t) (y-bounds.y+1); return(bounds); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p a r e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImageLayers() compares each image with the next in a sequence and % returns the minimum bounding region of all the pixel differences (of the % ImageLayerMethod specified) it discovers. % % Images do NOT have to be the same size, though it is best that all the % images are 'coalesced' (images are all the same size, on a flattened % canvas, so as to represent exactly how an specific frame should look). % % No GIF dispose methods are applied, so GIF animations must be coalesced % before applying this image operator to find differences to them. % % The format of the CompareImageLayers method is: % % Image *CompareImageLayers(const Image *images, % const ImageLayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers type to compare images with. Must be one of... % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CompareImageLayers(const Image *image, const ImageLayerMethod method,ExceptionInfo *exception) { Image *image_a, *image_b, *layers; RectangleInfo *bounds; register const Image *next; register ssize_t i; assert(image != (const 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); assert((method == CompareAnyLayer) || (method == CompareClearLayer) || (method == CompareOverlayLayer)); /* Allocate bounds memory. */ next=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(next),sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Set up first comparision images. */ image_a=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (image_a == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_a->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(image_a); image_a->page=next->page; image_a->page.x=0; image_a->page.y=0; (void) CompositeImage(image_a,CopyCompositeOp,next,next->page.x,next->page.y); /* Compute the bounding box of changes for the later images */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { image_b=CloneImage(image_a,0,0,MagickTrue,exception); if (image_b == (Image *) NULL) { image_a=DestroyImage(image_a); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } (void) CompositeImage(image_a,CopyCompositeOp,next,next->page.x, next->page.y); bounds[i]=CompareImageBounds(image_b,image_a,method,exception); image_b=DestroyImage(image_b); i++; } image_a=DestroyImage(image_a); /* Clone first image in sequence. */ next=GetFirstImageInList(image); layers=CloneImage(next,0,0,MagickTrue,exception); if (layers == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } /* Deconstruct the image sequence. */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { if ((bounds[i].x == -1) && (bounds[i].y == -1) && (bounds[i].width == 1) && (bounds[i].height == 1)) { /* An empty frame is returned from CompareImageBounds(), which means the current frame is identical to the previous frame. */ i++; continue; } image_a=CloneImage(next,0,0,MagickTrue,exception); if (image_a == (Image *) NULL) break; image_b=CropImage(image_a,&bounds[i],exception); image_a=DestroyImage(image_a); if (image_b == (Image *) NULL) break; AppendImageToList(&layers,image_b); i++; } bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); if (next != (Image *) NULL) { layers=DestroyImageList(layers); return((Image *) NULL); } return(GetFirstImageInList(layers)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o n s t r u c t I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeconstructImages() compares each image with the next in a sequence and % returns the minimum bounding region of all differences from the first image. % % This function is deprecated in favor of the more universal % CompareImageLayers() function. % % The format of the DeconstructImages method is: % % Image *DeconstructImages(const Image *images,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *DeconstructImages(const Image *images, ExceptionInfo *exception) { return(CompareImageLayers(images,CompareAnyLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p t i m i z e L a y e r F r a m e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeLayerFrames() takes a coalesced GIF animation, and compares each % frame against the three different 'disposal' forms of the previous frame. % From this it then attempts to select the smallest cropped image and % disposal method needed to reproduce the resulting image. % % Note that this not easy, and may require the expansion of the bounds % of previous frame, simply clear pixels for the next animation frame to % transparency according to the selected dispose method. % % The format of the OptimizeLayerFrames method is: % % static Image *OptimizeLayerFrames(const Image *image, % const ImageLayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers technique to optimize with. Must be one of... % OptimizeImageLayer, or OptimizePlusLayer. The Plus form allows % the addition of extra 'zero delay' frames to clear pixels from % the previous frame, and the removal of frames that done change, % merging the delay times together. % % o exception: return any errors or warnings in this structure. % */ /* Define a 'fake' dispose method where the frame is duplicated, (for OptimizePlusLayer) with a extra zero time delay frame which does a BackgroundDisposal to clear the pixels that need to be cleared. */ #define DupDispose ((DisposeType)9) /* Another 'fake' dispose method used to removed frames that don't change. */ #define DelDispose ((DisposeType)8) #define DEBUG_OPT_FRAME 0 static Image *OptimizeLayerFrames(const Image *image, const ImageLayerMethod method,ExceptionInfo *exception) { ExceptionInfo *sans_exception; Image *prev_image, *dup_image, *bgnd_image, *optimized_image; RectangleInfo try_bounds, bgnd_bounds, dup_bounds, *bounds; MagickBooleanType add_frames, try_cleared, cleared; DisposeType *disposals; register const Image *curr; register ssize_t i; assert(image != (const 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); assert(method == OptimizeLayer || method == OptimizeImageLayer || method == OptimizePlusLayer); /* Are we allowed to add/remove frames from animation */ add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse; /* Ensure all the images are the same size */ curr=GetFirstImageInList(image); for (; curr != (Image *) NULL; curr=GetNextImageInList(curr)) { if ((curr->columns != image->columns) || (curr->rows != image->rows)) ThrowImageException(OptionError,"ImagesAreNotTheSameSize"); if ((curr->page.x != 0) || (curr->page.y != 0) || (curr->page.width != image->page.width) || (curr->page.height != image->page.height)) ThrowImageException(OptionError,"ImagePagesAreNotCoalesced"); } /* Allocate memory (times 2 if we allow the use of frame duplications) */ curr=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); disposals=(DisposeType *) AcquireQuantumMemory((size_t) GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*disposals)); if (disposals == (DisposeType *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialise Previous Image as fully transparent */ prev_image=CloneImage(curr,curr->page.width,curr->page.height, MagickTrue,exception); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */ prev_image->page.x=0; prev_image->page.y=0; prev_image->dispose=NoneDispose; prev_image->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(prev_image); /* Figure out the area of overlay of the first frame No pixel could be cleared as all pixels are already cleared. */ #if DEBUG_OPT_FRAME i=0; (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif disposals[0]=NoneDispose; bounds[0]=CompareImageBounds(prev_image,curr,CompareAnyLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g\n\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); #endif /* Compute the bounding box of changes for each pair of images. */ i=1; bgnd_image=(Image *) NULL; dup_image=(Image *) NULL; dup_bounds.width=0; dup_bounds.height=0; dup_bounds.x=0; dup_bounds.y=0; curr=GetNextImageInList(curr); for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr)) { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif /* Assume none disposal is the best */ bounds[i]=CompareImageBounds(curr->previous,curr,CompareAnyLayer,exception); cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception); disposals[i-1]=NoneDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g%s%s\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y, bounds[i].x < 0?" (unchanged)":"", cleared?" (pixels cleared)":""); #endif if ( bounds[i].x < 0 ) { /* Image frame is exactly the same as the previous frame! If not adding frames leave it to be cropped down to a null image. Otherwise mark previous image for deleted, transfering its crop bounds to the current image. */ if ( add_frames && i>=2 ) { disposals[i-1]=DelDispose; disposals[i]=NoneDispose; bounds[i]=bounds[i-1]; i++; continue; } } else { /* Compare a none disposal against a previous disposal */ try_bounds=CompareImageBounds(prev_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "test_prev: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels were cleared)":""); #endif if ( (!try_cleared && cleared ) || try_bounds.width * try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=try_cleared; bounds[i]=try_bounds; disposals[i-1]=PreviousDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"previous: accepted\n"); } else { (void) FormatLocaleFile(stderr,"previous: rejected\n"); #endif } /* If we are allowed lets try a complex frame duplication. It is useless if the previous image already clears pixels correctly. This method will always clear all the pixels that need to be cleared. */ dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */ if ( add_frames ) { dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (dup_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); return((Image *) NULL); } dup_bounds=CompareImageBounds(dup_image,curr,CompareClearLayer,exception); ClearBounds(dup_image,&dup_bounds); try_bounds=CompareImageBounds(dup_image,curr,CompareAnyLayer,exception); if ( cleared || dup_bounds.width*dup_bounds.height +try_bounds.width*try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=MagickFalse; bounds[i]=try_bounds; disposals[i-1]=DupDispose; /* to be finalised later, if found to be optimial */ } else dup_bounds.width=dup_bounds.height=0; } /* Now compare against a simple background disposal */ bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (bgnd_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); return((Image *) NULL); } bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */ ClearBounds(bgnd_image,&bgnd_bounds); try_bounds=CompareImageBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "background: %s\n", try_cleared?"(pixels cleared)":""); #endif if ( try_cleared ) { /* Straight background disposal failed to clear pixels needed! Lets try expanding the disposal area of the previous frame, to include the pixels that are cleared. This guaranteed to work, though may not be the most optimized solution. */ try_bounds=CompareImageBounds(curr->previous,curr,CompareClearLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_clear: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_bounds.x<0?" (no expand nessary)":""); #endif if ( bgnd_bounds.x < 0 ) bgnd_bounds = try_bounds; else { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_bgnd: %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif if ( try_bounds.x < bgnd_bounds.x ) { bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; bgnd_bounds.x = try_bounds.x; } else { try_bounds.width += try_bounds.x - bgnd_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; } if ( try_bounds.y < bgnd_bounds.y ) { bgnd_bounds.height += bgnd_bounds.y - try_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; bgnd_bounds.y = try_bounds.y; } else { try_bounds.height += try_bounds.y - bgnd_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; } #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, " to : %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif } ClearBounds(bgnd_image,&bgnd_bounds); #if DEBUG_OPT_FRAME /* Something strange is happening with a specific animation * CompareAnyLayers (normal method) and CompareClearLayers returns the whole * image, which is not posibly correct! As verified by previous tests. * Something changed beyond the bgnd_bounds clearing. But without being able * to see, or writet he image at this point it is hard to tell what is wrong! * Only CompareOverlay seemed to return something sensible. */ try_bounds=CompareImageBounds(bgnd_image,curr,CompareClearLayer,exception); (void) FormatLocaleFile(stderr, "expand_ctst: %.20gx%.20g%+.20g%+.20g\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y ); try_bounds=CompareImageBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_any : %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif try_bounds=CompareImageBounds(bgnd_image,curr,CompareOverlayLayer,exception); #if DEBUG_OPT_FRAME try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_test: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif } /* Test if this background dispose is smaller than any of the other methods we tryed before this (including duplicated frame) */ if ( cleared || bgnd_bounds.width*bgnd_bounds.height +try_bounds.width*try_bounds.height < bounds[i-1].width*bounds[i-1].height +dup_bounds.width*dup_bounds.height +bounds[i].width*bounds[i].height ) { cleared=MagickFalse; bounds[i-1]=bgnd_bounds; bounds[i]=try_bounds; if ( disposals[i-1] == DupDispose ) dup_image=DestroyImage(dup_image); disposals[i-1]=BackgroundDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"expand_bgnd: accepted\n"); } else { (void) FormatLocaleFile(stderr,"expand_bgnd: reject\n"); #endif } } /* Finalise choice of dispose, set new prev_image, and junk any extra images as appropriate, */ if ( disposals[i-1] == DupDispose ) { if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); prev_image=DestroyImage(prev_image); prev_image=dup_image, dup_image=(Image *) NULL; bounds[i+1]=bounds[i]; bounds[i]=dup_bounds; disposals[i-1]=DupDispose; disposals[i]=BackgroundDispose; i++; } else { if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); if ( disposals[i-1] != PreviousDispose ) prev_image=DestroyImage(prev_image); if ( disposals[i-1] == BackgroundDispose ) prev_image=bgnd_image, bgnd_image=(Image *) NULL; if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); if ( disposals[i-1] == NoneDispose ) { prev_image=ReferenceImage(curr->previous); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } } } assert(prev_image != (Image *) NULL); disposals[i]=disposals[i-1]; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "final %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i-1, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]), (double) bounds[i-1].width,(double) bounds[i-1].height, (double) bounds[i-1].x,(double) bounds[i-1].y ); #endif #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "interum %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]), (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); (void) FormatLocaleFile(stderr,"\n"); #endif i++; } prev_image=DestroyImage(prev_image); /* Optimize all images in sequence. */ sans_exception=AcquireExceptionInfo(); i=0; curr=GetFirstImageInList(image); optimized_image=NewImageList(); while ( curr != (const Image *) NULL ) { prev_image=CloneImage(curr,0,0,MagickTrue,exception); if (prev_image == (Image *) NULL) break; if ( disposals[i] == DelDispose ) { size_t time = 0; while ( disposals[i] == DelDispose ) { time += curr->delay*1000/curr->ticks_per_second; curr=GetNextImageInList(curr); i++; } time += curr->delay*1000/curr->ticks_per_second; prev_image->ticks_per_second = 100L; prev_image->delay = time*prev_image->ticks_per_second/1000; } bgnd_image=CropImage(prev_image,&bounds[i],sans_exception); prev_image=DestroyImage(prev_image); if (bgnd_image == (Image *) NULL) break; bgnd_image->dispose=disposals[i]; if ( disposals[i] == DupDispose ) { bgnd_image->delay=0; bgnd_image->dispose=NoneDispose; } else curr=GetNextImageInList(curr); AppendImageToList(&optimized_image,bgnd_image); i++; } sans_exception=DestroyExceptionInfo(sans_exception); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); if (curr != (Image *) NULL) { optimized_image=DestroyImageList(optimized_image); return((Image *) NULL); } return(GetFirstImageInList(optimized_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageLayers() compares each image the GIF disposed forms of the % previous image in the sequence. From this it attempts to select the % smallest cropped image to replace each frame, while preserving the results % of the GIF animation. % % The format of the OptimizeImageLayers method is: % % Image *OptimizeImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizeImageLayers(const Image *image, ExceptionInfo *exception) { return(OptimizeLayerFrames(image,OptimizeImageLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e P l u s I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImagePlusLayers() is exactly as OptimizeImageLayers(), but may % also add or even remove extra frames in the animation, if it improves % the total number of pixels in the resulting GIF animation. % % The format of the OptimizePlusImageLayers method is: % % Image *OptimizePlusImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizePlusImageLayers(const Image *image, ExceptionInfo *exception) { return OptimizeLayerFrames(image,OptimizePlusLayer,exception); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e T r a n s p a r e n c y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageTransparency() takes a frame optimized GIF animation, and % compares the overlayed pixels against the disposal image resulting from all % the previous frames in the animation. Any pixel that does not change the % disposal image (and thus does not effect the outcome of an overlay) is made % transparent. % % WARNING: This modifies the current images directly, rather than generate % a new image sequence. % % The format of the OptimizeImageTransperency method is: % % void OptimizeImageTransperency(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence % % o exception: return any errors or warnings in this structure. % */ MagickExport void OptimizeImageTransparency(const Image *image, ExceptionInfo *exception) { Image *dispose_image; register Image *next; /* Run the image through the animation sequence */ 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); next=GetFirstImageInList(image); dispose_image=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return; dispose_image->page=next->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.opacity=(Quantum) TransparentOpacity; (void) SetImageBackgroundColor(dispose_image); while ( next != (Image *) NULL ) { Image *current_image; /* Overlay this frame's image over the previous disposal image */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_image=DestroyImage(dispose_image); return; } (void) CompositeImage(current_image,next->matte != MagickFalse ? OverCompositeOp : CopyCompositeOp,next,next->page.x,next->page.y); /* At this point the image would be displayed, for the delay period ** Work out the disposal of the previous image */ if (next->dispose == BackgroundDispose) { RectangleInfo bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds); } if (next->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; } else current_image=DestroyImage(current_image); /* Optimize Transparency of the next frame (if present) */ next=GetNextImageInList(next); if (next != (Image *) NULL) { (void) CompositeImage(next,ChangeMaskCompositeOp,dispose_image, -(next->page.x),-(next->page.y)); } } dispose_image=DestroyImage(dispose_image); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e D u p l i c a t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveDuplicateLayers() removes any image that is exactly the same as the % next image in the given image list. Image size and virtual canvas offset % must also match, though not the virtual canvas size itself. % % No check is made with regards to image disposal setting, though it is the % dispose setting of later image that is kept. Also any time delays are also % added together. As such coalesced image animations should still produce the % same result, though with duplicte frames merged into a single frame. % % The format of the RemoveDuplicateLayers method is: % % void RemoveDuplicateLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception) { RectangleInfo bounds; register Image *image, *next; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(*images); for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next) { if ((image->columns != next->columns) || (image->rows != next->rows) || (image->page.x != next->page.x) || (image->page.y != next->page.y)) continue; bounds=CompareImageBounds(image,next,CompareAnyLayer,exception); if (bounds.x < 0) { /* Two images are the same, merge time delays and delete one. */ size_t time; time=1000*image->delay*PerceptibleReciprocal(image->ticks_per_second); time+=1000*next->delay*PerceptibleReciprocal(next->ticks_per_second); next->ticks_per_second=100L; next->delay=time*image->ticks_per_second/1000; next->iterations=image->iterations; *images=image; (void) DeleteImageFromList(images); } } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e Z e r o D e l a y L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveZeroDelayLayers() removes any image that as a zero delay time. Such % images generally represent intermediate or partial updates in GIF % animations used for file optimization. They are not ment to be displayed % to users of the animation. Viewable images in an animation should have a % time delay of 3 or more centi-seconds (hundredths of a second). % % However if all the frames have a zero time delay, then either the animation % is as yet incomplete, or it is not a GIF animation. This a non-sensible % situation, so no image will be removed and a 'Zero Time Animation' warning % (exception) given. % % No warning will be given if no image was removed because all images had an % appropriate non-zero time delay set. % % Due to the special requirements of GIF disposal handling, GIF animations % should be coalesced first, before calling this function, though that is not % a requirement. % % The format of the RemoveZeroDelayLayers method is: % % void RemoveZeroDelayLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveZeroDelayLayers(Image **images, ExceptionInfo *exception) { Image *i; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); i=GetFirstImageInList(*images); for ( ; i != (Image *) NULL; i=GetNextImageInList(i)) if ( i->delay != 0L ) break; if ( i == (Image *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ZeroTimeAnimation","`%s'",GetFirstImageInList(*images)->filename); return; } i=GetFirstImageInList(*images); while ( i != (Image *) NULL ) { if ( i->delay == 0L ) { (void) DeleteImageFromList(&i); *images=i; } else i=GetNextImageInList(i); } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeLayers() compose the source image sequence over the destination % image sequence, starting with the current image in both lists. % % Each layer from the two image lists are composted together until the end of % one of the image lists is reached. The offset of each composition is also % adjusted to match the virtual canvas offsets of each layer. As such the % given offset is relative to the virtual canvas, and not the actual image. % % Composition uses given x and y offsets, as the 'origin' location of the % source images virtual canvas (not the real image) allowing you to compose a % list of 'layer images' into the destiantioni images. This makes it well % sutiable for directly composing 'Clears Frame Animations' or 'Coaleased % Animations' onto a static or other 'Coaleased Animation' destination image % list. GIF disposal handling is not looked at. % % Special case:- If one of the image sequences is the last image (just a % single image remaining), that image is repeatally composed with all the % images in the other image list. Either the source or destination lists may % be the single image, for this situation. % % In the case of a single destination image (or last image given), that image % will ve cloned to match the number of images remaining in the source image % list. % % This is equivelent to the "-layer Composite" Shell API operator. % % % The format of the CompositeLayers method is: % % void CompositeLayers(Image *destination, % const CompositeOperator compose, Image *source, % const ssize_t x_offset, const ssize_t y_offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o destination: the destination images and results % % o source: source image(s) for the layer composition % % o compose, x_offset, y_offset: arguments passed on to CompositeImages() % % o exception: return any errors or warnings in this structure. % */ static inline void CompositeCanvas(Image *destination, const CompositeOperator compose, Image *source,ssize_t x_offset, ssize_t y_offset ) { x_offset+=source->page.x-destination->page.x; y_offset+=source->page.y-destination->page.y; (void) CompositeImage(destination,compose,source,x_offset,y_offset); } MagickExport void CompositeLayers(Image *destination, const CompositeOperator compose, Image *source,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { assert(destination != (Image *) NULL); assert(destination->signature == MagickCoreSignature); assert(source != (Image *) NULL); assert(source->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (source->debug != MagickFalse || destination->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s - %s", source->filename,destination->filename); /* Overlay single source image over destation image/list */ if ( source->next == (Image *) NULL ) while ( destination != (Image *) NULL ) { CompositeCanvas(destination,compose,source,x_offset,y_offset); destination=GetNextImageInList(destination); } /* Overlay source image list over single destination Generating multiple clones of destination image to match source list. Original Destination image becomes first image of generated list. As such the image list pointer does not require any change in caller. Some animation attributes however also needs coping in this case. */ else if ( destination->next == (Image *) NULL ) { Image *dest = CloneImage(destination,0,0,MagickTrue,exception); CompositeCanvas(destination,compose,source,x_offset,y_offset); /* copy source image attributes ? */ if ( source->next != (Image *) NULL ) { destination->delay = source->delay; destination->iterations = source->iterations; } source=GetNextImageInList(source); while ( source != (Image *) NULL ) { AppendImageToList(&destination, CloneImage(dest,0,0,MagickTrue,exception)); destination=GetLastImageInList(destination); CompositeCanvas(destination,compose,source,x_offset,y_offset); destination->delay = source->delay; destination->iterations = source->iterations; source=GetNextImageInList(source); } dest=DestroyImage(dest); } /* Overlay a source image list over a destination image list until either list runs out of images. (Does not repeat) */ else while ( source != (Image *) NULL && destination != (Image *) NULL ) { CompositeCanvas(destination,compose,source,x_offset,y_offset); source=GetNextImageInList(source); destination=GetNextImageInList(destination); } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e r g e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MergeImageLayers() composes all the image layers from the current given % image onward to produce a single image of the merged layers. % % The inital canvas's size depends on the given ImageLayerMethod, and is % initialized using the first images background color. The images % are then compositied onto that image in sequence using the given % composition that has been assigned to each individual image. % % The format of the MergeImageLayers is: % % Image *MergeImageLayers(const Image *image, % const ImageLayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image list to be composited together % % o method: the method of selecting the size of the initial canvas. % % MergeLayer: Merge all layers onto a canvas just large enough % to hold all the actual images. The virtual canvas of the % first image is preserved but otherwise ignored. % % FlattenLayer: Use the virtual canvas size of first image. % Images which fall outside this canvas is clipped. % This can be used to 'fill out' a given virtual canvas. % % MosaicLayer: Start with the virtual canvas of the first image, % enlarging left and right edges to contain all images. % Images with negative offsets will be clipped. % % TrimBoundsLayer: Determine the overall bounds of all the image % layers just as in "MergeLayer", then adjust the the canvas % and offsets to be relative to those bounds, without overlaying % the images. % % WARNING: a new image is not returned, the original image % sequence page data is modified instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MergeImageLayers(Image *image, const ImageLayerMethod method,ExceptionInfo *exception) { #define MergeLayersTag "Merge/Layers" Image *canvas; MagickBooleanType proceed; RectangleInfo page; register const Image *next; size_t number_images, height, width; ssize_t scene; 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); /* Determine canvas image size, and its virtual canvas size and offset. */ page=image->page; width=image->columns; height=image->rows; switch (method) { case TrimBoundsLayer: case MergeLayer: default: { next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (page.x > next->page.x) { width+=page.x-next->page.x; page.x=next->page.x; } if (page.y > next->page.y) { height+=page.y-next->page.y; page.y=next->page.y; } if ((ssize_t) width < (next->page.x+(ssize_t) next->columns-page.x)) width=(size_t) next->page.x+(ssize_t) next->columns-page.x; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows-page.y)) height=(size_t) next->page.y+(ssize_t) next->rows-page.y; } break; } case FlattenLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; page.x=0; page.y=0; break; } case MosaicLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { if ((ssize_t) width < (next->page.x+(ssize_t) next->columns)) width=(size_t) next->page.x+next->columns; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows)) height=(size_t) next->page.y+next->rows; } page.width=width; page.height=height; page.x=0; page.y=0; break; } } /* Set virtual canvas size if not defined. */ if (page.width == 0) page.width=page.x < 0 ? width : width+page.x; if (page.height == 0) page.height=page.y < 0 ? height : height+page.y; /* Handle "TrimBoundsLayer" method separately to normal 'layer merge'. */ if (method == TrimBoundsLayer) { number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { image->page.x-=page.x; image->page.y-=page.y; image->page.width=width; image->page.height=height; proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return((Image *) NULL); } /* Create canvas size of width and height, and background color. */ canvas=CloneImage(image,width,height,MagickTrue,exception); if (canvas == (Image *) NULL) return((Image *) NULL); (void) SetImageBackgroundColor(canvas); canvas->page=page; canvas->dispose=UndefinedDispose; /* Compose images onto canvas, with progress monitor */ number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { (void) CompositeImage(canvas,image->compose,image,image->page.x- canvas->page.x,image->page.y-canvas->page.y); proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return(canvas); }
./CrossVul/dataset_final_sorted/CWE-369/c/good_952_0
crossvul-cpp_data_good_1009_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF EEEEE AAA TTTTT U U RRRR EEEEE % % F E A A T U U R R E % % FFF EEE AAAAA T U U RRRR EEE % % F E A A T U U R R E % % F EEEEE A A T UUU R R EEEEE % % % % % % MagickCore Image Feature Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 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://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/animate.h" #include "magick/artifact.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/display.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/feature.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/image-private.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/matrix.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/morphology-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/semaphore.h" #include "magick/signature-private.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/timer.h" #include "magick/token.h" #include "magick/utility.h" #include "magick/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a n n y E d g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CannyEdgeImage() uses a multi-stage algorithm to detect a wide range of % edges in images. % % The format of the CannyEdgeImage method is: % % Image *CannyEdgeImage(const Image *image,const double radius, % const double sigma,const double lower_percent, % const double upper_percent,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the gaussian smoothing filter. % % o sigma: the sigma of the gaussian smoothing filter. % % o lower_percent: percentage of edge pixels in the lower threshold. % % o upper_percent: percentage of edge pixels in the upper threshold. % % o exception: return any errors or warnings in this structure. % */ typedef struct _CannyInfo { double magnitude, intensity; int orientation; ssize_t x, y; } CannyInfo; static inline MagickBooleanType IsAuthenticPixel(const Image *image, const ssize_t x,const ssize_t y) { if ((x < 0) || (x >= (ssize_t) image->columns)) return(MagickFalse); if ((y < 0) || (y >= (ssize_t) image->rows)) return(MagickFalse); return(MagickTrue); } static MagickBooleanType TraceEdges(Image *edge_image,CacheView *edge_view, MatrixInfo *canny_cache,const ssize_t x,const ssize_t y, const double lower_threshold,ExceptionInfo *exception) { CannyInfo edge, pixel; MagickBooleanType status; register PixelPacket *q; register ssize_t i; q=GetCacheViewAuthenticPixels(edge_view,x,y,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickFalse); q->red=QuantumRange; q->green=QuantumRange; q->blue=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); if (GetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); edge.x=x; edge.y=y; if (SetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); for (i=1; i != 0; ) { ssize_t v; i--; status=GetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); for (v=(-1); v <= 1; v++) { ssize_t u; for (u=(-1); u <= 1; u++) { if ((u == 0) && (v == 0)) continue; if (IsAuthenticPixel(edge_image,edge.x+u,edge.y+v) == MagickFalse) continue; /* Not an edge if gradient value is below the lower threshold. */ q=GetCacheViewAuthenticPixels(edge_view,edge.x+u,edge.y+v,1,1, exception); if (q == (PixelPacket *) NULL) return(MagickFalse); status=GetMatrixElement(canny_cache,edge.x+u,edge.y+v,&pixel); if (status == MagickFalse) return(MagickFalse); if ((GetPixelIntensity(edge_image,q) == 0.0) && (pixel.intensity >= lower_threshold)) { q->red=QuantumRange; q->green=QuantumRange; q->blue=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); edge.x+=u; edge.y+=v; status=SetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); i++; } } } } return(MagickTrue); } MagickExport Image *CannyEdgeImage(const Image *image,const double radius, const double sigma,const double lower_percent,const double upper_percent, ExceptionInfo *exception) { #define CannyEdgeImageTag "CannyEdge/Image" CacheView *edge_view; CannyInfo element; char geometry[MaxTextExtent]; double lower_threshold, max, min, upper_threshold; Image *edge_image; KernelInfo *kernel_info; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *canny_cache; ssize_t y; assert(image != (const 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); /* Filter out noise. */ (void) FormatLocaleString(geometry,MaxTextExtent, "blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma); kernel_info=AcquireKernelInfo(geometry); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); edge_image=MorphologyImageChannel(image,DefaultChannels,ConvolveMorphology,1, kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); if (edge_image == (Image *) NULL) return((Image *) NULL); if (TransformImageColorspace(edge_image,GRAYColorspace) == MagickFalse) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } (void) SetImageAlphaChannel(edge_image,DeactivateAlphaChannel); /* Find the intensity gradient of the image. */ canny_cache=AcquireMatrixInfo(edge_image->columns,edge_image->rows, sizeof(CannyInfo),exception); if (canny_cache == (MatrixInfo *) NULL) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } status=MagickTrue; edge_view=AcquireVirtualCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns+1,2, exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; double dx, dy; register const PixelPacket *magick_restrict kernel_pixels; ssize_t v; static double Gx[2][2] = { { -1.0, +1.0 }, { -1.0, +1.0 } }, Gy[2][2] = { { +1.0, +1.0 }, { -1.0, -1.0 } }; (void) memset(&pixel,0,sizeof(pixel)); dx=0.0; dy=0.0; kernel_pixels=p; for (v=0; v < 2; v++) { ssize_t u; for (u=0; u < 2; u++) { double intensity; intensity=GetPixelIntensity(edge_image,kernel_pixels+u); dx+=0.5*Gx[v][u]*intensity; dy+=0.5*Gy[v][u]*intensity; } kernel_pixels+=edge_image->columns+1; } pixel.magnitude=hypot(dx,dy); pixel.orientation=0; if (fabs(dx) > MagickEpsilon) { double slope; slope=dy/dx; if (slope < 0.0) { if (slope < -2.41421356237) pixel.orientation=0; else if (slope < -0.414213562373) pixel.orientation=1; else pixel.orientation=2; } else { if (slope > 2.41421356237) pixel.orientation=0; else if (slope > 0.414213562373) pixel.orientation=3; else pixel.orientation=2; } } if (SetMatrixElement(canny_cache,x,y,&pixel) == MagickFalse) continue; p++; } } edge_view=DestroyCacheView(edge_view); /* Non-maxima suppression, remove pixels that are not considered to be part of an edge. */ progress=0; (void) GetMatrixElement(canny_cache,0,0,&element); max=element.intensity; min=element.intensity; edge_view=AcquireAuthenticCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(edge_view,0,y,edge_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo alpha_pixel, beta_pixel, pixel; (void) GetMatrixElement(canny_cache,x,y,&pixel); switch (pixel.orientation) { case 0: default: { /* 0 degrees, north and south. */ (void) GetMatrixElement(canny_cache,x,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x,y+1,&beta_pixel); break; } case 1: { /* 45 degrees, northwest and southeast. */ (void) GetMatrixElement(canny_cache,x-1,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y+1,&beta_pixel); break; } case 2: { /* 90 degrees, east and west. */ (void) GetMatrixElement(canny_cache,x-1,y,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y,&beta_pixel); break; } case 3: { /* 135 degrees, northeast and southwest. */ (void) GetMatrixElement(canny_cache,x+1,y-1,&beta_pixel); (void) GetMatrixElement(canny_cache,x-1,y+1,&alpha_pixel); break; } } pixel.intensity=pixel.magnitude; if ((pixel.magnitude < alpha_pixel.magnitude) || (pixel.magnitude < beta_pixel.magnitude)) pixel.intensity=0; (void) SetMatrixElement(canny_cache,x,y,&pixel); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CannyEdgeImage) #endif { if (pixel.intensity < min) min=pixel.intensity; if (pixel.intensity > max) max=pixel.intensity; } q->red=0; q->green=0; q->blue=0; q++; } if (SyncCacheViewAuthenticPixels(edge_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CannyEdgeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } edge_view=DestroyCacheView(edge_view); /* Estimate hysteresis threshold. */ lower_threshold=lower_percent*(max-min)+min; upper_threshold=upper_percent*(max-min)+min; /* Hysteresis threshold. */ edge_view=AcquireAuthenticCacheView(edge_image,exception); for (y=0; y < (ssize_t) edge_image->rows; y++) { register ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; register const PixelPacket *magick_restrict p; /* Edge if pixel gradient higher than upper threshold. */ p=GetCacheViewVirtualPixels(edge_view,x,y,1,1,exception); if (p == (const PixelPacket *) NULL) continue; status=GetMatrixElement(canny_cache,x,y,&pixel); if (status == MagickFalse) continue; if ((GetPixelIntensity(edge_image,p) == 0.0) && (pixel.intensity >= upper_threshold)) status=TraceEdges(edge_image,edge_view,canny_cache,x,y,lower_threshold, exception); } } edge_view=DestroyCacheView(edge_view); /* Free resources. */ canny_cache=DestroyMatrixInfo(canny_cache); return(edge_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l F e a t u r e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelFeatures() returns features for each channel in the image in % each of four directions (horizontal, vertical, left and right diagonals) % for the specified distance. The features include the angular second % moment, contrast, correlation, sum of squares: variance, inverse difference % moment, sum average, sum varience, sum entropy, entropy, difference variance,% difference entropy, information measures of correlation 1, information % measures of correlation 2, and maximum correlation coefficient. You can % access the red channel contrast, for example, like this: % % channel_features=GetImageChannelFeatures(image,1,exception); % contrast=channel_features[RedChannel].contrast[0]; % % Use MagickRelinquishMemory() to free the features buffer. % % The format of the GetImageChannelFeatures method is: % % ChannelFeatures *GetImageChannelFeatures(const Image *image, % const size_t distance,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o distance: the distance. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelFeatures *GetImageChannelFeatures(const Image *image, const size_t distance,ExceptionInfo *exception) { typedef struct _ChannelStatistics { DoublePixelPacket direction[4]; /* horizontal, vertical, left and right diagonals */ } ChannelStatistics; CacheView *image_view; ChannelFeatures *channel_features; ChannelStatistics **cooccurrence, correlation, *density_x, *density_xy, *density_y, entropy_x, entropy_xy, entropy_xy1, entropy_xy2, entropy_y, mean, **Q, *sum, sum_squares, variance; LongPixelPacket gray, *grays; MagickBooleanType status; register ssize_t i; size_t length; ssize_t y; unsigned int number_grays; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns < (distance+1)) || (image->rows < (distance+1))) return((ChannelFeatures *) NULL); length=CompositeChannels+1UL; channel_features=(ChannelFeatures *) AcquireQuantumMemory(length, sizeof(*channel_features)); if (channel_features == (ChannelFeatures *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(channel_features,0,length* sizeof(*channel_features)); /* Form grays. */ grays=(LongPixelPacket *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*grays)); if (grays == (LongPixelPacket *) NULL) { channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } for (i=0; i <= (ssize_t) MaxMap; i++) { grays[i].red=(~0U); grays[i].green=(~0U); grays[i].blue=(~0U); grays[i].opacity=(~0U); grays[i].index=(~0U); } status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { grays[ScaleQuantumToMap(GetPixelRed(p))].red= ScaleQuantumToMap(GetPixelRed(p)); grays[ScaleQuantumToMap(GetPixelGreen(p))].green= ScaleQuantumToMap(GetPixelGreen(p)); grays[ScaleQuantumToMap(GetPixelBlue(p))].blue= ScaleQuantumToMap(GetPixelBlue(p)); if (image->colorspace == CMYKColorspace) grays[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index= ScaleQuantumToMap(GetPixelIndex(indexes+x)); if (image->matte != MagickFalse) grays[ScaleQuantumToMap(GetPixelOpacity(p))].opacity= ScaleQuantumToMap(GetPixelOpacity(p)); p++; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { grays=(LongPixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); return(channel_features); } (void) memset(&gray,0,sizeof(gray)); for (i=0; i <= (ssize_t) MaxMap; i++) { if (grays[i].red != ~0U) grays[(ssize_t) gray.red++].red=grays[i].red; if (grays[i].green != ~0U) grays[(ssize_t) gray.green++].green=grays[i].green; if (grays[i].blue != ~0U) grays[(ssize_t) gray.blue++].blue=grays[i].blue; if (image->colorspace == CMYKColorspace) if (grays[i].index != ~0U) grays[(ssize_t) gray.index++].index=grays[i].index; if (image->matte != MagickFalse) if (grays[i].opacity != ~0U) grays[(ssize_t) gray.opacity++].opacity=grays[i].opacity; } /* Allocate spatial dependence matrix. */ number_grays=gray.red; if (gray.green > number_grays) number_grays=gray.green; if (gray.blue > number_grays) number_grays=gray.blue; if (image->colorspace == CMYKColorspace) if (gray.index > number_grays) number_grays=gray.index; if (image->matte != MagickFalse) if (gray.opacity > number_grays) number_grays=gray.opacity; cooccurrence=(ChannelStatistics **) AcquireQuantumMemory(number_grays, sizeof(*cooccurrence)); density_x=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_x)); density_xy=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_xy)); density_y=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_y)); Q=(ChannelStatistics **) AcquireQuantumMemory(number_grays,sizeof(*Q)); sum=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(*sum)); if ((cooccurrence == (ChannelStatistics **) NULL) || (density_x == (ChannelStatistics *) NULL) || (density_xy == (ChannelStatistics *) NULL) || (density_y == (ChannelStatistics *) NULL) || (Q == (ChannelStatistics **) NULL) || (sum == (ChannelStatistics *) NULL)) { if (Q != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); } if (sum != (ChannelStatistics *) NULL) sum=(ChannelStatistics *) RelinquishMagickMemory(sum); if (density_y != (ChannelStatistics *) NULL) density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); if (density_xy != (ChannelStatistics *) NULL) density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); if (density_x != (ChannelStatistics *) NULL) density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); if (cooccurrence != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory( cooccurrence); } grays=(LongPixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } (void) memset(&correlation,0,sizeof(correlation)); (void) memset(density_x,0,2*(number_grays+1)*sizeof(*density_x)); (void) memset(density_xy,0,2*(number_grays+1)*sizeof(*density_xy)); (void) memset(density_y,0,2*(number_grays+1)*sizeof(*density_y)); (void) memset(&mean,0,sizeof(mean)); (void) memset(sum,0,number_grays*sizeof(*sum)); (void) memset(&sum_squares,0,sizeof(sum_squares)); (void) memset(density_xy,0,2*number_grays*sizeof(*density_xy)); (void) memset(&entropy_x,0,sizeof(entropy_x)); (void) memset(&entropy_xy,0,sizeof(entropy_xy)); (void) memset(&entropy_xy1,0,sizeof(entropy_xy1)); (void) memset(&entropy_xy2,0,sizeof(entropy_xy2)); (void) memset(&entropy_y,0,sizeof(entropy_y)); (void) memset(&variance,0,sizeof(variance)); for (i=0; i < (ssize_t) number_grays; i++) { cooccurrence[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays, sizeof(**cooccurrence)); Q[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(**Q)); if ((cooccurrence[i] == (ChannelStatistics *) NULL) || (Q[i] == (ChannelStatistics *) NULL)) break; (void) memset(cooccurrence[i],0,number_grays* sizeof(**cooccurrence)); (void) memset(Q[i],0,number_grays*sizeof(**Q)); } if (i < (ssize_t) number_grays) { for (i--; i >= 0; i--) { if (Q[i] != (ChannelStatistics *) NULL) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); if (cooccurrence[i] != (ChannelStatistics *) NULL) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); } Q=(ChannelStatistics **) RelinquishMagickMemory(Q); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); sum=(ChannelStatistics *) RelinquishMagickMemory(sum); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); grays=(LongPixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Initialize spatial dependence matrix. */ status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; ssize_t i, offset, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-(ssize_t) distance,y,image->columns+ 2*distance,distance+2,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); p+=distance; indexes+=distance; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < 4; i++) { switch (i) { case 0: default: { /* Horizontal adjacency. */ offset=(ssize_t) distance; break; } case 1: { /* Vertical adjacency. */ offset=(ssize_t) (image->columns+2*distance); break; } case 2: { /* Right diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)-distance); break; } case 3: { /* Left diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)+distance); break; } } u=0; v=0; while (grays[u].red != ScaleQuantumToMap(GetPixelRed(p))) u++; while (grays[v].red != ScaleQuantumToMap(GetPixelRed(p+offset))) v++; cooccurrence[u][v].direction[i].red++; cooccurrence[v][u].direction[i].red++; u=0; v=0; while (grays[u].green != ScaleQuantumToMap(GetPixelGreen(p))) u++; while (grays[v].green != ScaleQuantumToMap(GetPixelGreen(p+offset))) v++; cooccurrence[u][v].direction[i].green++; cooccurrence[v][u].direction[i].green++; u=0; v=0; while (grays[u].blue != ScaleQuantumToMap(GetPixelBlue(p))) u++; while (grays[v].blue != ScaleQuantumToMap((p+offset)->blue)) v++; cooccurrence[u][v].direction[i].blue++; cooccurrence[v][u].direction[i].blue++; if (image->colorspace == CMYKColorspace) { u=0; v=0; while (grays[u].index != ScaleQuantumToMap(GetPixelIndex(indexes+x))) u++; while (grays[v].index != ScaleQuantumToMap(GetPixelIndex(indexes+x+offset))) v++; cooccurrence[u][v].direction[i].index++; cooccurrence[v][u].direction[i].index++; } if (image->matte != MagickFalse) { u=0; v=0; while (grays[u].opacity != ScaleQuantumToMap(GetPixelOpacity(p))) u++; while (grays[v].opacity != ScaleQuantumToMap((p+offset)->opacity)) v++; cooccurrence[u][v].direction[i].opacity++; cooccurrence[v][u].direction[i].opacity++; } } p++; } } grays=(LongPixelPacket *) RelinquishMagickMemory(grays); image_view=DestroyCacheView(image_view); if (status == MagickFalse) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Normalize spatial dependence matrix. */ for (i=0; i < 4; i++) { double normalize; register ssize_t y; switch (i) { case 0: default: { /* Horizontal adjacency. */ normalize=2.0*image->rows*(image->columns-distance); break; } case 1: { /* Vertical adjacency. */ normalize=2.0*(image->rows-distance)*image->columns; break; } case 2: { /* Right diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } case 3: { /* Left diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } } normalize=PerceptibleReciprocal(normalize); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { cooccurrence[x][y].direction[i].red*=normalize; cooccurrence[x][y].direction[i].green*=normalize; cooccurrence[x][y].direction[i].blue*=normalize; if (image->colorspace == CMYKColorspace) cooccurrence[x][y].direction[i].index*=normalize; if (image->matte != MagickFalse) cooccurrence[x][y].direction[i].opacity*=normalize; } } } /* Compute texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Angular second moment: measure of homogeneity of the image. */ channel_features[RedChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].red* cooccurrence[x][y].direction[i].red; channel_features[GreenChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].green* cooccurrence[x][y].direction[i].green; channel_features[BlueChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].blue* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].index* cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) channel_features[OpacityChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].opacity* cooccurrence[x][y].direction[i].opacity; /* Correlation: measure of linear-dependencies in the image. */ sum[y].direction[i].red+=cooccurrence[x][y].direction[i].red; sum[y].direction[i].green+=cooccurrence[x][y].direction[i].green; sum[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) sum[y].direction[i].index+=cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) sum[y].direction[i].opacity+=cooccurrence[x][y].direction[i].opacity; correlation.direction[i].red+=x*y*cooccurrence[x][y].direction[i].red; correlation.direction[i].green+=x*y* cooccurrence[x][y].direction[i].green; correlation.direction[i].blue+=x*y* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) correlation.direction[i].index+=x*y* cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) correlation.direction[i].opacity+=x*y* cooccurrence[x][y].direction[i].opacity; /* Inverse Difference Moment. */ channel_features[RedChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].red/((y-x)*(y-x)+1); channel_features[GreenChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].green/((y-x)*(y-x)+1); channel_features[BlueChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].blue/((y-x)*(y-x)+1); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].index/((y-x)*(y-x)+1); if (image->matte != MagickFalse) channel_features[OpacityChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].opacity/((y-x)*(y-x)+1); /* Sum average. */ density_xy[y+x+2].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[y+x+2].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[y+x+2].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[y+x+2].direction[i].index+= cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) density_xy[y+x+2].direction[i].opacity+= cooccurrence[x][y].direction[i].opacity; /* Entropy. */ channel_features[RedChannel].entropy[i]-= cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); channel_features[GreenChannel].entropy[i]-= cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); channel_features[BlueChannel].entropy[i]-= cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].entropy[i]-= cooccurrence[x][y].direction[i].index* MagickLog10(cooccurrence[x][y].direction[i].index); if (image->matte != MagickFalse) channel_features[OpacityChannel].entropy[i]-= cooccurrence[x][y].direction[i].opacity* MagickLog10(cooccurrence[x][y].direction[i].opacity); /* Information Measures of Correlation. */ density_x[x].direction[i].red+=cooccurrence[x][y].direction[i].red; density_x[x].direction[i].green+=cooccurrence[x][y].direction[i].green; density_x[x].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_x[x].direction[i].index+= cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) density_x[x].direction[i].opacity+= cooccurrence[x][y].direction[i].opacity; density_y[y].direction[i].red+=cooccurrence[x][y].direction[i].red; density_y[y].direction[i].green+=cooccurrence[x][y].direction[i].green; density_y[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_y[y].direction[i].index+= cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) density_y[y].direction[i].opacity+= cooccurrence[x][y].direction[i].opacity; } mean.direction[i].red+=y*sum[y].direction[i].red; sum_squares.direction[i].red+=y*y*sum[y].direction[i].red; mean.direction[i].green+=y*sum[y].direction[i].green; sum_squares.direction[i].green+=y*y*sum[y].direction[i].green; mean.direction[i].blue+=y*sum[y].direction[i].blue; sum_squares.direction[i].blue+=y*y*sum[y].direction[i].blue; if (image->colorspace == CMYKColorspace) { mean.direction[i].index+=y*sum[y].direction[i].index; sum_squares.direction[i].index+=y*y*sum[y].direction[i].index; } if (image->matte != MagickFalse) { mean.direction[i].opacity+=y*sum[y].direction[i].opacity; sum_squares.direction[i].opacity+=y*y*sum[y].direction[i].opacity; } } /* Correlation: measure of linear-dependencies in the image. */ channel_features[RedChannel].correlation[i]= (correlation.direction[i].red-mean.direction[i].red* mean.direction[i].red)/(sqrt(sum_squares.direction[i].red- (mean.direction[i].red*mean.direction[i].red))*sqrt( sum_squares.direction[i].red-(mean.direction[i].red* mean.direction[i].red))); channel_features[GreenChannel].correlation[i]= (correlation.direction[i].green-mean.direction[i].green* mean.direction[i].green)/(sqrt(sum_squares.direction[i].green- (mean.direction[i].green*mean.direction[i].green))*sqrt( sum_squares.direction[i].green-(mean.direction[i].green* mean.direction[i].green))); channel_features[BlueChannel].correlation[i]= (correlation.direction[i].blue-mean.direction[i].blue* mean.direction[i].blue)/(sqrt(sum_squares.direction[i].blue- (mean.direction[i].blue*mean.direction[i].blue))*sqrt( sum_squares.direction[i].blue-(mean.direction[i].blue* mean.direction[i].blue))); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].correlation[i]= (correlation.direction[i].index-mean.direction[i].index* mean.direction[i].index)/(sqrt(sum_squares.direction[i].index- (mean.direction[i].index*mean.direction[i].index))*sqrt( sum_squares.direction[i].index-(mean.direction[i].index* mean.direction[i].index))); if (image->matte != MagickFalse) channel_features[OpacityChannel].correlation[i]= (correlation.direction[i].opacity-mean.direction[i].opacity* mean.direction[i].opacity)/(sqrt(sum_squares.direction[i].opacity- (mean.direction[i].opacity*mean.direction[i].opacity))*sqrt( sum_squares.direction[i].opacity-(mean.direction[i].opacity* mean.direction[i].opacity))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=2; x < (ssize_t) (2*number_grays); x++) { /* Sum average. */ channel_features[RedChannel].sum_average[i]+= x*density_xy[x].direction[i].red; channel_features[GreenChannel].sum_average[i]+= x*density_xy[x].direction[i].green; channel_features[BlueChannel].sum_average[i]+= x*density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].sum_average[i]+= x*density_xy[x].direction[i].index; if (image->matte != MagickFalse) channel_features[OpacityChannel].sum_average[i]+= x*density_xy[x].direction[i].opacity; /* Sum entropy. */ channel_features[RedChannel].sum_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenChannel].sum_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BlueChannel].sum_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].sum_entropy[i]-= density_xy[x].direction[i].index* MagickLog10(density_xy[x].direction[i].index); if (image->matte != MagickFalse) channel_features[OpacityChannel].sum_entropy[i]-= density_xy[x].direction[i].opacity* MagickLog10(density_xy[x].direction[i].opacity); /* Sum variance. */ channel_features[RedChannel].sum_variance[i]+= (x-channel_features[RedChannel].sum_entropy[i])* (x-channel_features[RedChannel].sum_entropy[i])* density_xy[x].direction[i].red; channel_features[GreenChannel].sum_variance[i]+= (x-channel_features[GreenChannel].sum_entropy[i])* (x-channel_features[GreenChannel].sum_entropy[i])* density_xy[x].direction[i].green; channel_features[BlueChannel].sum_variance[i]+= (x-channel_features[BlueChannel].sum_entropy[i])* (x-channel_features[BlueChannel].sum_entropy[i])* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].sum_variance[i]+= (x-channel_features[IndexChannel].sum_entropy[i])* (x-channel_features[IndexChannel].sum_entropy[i])* density_xy[x].direction[i].index; if (image->matte != MagickFalse) channel_features[OpacityChannel].sum_variance[i]+= (x-channel_features[OpacityChannel].sum_entropy[i])* (x-channel_features[OpacityChannel].sum_entropy[i])* density_xy[x].direction[i].opacity; } } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Sum of Squares: Variance */ variance.direction[i].red+=(y-mean.direction[i].red+1)* (y-mean.direction[i].red+1)*cooccurrence[x][y].direction[i].red; variance.direction[i].green+=(y-mean.direction[i].green+1)* (y-mean.direction[i].green+1)*cooccurrence[x][y].direction[i].green; variance.direction[i].blue+=(y-mean.direction[i].blue+1)* (y-mean.direction[i].blue+1)*cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].index+=(y-mean.direction[i].index+1)* (y-mean.direction[i].index+1)*cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) variance.direction[i].opacity+=(y-mean.direction[i].opacity+1)* (y-mean.direction[i].opacity+1)* cooccurrence[x][y].direction[i].opacity; /* Sum average / Difference Variance. */ density_xy[MagickAbsoluteValue(y-x)].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[MagickAbsoluteValue(y-x)].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[MagickAbsoluteValue(y-x)].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[MagickAbsoluteValue(y-x)].direction[i].index+= cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) density_xy[MagickAbsoluteValue(y-x)].direction[i].opacity+= cooccurrence[x][y].direction[i].opacity; /* Information Measures of Correlation. */ entropy_xy.direction[i].red-=cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); entropy_xy.direction[i].green-=cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); entropy_xy.direction[i].blue-=cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) entropy_xy.direction[i].index-=cooccurrence[x][y].direction[i].index* MagickLog10(cooccurrence[x][y].direction[i].index); if (image->matte != MagickFalse) entropy_xy.direction[i].opacity-= cooccurrence[x][y].direction[i].opacity*MagickLog10( cooccurrence[x][y].direction[i].opacity); entropy_xy1.direction[i].red-=(cooccurrence[x][y].direction[i].red* MagickLog10(density_x[x].direction[i].red* density_y[y].direction[i].red)); entropy_xy1.direction[i].green-=(cooccurrence[x][y].direction[i].green* MagickLog10(density_x[x].direction[i].green* density_y[y].direction[i].green)); entropy_xy1.direction[i].blue-=(cooccurrence[x][y].direction[i].blue* MagickLog10(density_x[x].direction[i].blue* density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy1.direction[i].index-=( cooccurrence[x][y].direction[i].index*MagickLog10( density_x[x].direction[i].index*density_y[y].direction[i].index)); if (image->matte != MagickFalse) entropy_xy1.direction[i].opacity-=( cooccurrence[x][y].direction[i].opacity*MagickLog10( density_x[x].direction[i].opacity* density_y[y].direction[i].opacity)); entropy_xy2.direction[i].red-=(density_x[x].direction[i].red* density_y[y].direction[i].red*MagickLog10( density_x[x].direction[i].red*density_y[y].direction[i].red)); entropy_xy2.direction[i].green-=(density_x[x].direction[i].green* density_y[y].direction[i].green*MagickLog10( density_x[x].direction[i].green*density_y[y].direction[i].green)); entropy_xy2.direction[i].blue-=(density_x[x].direction[i].blue* density_y[y].direction[i].blue*MagickLog10( density_x[x].direction[i].blue*density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy2.direction[i].index-=(density_x[x].direction[i].index* density_y[y].direction[i].index*MagickLog10( density_x[x].direction[i].index*density_y[y].direction[i].index)); if (image->matte != MagickFalse) entropy_xy2.direction[i].opacity-=(density_x[x].direction[i].opacity* density_y[y].direction[i].opacity*MagickLog10( density_x[x].direction[i].opacity* density_y[y].direction[i].opacity)); } } channel_features[RedChannel].variance_sum_of_squares[i]= variance.direction[i].red; channel_features[GreenChannel].variance_sum_of_squares[i]= variance.direction[i].green; channel_features[BlueChannel].variance_sum_of_squares[i]= variance.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[RedChannel].variance_sum_of_squares[i]= variance.direction[i].index; if (image->matte != MagickFalse) channel_features[RedChannel].variance_sum_of_squares[i]= variance.direction[i].opacity; } /* Compute more texture features. */ (void) memset(&variance,0,sizeof(variance)); (void) memset(&sum_squares,0,sizeof(sum_squares)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Difference variance. */ variance.direction[i].red+=density_xy[x].direction[i].red; variance.direction[i].green+=density_xy[x].direction[i].green; variance.direction[i].blue+=density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].index+=density_xy[x].direction[i].index; if (image->matte != MagickFalse) variance.direction[i].opacity+=density_xy[x].direction[i].opacity; sum_squares.direction[i].red+=density_xy[x].direction[i].red* density_xy[x].direction[i].red; sum_squares.direction[i].green+=density_xy[x].direction[i].green* density_xy[x].direction[i].green; sum_squares.direction[i].blue+=density_xy[x].direction[i].blue* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) sum_squares.direction[i].index+=density_xy[x].direction[i].index* density_xy[x].direction[i].index; if (image->matte != MagickFalse) sum_squares.direction[i].opacity+=density_xy[x].direction[i].opacity* density_xy[x].direction[i].opacity; /* Difference entropy. */ channel_features[RedChannel].difference_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenChannel].difference_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BlueChannel].difference_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].difference_entropy[i]-= density_xy[x].direction[i].index* MagickLog10(density_xy[x].direction[i].index); if (image->matte != MagickFalse) channel_features[OpacityChannel].difference_entropy[i]-= density_xy[x].direction[i].opacity* MagickLog10(density_xy[x].direction[i].opacity); /* Information Measures of Correlation. */ entropy_x.direction[i].red-=(density_x[x].direction[i].red* MagickLog10(density_x[x].direction[i].red)); entropy_x.direction[i].green-=(density_x[x].direction[i].green* MagickLog10(density_x[x].direction[i].green)); entropy_x.direction[i].blue-=(density_x[x].direction[i].blue* MagickLog10(density_x[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_x.direction[i].index-=(density_x[x].direction[i].index* MagickLog10(density_x[x].direction[i].index)); if (image->matte != MagickFalse) entropy_x.direction[i].opacity-=(density_x[x].direction[i].opacity* MagickLog10(density_x[x].direction[i].opacity)); entropy_y.direction[i].red-=(density_y[x].direction[i].red* MagickLog10(density_y[x].direction[i].red)); entropy_y.direction[i].green-=(density_y[x].direction[i].green* MagickLog10(density_y[x].direction[i].green)); entropy_y.direction[i].blue-=(density_y[x].direction[i].blue* MagickLog10(density_y[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_y.direction[i].index-=(density_y[x].direction[i].index* MagickLog10(density_y[x].direction[i].index)); if (image->matte != MagickFalse) entropy_y.direction[i].opacity-=(density_y[x].direction[i].opacity* MagickLog10(density_y[x].direction[i].opacity)); } /* Difference variance. */ channel_features[RedChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].red)- (variance.direction[i].red*variance.direction[i].red))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[GreenChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].green)- (variance.direction[i].green*variance.direction[i].green))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[BlueChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].blue)- (variance.direction[i].blue*variance.direction[i].blue))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->matte != MagickFalse) channel_features[OpacityChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].opacity)- (variance.direction[i].opacity*variance.direction[i].opacity))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].index)- (variance.direction[i].index*variance.direction[i].index))/ ((double) number_grays*number_grays*number_grays*number_grays); /* Information Measures of Correlation. */ channel_features[RedChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].red-entropy_xy1.direction[i].red)/ (entropy_x.direction[i].red > entropy_y.direction[i].red ? entropy_x.direction[i].red : entropy_y.direction[i].red); channel_features[GreenChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].green-entropy_xy1.direction[i].green)/ (entropy_x.direction[i].green > entropy_y.direction[i].green ? entropy_x.direction[i].green : entropy_y.direction[i].green); channel_features[BlueChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].blue-entropy_xy1.direction[i].blue)/ (entropy_x.direction[i].blue > entropy_y.direction[i].blue ? entropy_x.direction[i].blue : entropy_y.direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].index-entropy_xy1.direction[i].index)/ (entropy_x.direction[i].index > entropy_y.direction[i].index ? entropy_x.direction[i].index : entropy_y.direction[i].index); if (image->matte != MagickFalse) channel_features[OpacityChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].opacity-entropy_xy1.direction[i].opacity)/ (entropy_x.direction[i].opacity > entropy_y.direction[i].opacity ? entropy_x.direction[i].opacity : entropy_y.direction[i].opacity); channel_features[RedChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].red- entropy_xy.direction[i].red))))); channel_features[GreenChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].green- entropy_xy.direction[i].green))))); channel_features[BlueChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].blue- entropy_xy.direction[i].blue))))); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].index- entropy_xy.direction[i].index))))); if (image->matte != MagickFalse) channel_features[OpacityChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].opacity- entropy_xy.direction[i].opacity))))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t z; for (z=0; z < (ssize_t) number_grays; z++) { register ssize_t y; ChannelStatistics pixel; (void) memset(&pixel,0,sizeof(pixel)); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Contrast: amount of local variations present in an image. */ if (((y-x) == z) || ((x-y) == z)) { pixel.direction[i].red+=cooccurrence[x][y].direction[i].red; pixel.direction[i].green+=cooccurrence[x][y].direction[i].green; pixel.direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) pixel.direction[i].index+=cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) pixel.direction[i].opacity+= cooccurrence[x][y].direction[i].opacity; } /* Maximum Correlation Coefficient. */ Q[z][y].direction[i].red+=cooccurrence[z][x].direction[i].red* cooccurrence[y][x].direction[i].red/density_x[z].direction[i].red/ density_y[x].direction[i].red; Q[z][y].direction[i].green+=cooccurrence[z][x].direction[i].green* cooccurrence[y][x].direction[i].green/ density_x[z].direction[i].green/density_y[x].direction[i].red; Q[z][y].direction[i].blue+=cooccurrence[z][x].direction[i].blue* cooccurrence[y][x].direction[i].blue/density_x[z].direction[i].blue/ density_y[x].direction[i].blue; if (image->colorspace == CMYKColorspace) Q[z][y].direction[i].index+=cooccurrence[z][x].direction[i].index* cooccurrence[y][x].direction[i].index/ density_x[z].direction[i].index/density_y[x].direction[i].index; if (image->matte != MagickFalse) Q[z][y].direction[i].opacity+= cooccurrence[z][x].direction[i].opacity* cooccurrence[y][x].direction[i].opacity/ density_x[z].direction[i].opacity/ density_y[x].direction[i].opacity; } } channel_features[RedChannel].contrast[i]+=z*z*pixel.direction[i].red; channel_features[GreenChannel].contrast[i]+=z*z*pixel.direction[i].green; channel_features[BlueChannel].contrast[i]+=z*z*pixel.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackChannel].contrast[i]+=z*z* pixel.direction[i].index; if (image->matte != MagickFalse) channel_features[OpacityChannel].contrast[i]+=z*z* pixel.direction[i].opacity; } /* Maximum Correlation Coefficient. Future: return second largest eigenvalue of Q. */ channel_features[RedChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[GreenChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[BlueChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->matte != MagickFalse) channel_features[OpacityChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); } /* Relinquish resources. */ sum=(ChannelStatistics *) RelinquishMagickMemory(sum); for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); return(channel_features); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H o u g h L i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Use HoughLineImage() in conjunction with any binary edge extracted image (we % recommand Canny) to identify lines in the image. The algorithm accumulates % counts for every white pixel for every possible orientation (for angles from % 0 to 179 in 1 degree increments) and distance from the center of the image to % the corner (in 1 px increments) and stores the counts in an accumulator % matrix of angle vs distance. The size of the accumulator is 180x(diagonal/2).% Next it searches this space for peaks in counts and converts the locations % of the peaks to slope and intercept in the normal x,y input image space. Use % the slope/intercepts to find the endpoints clipped to the bounds of the % image. The lines are then drawn. The counts are a measure of the length of % the lines. % % The format of the HoughLineImage method is: % % Image *HoughLineImage(const Image *image,const size_t width, % const size_t height,const size_t threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find line pairs as local maxima in this neighborhood. % % o threshold: the line count threshold. % % o exception: return any errors or warnings in this structure. % */ 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)); } static Image *RenderHoughLines(const ImageInfo *image_info,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define BoundingBox "viewbox" DrawInfo *draw_info; Image *image; MagickBooleanType status; /* Open image. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->columns=columns; image->rows=rows; draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->affine.sx=image->x_resolution == 0.0 ? 1.0 : image->x_resolution/ DefaultResolution; draw_info->affine.sy=image->y_resolution == 0.0 ? 1.0 : image->y_resolution/ DefaultResolution; image->columns=(size_t) (draw_info->affine.sx*image->columns); image->rows=(size_t) (draw_info->affine.sy*image->rows); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Render drawing. */ if (GetBlobStreamData(image) == (unsigned char *) NULL) draw_info->primitive=FileToString(image->filename,~0UL,exception); else { draw_info->primitive=(char *) AcquireMagickMemory((size_t) GetBlobSize(image)+1); if (draw_info->primitive != (char *) NULL) { (void) memcpy(draw_info->primitive,GetBlobStreamData(image), (size_t) GetBlobSize(image)); draw_info->primitive[GetBlobSize(image)]='\0'; } } (void) DrawImage(image,draw_info); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } MagickExport Image *HoughLineImage(const Image *image,const size_t width, const size_t height,const size_t threshold,ExceptionInfo *exception) { #define HoughLineImageTag "HoughLine/Image" CacheView *image_view; char message[MaxTextExtent], path[MaxTextExtent]; const char *artifact; double hough_height; Image *lines_image = NULL; ImageInfo *image_info; int file; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *accumulator; PointInfo center; register ssize_t y; size_t accumulator_height, accumulator_width, line_count; /* Create the accumulator. */ assert(image != (const 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); accumulator_width=180; hough_height=((sqrt(2.0)*(double) (image->rows > image->columns ? image->rows : image->columns))/2.0); accumulator_height=(size_t) (2.0*hough_height); accumulator=AcquireMatrixInfo(accumulator_width,accumulator_height, sizeof(double),exception); if (accumulator == (MatrixInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); if (NullMatrix(accumulator) == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Populate the accumulator. */ status=MagickTrue; progress=0; center.x=(double) image->columns/2.0; center.y=(double) image->rows/2.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; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelIntensity(image,p) > (QuantumRange/2.0)) { register ssize_t i; for (i=0; i < 180; i++) { double count, radius; radius=(((double) x-center.x)*cos(DegreesToRadians((double) i)))+ (((double) y-center.y)*sin(DegreesToRadians((double) i))); (void) GetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); count++; (void) SetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); } } p++; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,HoughLineImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } /* Generate line segments from accumulator. */ file=AcquireUniqueFileResource(path); if (file == -1) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } (void) FormatLocaleString(message,MaxTextExtent, "# Hough line transform: %.20gx%.20g%+.20g\n",(double) width, (double) height,(double) threshold); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; (void) FormatLocaleString(message,MaxTextExtent,"viewbox 0 0 %.20g %.20g\n", (double) image->columns,(double) image->rows); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; (void) FormatLocaleString(message,MaxTextExtent, "# x1,y1 x2,y2 # count angle distance\n"); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; line_count=image->columns > image->rows ? image->columns/4 : image->rows/4; if (threshold != 0) line_count=threshold; for (y=0; y < (ssize_t) accumulator_height; y++) { register ssize_t x; for (x=0; x < (ssize_t) accumulator_width; x++) { double count; (void) GetMatrixElement(accumulator,x,y,&count); if (count >= (double) line_count) { double maxima; SegmentInfo line; ssize_t v; /* Is point a local maxima? */ maxima=count; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((u != 0) || (v !=0)) { (void) GetMatrixElement(accumulator,x+u,y+v,&count); if (count > maxima) { maxima=count; break; } } } if (u < (ssize_t) (width/2)) break; } (void) GetMatrixElement(accumulator,x,y,&count); if (maxima > count) continue; if ((x >= 45) && (x <= 135)) { /* y = (r-x cos(t))/sin(t) */ line.x1=0.0; line.y1=((double) (y-(accumulator_height/2.0))-((line.x1- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); line.x2=(double) image->columns; line.y2=((double) (y-(accumulator_height/2.0))-((line.x2- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); } else { /* x = (r-y cos(t))/sin(t) */ line.y1=0.0; line.x1=((double) (y-(accumulator_height/2.0))-((line.y1- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); line.y2=(double) image->rows; line.x2=((double) (y-(accumulator_height/2.0))-((line.y2- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); } (void) FormatLocaleString(message,MaxTextExtent, "line %g,%g %g,%g # %g %g %g\n",line.x1,line.y1,line.x2,line.y2, maxima,(double) x,(double) y); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; } } } (void) close(file); /* Render lines to image canvas. */ image_info=AcquireImageInfo(); image_info->background_color=image->background_color; (void) FormatLocaleString(image_info->filename,MaxTextExtent,"%s",path); artifact=GetImageArtifact(image,"background"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"background",artifact); artifact=GetImageArtifact(image,"fill"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"fill",artifact); artifact=GetImageArtifact(image,"stroke"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"stroke",artifact); artifact=GetImageArtifact(image,"strokewidth"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"strokewidth",artifact); lines_image=RenderHoughLines(image_info,image->columns,image->rows,exception); artifact=GetImageArtifact(image,"hough-lines:accumulator"); if ((lines_image != (Image *) NULL) && (IsMagickTrue(artifact) != MagickFalse)) { Image *accumulator_image; accumulator_image=MatrixToImage(accumulator,exception); if (accumulator_image != (Image *) NULL) AppendImageToList(&lines_image,accumulator_image); } /* Free resources. */ accumulator=DestroyMatrixInfo(accumulator); image_info=DestroyImageInfo(image_info); (void) RelinquishUniqueFileResource(path); return(GetFirstImageInList(lines_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e a n S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MeanShiftImage() delineate arbitrarily shaped clusters in the image. For % each pixel, it visits all the pixels in the neighborhood specified by % the window centered at the pixel and excludes those that are outside the % radius=(window-1)/2 surrounding the pixel. From those pixels, it finds those % that are within the specified color distance from the current mean, and % computes a new x,y centroid from those coordinates and a new mean. This new % x,y centroid is used as the center for a new window. This process iterates % until it converges and the final mean is replaces the (original window % center) pixel value. It repeats this process for the next pixel, etc., % until it processes all pixels in the image. Results are typically better with % colorspaces other than sRGB. We recommend YIQ, YUV or YCbCr. % % The format of the MeanShiftImage method is: % % Image *MeanShiftImage(const Image *image,const size_t width, % const size_t height,const double color_distance, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find pixels in this neighborhood. % % o color_distance: the color distance. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MeanShiftImage(const Image *image,const size_t width, const size_t height,const double color_distance,ExceptionInfo *exception) { #define MaxMeanShiftIterations 100 #define MeanShiftImageTag "MeanShift/Image" CacheView *image_view, *mean_view, *pixel_view; Image *mean_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (const 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); mean_image=CloneImage(image,0,0,MagickTrue,exception); if (mean_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(mean_image,DirectClass) == MagickFalse) { InheritException(exception,&mean_image->exception); mean_image=DestroyImage(mean_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); pixel_view=AcquireVirtualCacheView(image,exception); mean_view=AcquireAuthenticCacheView(mean_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,progress) \ magick_number_threads(mean_image,mean_image,mean_image->rows,1) #endif for (y=0; y < (ssize_t) mean_image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) mean_image->columns; x++) { MagickPixelPacket mean_pixel, previous_pixel; PointInfo mean_location, previous_location; register ssize_t i; GetMagickPixelPacket(image,&mean_pixel); SetMagickPixelPacket(image,p,indexes+x,&mean_pixel); mean_location.x=(double) x; mean_location.y=(double) y; for (i=0; i < MaxMeanShiftIterations; i++) { double distance, gamma; MagickPixelPacket sum_pixel; PointInfo sum_location; ssize_t count, v; sum_location.x=0.0; sum_location.y=0.0; GetMagickPixelPacket(image,&sum_pixel); previous_location=mean_location; previous_pixel=mean_pixel; count=0; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) { PixelPacket pixel; status=GetOneCacheViewVirtualPixel(pixel_view,(ssize_t) MagickRound(mean_location.x+u),(ssize_t) MagickRound( mean_location.y+v),&pixel,exception); distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); if (distance <= (color_distance*color_distance)) { sum_location.x+=mean_location.x+u; sum_location.y+=mean_location.y+v; sum_pixel.red+=pixel.red; sum_pixel.green+=pixel.green; sum_pixel.blue+=pixel.blue; sum_pixel.opacity+=pixel.opacity; count++; } } } } gamma=PerceptibleReciprocal(count); mean_location.x=gamma*sum_location.x; mean_location.y=gamma*sum_location.y; mean_pixel.red=gamma*sum_pixel.red; mean_pixel.green=gamma*sum_pixel.green; mean_pixel.blue=gamma*sum_pixel.blue; mean_pixel.opacity=gamma*sum_pixel.opacity; distance=(mean_location.x-previous_location.x)* (mean_location.x-previous_location.x)+ (mean_location.y-previous_location.y)* (mean_location.y-previous_location.y)+ 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); if (distance <= 3.0) break; } q->red=ClampToQuantum(mean_pixel.red); q->green=ClampToQuantum(mean_pixel.green); q->blue=ClampToQuantum(mean_pixel.blue); q->opacity=ClampToQuantum(mean_pixel.opacity); p++; q++; } if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } mean_view=DestroyCacheView(mean_view); pixel_view=DestroyCacheView(pixel_view); image_view=DestroyCacheView(image_view); return(mean_image); }
./CrossVul/dataset_final_sorted/CWE-369/c/good_1009_0
crossvul-cpp_data_bad_2768_0
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Implementation of the Transmission Control Protocol(TCP). * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Mark Evans, <evansmp@uhura.aston.ac.uk> * Corey Minyard <wf-rch!minyard@relay.EU.net> * Florian La Roche, <flla@stud.uni-sb.de> * Charles Hedrick, <hedrick@klinzhai.rutgers.edu> * Linus Torvalds, <torvalds@cs.helsinki.fi> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Matthew Dillon, <dillon@apollo.west.oic.com> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Jorge Cwik, <jorge@laser.satlink.net> * * Fixes: * Alan Cox : Numerous verify_area() calls * Alan Cox : Set the ACK bit on a reset * Alan Cox : Stopped it crashing if it closed while * sk->inuse=1 and was trying to connect * (tcp_err()). * Alan Cox : All icmp error handling was broken * pointers passed where wrong and the * socket was looked up backwards. Nobody * tested any icmp error code obviously. * Alan Cox : tcp_err() now handled properly. It * wakes people on errors. poll * behaves and the icmp error race * has gone by moving it into sock.c * Alan Cox : tcp_send_reset() fixed to work for * everything not just packets for * unknown sockets. * Alan Cox : tcp option processing. * Alan Cox : Reset tweaked (still not 100%) [Had * syn rule wrong] * Herp Rosmanith : More reset fixes * Alan Cox : No longer acks invalid rst frames. * Acking any kind of RST is right out. * Alan Cox : Sets an ignore me flag on an rst * receive otherwise odd bits of prattle * escape still * Alan Cox : Fixed another acking RST frame bug. * Should stop LAN workplace lockups. * Alan Cox : Some tidyups using the new skb list * facilities * Alan Cox : sk->keepopen now seems to work * Alan Cox : Pulls options out correctly on accepts * Alan Cox : Fixed assorted sk->rqueue->next errors * Alan Cox : PSH doesn't end a TCP read. Switched a * bit to skb ops. * Alan Cox : Tidied tcp_data to avoid a potential * nasty. * Alan Cox : Added some better commenting, as the * tcp is hard to follow * Alan Cox : Removed incorrect check for 20 * psh * Michael O'Reilly : ack < copied bug fix. * Johannes Stille : Misc tcp fixes (not all in yet). * Alan Cox : FIN with no memory -> CRASH * Alan Cox : Added socket option proto entries. * Also added awareness of them to accept. * Alan Cox : Added TCP options (SOL_TCP) * Alan Cox : Switched wakeup calls to callbacks, * so the kernel can layer network * sockets. * Alan Cox : Use ip_tos/ip_ttl settings. * Alan Cox : Handle FIN (more) properly (we hope). * Alan Cox : RST frames sent on unsynchronised * state ack error. * Alan Cox : Put in missing check for SYN bit. * Alan Cox : Added tcp_select_window() aka NET2E * window non shrink trick. * Alan Cox : Added a couple of small NET2E timer * fixes * Charles Hedrick : TCP fixes * Toomas Tamm : TCP window fixes * Alan Cox : Small URG fix to rlogin ^C ack fight * Charles Hedrick : Rewrote most of it to actually work * Linus : Rewrote tcp_read() and URG handling * completely * Gerhard Koerting: Fixed some missing timer handling * Matthew Dillon : Reworked TCP machine states as per RFC * Gerhard Koerting: PC/TCP workarounds * Adam Caldwell : Assorted timer/timing errors * Matthew Dillon : Fixed another RST bug * Alan Cox : Move to kernel side addressing changes. * Alan Cox : Beginning work on TCP fastpathing * (not yet usable) * Arnt Gulbrandsen: Turbocharged tcp_check() routine. * Alan Cox : TCP fast path debugging * Alan Cox : Window clamping * Michael Riepe : Bug in tcp_check() * Matt Dillon : More TCP improvements and RST bug fixes * Matt Dillon : Yet more small nasties remove from the * TCP code (Be very nice to this man if * tcp finally works 100%) 8) * Alan Cox : BSD accept semantics. * Alan Cox : Reset on closedown bug. * Peter De Schrijver : ENOTCONN check missing in tcp_sendto(). * Michael Pall : Handle poll() after URG properly in * all cases. * Michael Pall : Undo the last fix in tcp_read_urg() * (multi URG PUSH broke rlogin). * Michael Pall : Fix the multi URG PUSH problem in * tcp_readable(), poll() after URG * works now. * Michael Pall : recv(...,MSG_OOB) never blocks in the * BSD api. * Alan Cox : Changed the semantics of sk->socket to * fix a race and a signal problem with * accept() and async I/O. * Alan Cox : Relaxed the rules on tcp_sendto(). * Yury Shevchuk : Really fixed accept() blocking problem. * Craig I. Hagan : Allow for BSD compatible TIME_WAIT for * clients/servers which listen in on * fixed ports. * Alan Cox : Cleaned the above up and shrank it to * a sensible code size. * Alan Cox : Self connect lockup fix. * Alan Cox : No connect to multicast. * Ross Biro : Close unaccepted children on master * socket close. * Alan Cox : Reset tracing code. * Alan Cox : Spurious resets on shutdown. * Alan Cox : Giant 15 minute/60 second timer error * Alan Cox : Small whoops in polling before an * accept. * Alan Cox : Kept the state trace facility since * it's handy for debugging. * Alan Cox : More reset handler fixes. * Alan Cox : Started rewriting the code based on * the RFC's for other useful protocol * references see: Comer, KA9Q NOS, and * for a reference on the difference * between specifications and how BSD * works see the 4.4lite source. * A.N.Kuznetsov : Don't time wait on completion of tidy * close. * Linus Torvalds : Fin/Shutdown & copied_seq changes. * Linus Torvalds : Fixed BSD port reuse to work first syn * Alan Cox : Reimplemented timers as per the RFC * and using multiple timers for sanity. * Alan Cox : Small bug fixes, and a lot of new * comments. * Alan Cox : Fixed dual reader crash by locking * the buffers (much like datagram.c) * Alan Cox : Fixed stuck sockets in probe. A probe * now gets fed up of retrying without * (even a no space) answer. * Alan Cox : Extracted closing code better * Alan Cox : Fixed the closing state machine to * resemble the RFC. * Alan Cox : More 'per spec' fixes. * Jorge Cwik : Even faster checksumming. * Alan Cox : tcp_data() doesn't ack illegal PSH * only frames. At least one pc tcp stack * generates them. * Alan Cox : Cache last socket. * Alan Cox : Per route irtt. * Matt Day : poll()->select() match BSD precisely on error * Alan Cox : New buffers * Marc Tamsky : Various sk->prot->retransmits and * sk->retransmits misupdating fixed. * Fixed tcp_write_timeout: stuck close, * and TCP syn retries gets used now. * Mark Yarvis : In tcp_read_wakeup(), don't send an * ack if state is TCP_CLOSED. * Alan Cox : Look up device on a retransmit - routes may * change. Doesn't yet cope with MSS shrink right * but it's a start! * Marc Tamsky : Closing in closing fixes. * Mike Shaver : RFC1122 verifications. * Alan Cox : rcv_saddr errors. * Alan Cox : Block double connect(). * Alan Cox : Small hooks for enSKIP. * Alexey Kuznetsov: Path MTU discovery. * Alan Cox : Support soft errors. * Alan Cox : Fix MTU discovery pathological case * when the remote claims no mtu! * Marc Tamsky : TCP_CLOSE fix. * Colin (G3TNE) : Send a reset on syn ack replies in * window but wrong (fixes NT lpd problems) * Pedro Roque : Better TCP window handling, delayed ack. * Joerg Reuter : No modification of locked buffers in * tcp_do_retransmit() * Eric Schenk : Changed receiver side silly window * avoidance algorithm to BSD style * algorithm. This doubles throughput * against machines running Solaris, * and seems to result in general * improvement. * Stefan Magdalinski : adjusted tcp_readable() to fix FIONREAD * Willy Konynenberg : Transparent proxying support. * Mike McLagan : Routing by source * Keith Owens : Do proper merging with partial SKB's in * tcp_do_sendmsg to avoid burstiness. * Eric Schenk : Fix fast close down bug with * shutdown() followed by close(). * Andi Kleen : Make poll agree with SIGIO * Salvatore Sanfilippo : Support SO_LINGER with linger == 1 and * lingertime == 0 (RFC 793 ABORT Call) * Hirokazu Takahashi : Use copy_from_user() instead of * csum_and_copy_from_user() if possible. * * 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. * * Description of States: * * TCP_SYN_SENT sent a connection request, waiting for ack * * TCP_SYN_RECV received a connection request, sent ack, * waiting for final ack in three-way handshake. * * TCP_ESTABLISHED connection established * * TCP_FIN_WAIT1 our side has shutdown, waiting to complete * transmission of remaining buffered data * * TCP_FIN_WAIT2 all buffered data sent, waiting for remote * to shutdown * * TCP_CLOSING both sides have shutdown but we still have * data we have to finish sending * * TCP_TIME_WAIT timeout to catch resent junk before entering * closed, can only be entered from FIN_WAIT2 * or CLOSING. Required because the other end * may not have gotten our last ACK causing it * to retransmit the data packet (which we ignore) * * TCP_CLOSE_WAIT remote side has shutdown and is waiting for * us to finish writing our data and to shutdown * (we have to close() to move on to LAST_ACK) * * TCP_LAST_ACK out side has shutdown after remote has * shutdown. There may still be data in our * buffer that we have to finish sending * * TCP_CLOSE socket is finished */ #define pr_fmt(fmt) "TCP: " fmt #include <crypto/hash.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/poll.h> #include <linux/inet_diag.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/skbuff.h> #include <linux/scatterlist.h> #include <linux/splice.h> #include <linux/net.h> #include <linux/socket.h> #include <linux/random.h> #include <linux/bootmem.h> #include <linux/highmem.h> #include <linux/swap.h> #include <linux/cache.h> #include <linux/err.h> #include <linux/time.h> #include <linux/slab.h> #include <net/icmp.h> #include <net/inet_common.h> #include <net/tcp.h> #include <net/xfrm.h> #include <net/ip.h> #include <net/sock.h> #include <linux/uaccess.h> #include <asm/ioctls.h> #include <net/busy_poll.h> int sysctl_tcp_min_tso_segs __read_mostly = 2; int sysctl_tcp_autocorking __read_mostly = 1; struct percpu_counter tcp_orphan_count; EXPORT_SYMBOL_GPL(tcp_orphan_count); long sysctl_tcp_mem[3] __read_mostly; int sysctl_tcp_wmem[3] __read_mostly; int sysctl_tcp_rmem[3] __read_mostly; EXPORT_SYMBOL(sysctl_tcp_mem); EXPORT_SYMBOL(sysctl_tcp_rmem); EXPORT_SYMBOL(sysctl_tcp_wmem); atomic_long_t tcp_memory_allocated; /* Current allocated memory. */ EXPORT_SYMBOL(tcp_memory_allocated); /* * Current number of TCP sockets. */ struct percpu_counter tcp_sockets_allocated; EXPORT_SYMBOL(tcp_sockets_allocated); /* * TCP splice context */ struct tcp_splice_state { struct pipe_inode_info *pipe; size_t len; unsigned int flags; }; /* * Pressure flag: try to collapse. * Technical note: it is used by multiple contexts non atomically. * All the __sk_mem_schedule() is of this nature: accounting * is strict, actions are advisory and have some latency. */ int tcp_memory_pressure __read_mostly; EXPORT_SYMBOL(tcp_memory_pressure); void tcp_enter_memory_pressure(struct sock *sk) { if (!tcp_memory_pressure) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES); tcp_memory_pressure = 1; } } EXPORT_SYMBOL(tcp_enter_memory_pressure); /* Convert seconds to retransmits based on initial and max timeout */ static u8 secs_to_retrans(int seconds, int timeout, int rto_max) { u8 res = 0; if (seconds > 0) { int period = timeout; res = 1; while (seconds > period && res < 255) { res++; timeout <<= 1; if (timeout > rto_max) timeout = rto_max; period += timeout; } } return res; } /* Convert retransmits to seconds based on initial and max timeout */ static int retrans_to_secs(u8 retrans, int timeout, int rto_max) { int period = 0; if (retrans > 0) { period = timeout; while (--retrans) { timeout <<= 1; if (timeout > rto_max) timeout = rto_max; period += timeout; } } return period; } /* Address-family independent initialization for a tcp_sock. * * NOTE: A lot of things set to zero explicitly by call to * sk_alloc() so need not be done here. */ void tcp_init_sock(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); tp->out_of_order_queue = RB_ROOT; tcp_init_xmit_timers(sk); tcp_prequeue_init(tp); INIT_LIST_HEAD(&tp->tsq_node); icsk->icsk_rto = TCP_TIMEOUT_INIT; tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT); minmax_reset(&tp->rtt_min, tcp_time_stamp, ~0U); /* So many TCP implementations out there (incorrectly) count the * initial SYN frame in their delayed-ACK and congestion control * algorithms that we must have the following bandaid to talk * efficiently to them. -DaveM */ tp->snd_cwnd = TCP_INIT_CWND; /* There's a bubble in the pipe until at least the first ACK. */ tp->app_limited = ~0U; /* See draft-stevens-tcpca-spec-01 for discussion of the * initialization of these values. */ tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; tp->snd_cwnd_clamp = ~0; tp->mss_cache = TCP_MSS_DEFAULT; tp->reordering = sock_net(sk)->ipv4.sysctl_tcp_reordering; tcp_assign_congestion_control(sk); tp->tsoffset = 0; sk->sk_state = TCP_CLOSE; sk->sk_write_space = sk_stream_write_space; sock_set_flag(sk, SOCK_USE_WRITE_QUEUE); icsk->icsk_sync_mss = tcp_sync_mss; sk->sk_sndbuf = sysctl_tcp_wmem[1]; sk->sk_rcvbuf = sysctl_tcp_rmem[1]; sk_sockets_allocated_inc(sk); } EXPORT_SYMBOL(tcp_init_sock); static void tcp_tx_timestamp(struct sock *sk, u16 tsflags, struct sk_buff *skb) { if (tsflags && skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); sock_tx_timestamp(sk, tsflags, &shinfo->tx_flags); if (tsflags & SOF_TIMESTAMPING_TX_ACK) tcb->txstamp_ack = 1; if (tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK) shinfo->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1; } } /* * Wait for a TCP event. * * Note that we don't need to lock the socket, as the upper poll layers * take care of normal races (between the test and the event) and we don't * go look at any of the socket buffers directly. */ unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait) { unsigned int mask; struct sock *sk = sock->sk; const struct tcp_sock *tp = tcp_sk(sk); int state; sock_rps_record_flow(sk); sock_poll_wait(file, sk_sleep(sk), wait); state = sk_state_load(sk); if (state == TCP_LISTEN) return inet_csk_listen_poll(sk); /* Socket is not locked. We are protected from async events * by poll logic and correct handling of state changes * made by other threads is impossible in any case. */ mask = 0; /* * POLLHUP is certainly not done right. But poll() doesn't * have a notion of HUP in just one direction, and for a * socket the read side is more interesting. * * Some poll() documentation says that POLLHUP is incompatible * with the POLLOUT/POLLWR flags, so somebody should check this * all. But careful, it tends to be safer to return too many * bits than too few, and you can easily break real applications * if you don't tell them that something has hung up! * * Check-me. * * Check number 1. POLLHUP is _UNMASKABLE_ event (see UNIX98 and * our fs/select.c). It means that after we received EOF, * poll always returns immediately, making impossible poll() on write() * in state CLOSE_WAIT. One solution is evident --- to set POLLHUP * if and only if shutdown has been made in both directions. * Actually, it is interesting to look how Solaris and DUX * solve this dilemma. I would prefer, if POLLHUP were maskable, * then we could set it on SND_SHUTDOWN. BTW examples given * in Stevens' books assume exactly this behaviour, it explains * why POLLHUP is incompatible with POLLOUT. --ANK * * NOTE. Check for TCP_CLOSE is added. The goal is to prevent * blocking on fresh not-connected or disconnected socket. --ANK */ if (sk->sk_shutdown == SHUTDOWN_MASK || state == TCP_CLOSE) mask |= POLLHUP; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLIN | POLLRDNORM | POLLRDHUP; /* Connected or passive Fast Open socket? */ if (state != TCP_SYN_SENT && (state != TCP_SYN_RECV || tp->fastopen_rsk)) { int target = sock_rcvlowat(sk, 0, INT_MAX); if (tp->urg_seq == tp->copied_seq && !sock_flag(sk, SOCK_URGINLINE) && tp->urg_data) target++; if (tp->rcv_nxt - tp->copied_seq >= target) mask |= POLLIN | POLLRDNORM; if (!(sk->sk_shutdown & SEND_SHUTDOWN)) { if (sk_stream_is_writeable(sk)) { mask |= POLLOUT | POLLWRNORM; } else { /* send SIGIO later */ sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); /* Race breaker. If space is freed after * wspace test but before the flags are set, * IO signal will be lost. Memory barrier * pairs with the input side. */ smp_mb__after_atomic(); if (sk_stream_is_writeable(sk)) mask |= POLLOUT | POLLWRNORM; } } else mask |= POLLOUT | POLLWRNORM; if (tp->urg_data & TCP_URG_VALID) mask |= POLLPRI; } else if (state == TCP_SYN_SENT && inet_sk(sk)->defer_connect) { /* Active TCP fastopen socket with defer_connect * Return POLLOUT so application can call write() * in order for kernel to generate SYN+data */ mask |= POLLOUT | POLLWRNORM; } /* This barrier is coupled with smp_wmb() in tcp_reset() */ smp_rmb(); if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR; return mask; } EXPORT_SYMBOL(tcp_poll); int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg) { struct tcp_sock *tp = tcp_sk(sk); int answ; bool slow; switch (cmd) { case SIOCINQ: if (sk->sk_state == TCP_LISTEN) return -EINVAL; slow = lock_sock_fast(sk); answ = tcp_inq(sk); unlock_sock_fast(sk, slow); break; case SIOCATMARK: answ = tp->urg_data && tp->urg_seq == tp->copied_seq; break; case SIOCOUTQ: if (sk->sk_state == TCP_LISTEN) return -EINVAL; if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) answ = 0; else answ = tp->write_seq - tp->snd_una; break; case SIOCOUTQNSD: if (sk->sk_state == TCP_LISTEN) return -EINVAL; if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) answ = 0; else answ = tp->write_seq - tp->snd_nxt; break; default: return -ENOIOCTLCMD; } return put_user(answ, (int __user *)arg); } EXPORT_SYMBOL(tcp_ioctl); static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb) { TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH; tp->pushed_seq = tp->write_seq; } static inline bool forced_push(const struct tcp_sock *tp) { return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1)); } static void skb_entail(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); skb->csum = 0; tcb->seq = tcb->end_seq = tp->write_seq; tcb->tcp_flags = TCPHDR_ACK; tcb->sacked = 0; __skb_header_release(skb); tcp_add_write_queue_tail(sk, skb); sk->sk_wmem_queued += skb->truesize; sk_mem_charge(sk, skb->truesize); if (tp->nonagle & TCP_NAGLE_PUSH) tp->nonagle &= ~TCP_NAGLE_PUSH; tcp_slow_start_after_idle_check(sk); } static inline void tcp_mark_urg(struct tcp_sock *tp, int flags) { if (flags & MSG_OOB) tp->snd_up = tp->write_seq; } /* If a not yet filled skb is pushed, do not send it if * we have data packets in Qdisc or NIC queues : * Because TX completion will happen shortly, it gives a chance * to coalesce future sendmsg() payload into this skb, without * need for a timer, and with no latency trade off. * As packets containing data payload have a bigger truesize * than pure acks (dataless) packets, the last checks prevent * autocorking if we only have an ACK in Qdisc/NIC queues, * or if TX completion was delayed after we processed ACK packet. */ static bool tcp_should_autocork(struct sock *sk, struct sk_buff *skb, int size_goal) { return skb->len < size_goal && sysctl_tcp_autocorking && skb != tcp_write_queue_head(sk) && atomic_read(&sk->sk_wmem_alloc) > skb->truesize; } static void tcp_push(struct sock *sk, int flags, int mss_now, int nonagle, int size_goal) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; if (!tcp_send_head(sk)) return; skb = tcp_write_queue_tail(sk); if (!(flags & MSG_MORE) || forced_push(tp)) tcp_mark_push(tp, skb); tcp_mark_urg(tp, flags); if (tcp_should_autocork(sk, skb, size_goal)) { /* avoid atomic op if TSQ_THROTTLED bit is already set */ if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING); set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags); } /* It is possible TX completion already happened * before we set TSQ_THROTTLED. */ if (atomic_read(&sk->sk_wmem_alloc) > skb->truesize) return; } if (flags & MSG_MORE) nonagle = TCP_NAGLE_CORK; __tcp_push_pending_frames(sk, mss_now, nonagle); } static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb, unsigned int offset, size_t len) { struct tcp_splice_state *tss = rd_desc->arg.data; int ret; ret = skb_splice_bits(skb, skb->sk, offset, tss->pipe, min(rd_desc->count, len), tss->flags); if (ret > 0) rd_desc->count -= ret; return ret; } static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss) { /* Store TCP splice context information in read_descriptor_t. */ read_descriptor_t rd_desc = { .arg.data = tss, .count = tss->len, }; return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv); } /** * tcp_splice_read - splice data from TCP socket to a pipe * @sock: socket to splice from * @ppos: position (not valid) * @pipe: pipe to splice to * @len: number of bytes to splice * @flags: splice modifier flags * * Description: * Will read pages from given socket and fill them into a pipe. * **/ ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct sock *sk = sock->sk; struct tcp_splice_state tss = { .pipe = pipe, .len = len, .flags = flags, }; long timeo; ssize_t spliced; int ret; sock_rps_record_flow(sk); /* * We can't seek on a socket input */ if (unlikely(*ppos)) return -ESPIPE; ret = spliced = 0; lock_sock(sk); timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK); while (tss.len) { ret = __tcp_splice_read(sk, &tss); if (ret < 0) break; else if (!ret) { if (spliced) break; if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { ret = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_state == TCP_CLOSE) { /* * This occurs when user tries to read * from never connected socket. */ if (!sock_flag(sk, SOCK_DONE)) ret = -ENOTCONN; break; } if (!timeo) { ret = -EAGAIN; break; } /* if __tcp_splice_read() got nothing while we have * an skb in receive queue, we do not want to loop. * This might happen with URG data. */ if (!skb_queue_empty(&sk->sk_receive_queue)) break; sk_wait_data(sk, &timeo, NULL); if (signal_pending(current)) { ret = sock_intr_errno(timeo); break; } continue; } tss.len -= ret; spliced += ret; if (!timeo) break; release_sock(sk); lock_sock(sk); if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || signal_pending(current)) break; } release_sock(sk); if (spliced) return spliced; return ret; } EXPORT_SYMBOL(tcp_splice_read); struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp, bool force_schedule) { struct sk_buff *skb; /* The TCP header must be at least 32-bit aligned. */ size = ALIGN(size, 4); if (unlikely(tcp_under_memory_pressure(sk))) sk_mem_reclaim_partial(sk); skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp); if (likely(skb)) { bool mem_scheduled; if (force_schedule) { mem_scheduled = true; sk_forced_mem_schedule(sk, skb->truesize); } else { mem_scheduled = sk_wmem_schedule(sk, skb->truesize); } if (likely(mem_scheduled)) { skb_reserve(skb, sk->sk_prot->max_header); /* * Make sure that we have exactly size bytes * available to the caller, no more, no less. */ skb->reserved_tailroom = skb->end - skb->tail - size; return skb; } __kfree_skb(skb); } else { sk->sk_prot->enter_memory_pressure(sk); sk_stream_moderate_sndbuf(sk); } return NULL; } static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now, int large_allowed) { struct tcp_sock *tp = tcp_sk(sk); u32 new_size_goal, size_goal; if (!large_allowed || !sk_can_gso(sk)) return mss_now; /* Note : tcp_tso_autosize() will eventually split this later */ new_size_goal = sk->sk_gso_max_size - 1 - MAX_TCP_HEADER; new_size_goal = tcp_bound_to_half_wnd(tp, new_size_goal); /* We try hard to avoid divides here */ size_goal = tp->gso_segs * mss_now; if (unlikely(new_size_goal < size_goal || new_size_goal >= size_goal + mss_now)) { tp->gso_segs = min_t(u16, new_size_goal / mss_now, sk->sk_gso_max_segs); size_goal = tp->gso_segs * mss_now; } return max(size_goal, mss_now); } static int tcp_send_mss(struct sock *sk, int *size_goal, int flags) { int mss_now; mss_now = tcp_current_mss(sk); *size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB)); return mss_now; } static ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset, size_t size, int flags) { struct tcp_sock *tp = tcp_sk(sk); int mss_now, size_goal; int err; ssize_t copied; long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT); /* Wait for a connection to finish. One exception is TCP Fast Open * (passive side) where data is allowed to be sent before a connection * is fully established. */ if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) && !tcp_passive_fastopen(sk)) { err = sk_stream_wait_connect(sk, &timeo); if (err != 0) goto out_err; } sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); mss_now = tcp_send_mss(sk, &size_goal, flags); copied = 0; err = -EPIPE; if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) goto out_err; while (size > 0) { struct sk_buff *skb = tcp_write_queue_tail(sk); int copy, i; bool can_coalesce; if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0 || !tcp_skb_can_collapse_to(skb)) { new_segment: if (!sk_stream_memory_free(sk)) goto wait_for_sndbuf; skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation, skb_queue_empty(&sk->sk_write_queue)); if (!skb) goto wait_for_memory; skb_entail(sk, skb); copy = size_goal; } if (copy > size) copy = size; i = skb_shinfo(skb)->nr_frags; can_coalesce = skb_can_coalesce(skb, i, page, offset); if (!can_coalesce && i >= sysctl_max_skb_frags) { tcp_mark_push(tp, skb); goto new_segment; } if (!sk_wmem_schedule(sk, copy)) goto wait_for_memory; if (can_coalesce) { skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); } else { get_page(page); skb_fill_page_desc(skb, i, page, offset, copy); } skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG; skb->len += copy; skb->data_len += copy; skb->truesize += copy; sk->sk_wmem_queued += copy; sk_mem_charge(sk, copy); skb->ip_summed = CHECKSUM_PARTIAL; tp->write_seq += copy; TCP_SKB_CB(skb)->end_seq += copy; tcp_skb_pcount_set(skb, 0); if (!copied) TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH; copied += copy; offset += copy; size -= copy; if (!size) goto out; if (skb->len < size_goal || (flags & MSG_OOB)) continue; if (forced_push(tp)) { tcp_mark_push(tp, skb); __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH); } else if (skb == tcp_send_head(sk)) tcp_push_one(sk, mss_now); continue; wait_for_sndbuf: set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); wait_for_memory: tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH, size_goal); err = sk_stream_wait_memory(sk, &timeo); if (err != 0) goto do_error; mss_now = tcp_send_mss(sk, &size_goal, flags); } out: if (copied) { tcp_tx_timestamp(sk, sk->sk_tsflags, tcp_write_queue_tail(sk)); if (!(flags & MSG_SENDPAGE_NOTLAST)) tcp_push(sk, flags, mss_now, tp->nonagle, size_goal); } return copied; do_error: if (copied) goto out; out_err: /* make sure we wake any epoll edge trigger waiter */ if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 && err == -EAGAIN)) { sk->sk_write_space(sk); tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED); } return sk_stream_error(sk, flags, err); } int tcp_sendpage(struct sock *sk, struct page *page, int offset, size_t size, int flags) { ssize_t res; if (!(sk->sk_route_caps & NETIF_F_SG) || !sk_check_csum_caps(sk)) return sock_no_sendpage(sk->sk_socket, page, offset, size, flags); lock_sock(sk); tcp_rate_check_app_limited(sk); /* is sending application-limited? */ res = do_tcp_sendpages(sk, page, offset, size, flags); release_sock(sk); return res; } EXPORT_SYMBOL(tcp_sendpage); /* Do not bother using a page frag for very small frames. * But use this heuristic only for the first skb in write queue. * * Having no payload in skb->head allows better SACK shifting * in tcp_shift_skb_data(), reducing sack/rack overhead, because * write queue has less skbs. * Each skb can hold up to MAX_SKB_FRAGS * 32Kbytes, or ~0.5 MB. * This also speeds up tso_fragment(), since it wont fallback * to tcp_fragment(). */ static int linear_payload_sz(bool first_skb) { if (first_skb) return SKB_WITH_OVERHEAD(2048 - MAX_TCP_HEADER); return 0; } static int select_size(const struct sock *sk, bool sg, bool first_skb) { const struct tcp_sock *tp = tcp_sk(sk); int tmp = tp->mss_cache; if (sg) { if (sk_can_gso(sk)) { tmp = linear_payload_sz(first_skb); } else { int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER); if (tmp >= pgbreak && tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE) tmp = pgbreak; } } return tmp; } void tcp_free_fastopen_req(struct tcp_sock *tp) { if (tp->fastopen_req) { kfree(tp->fastopen_req); tp->fastopen_req = NULL; } } static int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, int *copied, size_t size) { struct tcp_sock *tp = tcp_sk(sk); struct inet_sock *inet = inet_sk(sk); int err, flags; if (!(sysctl_tcp_fastopen & TFO_CLIENT_ENABLE)) return -EOPNOTSUPP; if (tp->fastopen_req) return -EALREADY; /* Another Fast Open is in progress */ tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request), sk->sk_allocation); if (unlikely(!tp->fastopen_req)) return -ENOBUFS; tp->fastopen_req->data = msg; tp->fastopen_req->size = size; if (inet->defer_connect) { err = tcp_connect(sk); /* Same failure procedure as in tcp_v4/6_connect */ if (err) { tcp_set_state(sk, TCP_CLOSE); inet->inet_dport = 0; sk->sk_route_caps = 0; } } flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0; err = __inet_stream_connect(sk->sk_socket, msg->msg_name, msg->msg_namelen, flags, 1); /* fastopen_req could already be freed in __inet_stream_connect * if the connection times out or gets rst */ if (tp->fastopen_req) { *copied = tp->fastopen_req->copied; tcp_free_fastopen_req(tp); inet->defer_connect = 0; } return err; } int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; struct sockcm_cookie sockc; int flags, err, copied = 0; int mss_now = 0, size_goal, copied_syn = 0; bool process_backlog = false; bool sg; long timeo; lock_sock(sk); flags = msg->msg_flags; if (unlikely(flags & MSG_FASTOPEN || inet_sk(sk)->defer_connect)) { err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size); if (err == -EINPROGRESS && copied_syn > 0) goto out; else if (err) goto out_err; } timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT); tcp_rate_check_app_limited(sk); /* is sending application-limited? */ /* Wait for a connection to finish. One exception is TCP Fast Open * (passive side) where data is allowed to be sent before a connection * is fully established. */ if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) && !tcp_passive_fastopen(sk)) { err = sk_stream_wait_connect(sk, &timeo); if (err != 0) goto do_error; } if (unlikely(tp->repair)) { if (tp->repair_queue == TCP_RECV_QUEUE) { copied = tcp_send_rcvq(sk, msg, size); goto out_nopush; } err = -EINVAL; if (tp->repair_queue == TCP_NO_QUEUE) goto out_err; /* 'common' sending to sendq */ } sockc.tsflags = sk->sk_tsflags; if (msg->msg_controllen) { err = sock_cmsg_send(sk, msg, &sockc); if (unlikely(err)) { err = -EINVAL; goto out_err; } } /* This should be in poll */ sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); /* Ok commence sending. */ copied = 0; restart: mss_now = tcp_send_mss(sk, &size_goal, flags); err = -EPIPE; if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) goto do_error; sg = !!(sk->sk_route_caps & NETIF_F_SG); while (msg_data_left(msg)) { int copy = 0; int max = size_goal; skb = tcp_write_queue_tail(sk); if (tcp_send_head(sk)) { if (skb->ip_summed == CHECKSUM_NONE) max = mss_now; copy = max - skb->len; } if (copy <= 0 || !tcp_skb_can_collapse_to(skb)) { bool first_skb; new_segment: /* Allocate new segment. If the interface is SG, * allocate skb fitting to single page. */ if (!sk_stream_memory_free(sk)) goto wait_for_sndbuf; if (process_backlog && sk_flush_backlog(sk)) { process_backlog = false; goto restart; } first_skb = skb_queue_empty(&sk->sk_write_queue); skb = sk_stream_alloc_skb(sk, select_size(sk, sg, first_skb), sk->sk_allocation, first_skb); if (!skb) goto wait_for_memory; process_backlog = true; /* * Check whether we can use HW checksum. */ if (sk_check_csum_caps(sk)) skb->ip_summed = CHECKSUM_PARTIAL; skb_entail(sk, skb); copy = size_goal; max = size_goal; /* All packets are restored as if they have * already been sent. skb_mstamp isn't set to * avoid wrong rtt estimation. */ if (tp->repair) TCP_SKB_CB(skb)->sacked |= TCPCB_REPAIRED; } /* Try to append data to the end of skb. */ if (copy > msg_data_left(msg)) copy = msg_data_left(msg); /* Where to copy to? */ if (skb_availroom(skb) > 0) { /* We have some space in skb head. Superb! */ copy = min_t(int, copy, skb_availroom(skb)); err = skb_add_data_nocache(sk, skb, &msg->msg_iter, copy); if (err) goto do_fault; } else { bool merge = true; int i = skb_shinfo(skb)->nr_frags; struct page_frag *pfrag = sk_page_frag(sk); if (!sk_page_frag_refill(sk, pfrag)) goto wait_for_memory; if (!skb_can_coalesce(skb, i, pfrag->page, pfrag->offset)) { if (i >= sysctl_max_skb_frags || !sg) { tcp_mark_push(tp, skb); goto new_segment; } merge = false; } copy = min_t(int, copy, pfrag->size - pfrag->offset); if (!sk_wmem_schedule(sk, copy)) goto wait_for_memory; err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb, pfrag->page, pfrag->offset, copy); if (err) goto do_error; /* Update the skb. */ if (merge) { skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); } else { skb_fill_page_desc(skb, i, pfrag->page, pfrag->offset, copy); page_ref_inc(pfrag->page); } pfrag->offset += copy; } if (!copied) TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH; tp->write_seq += copy; TCP_SKB_CB(skb)->end_seq += copy; tcp_skb_pcount_set(skb, 0); copied += copy; if (!msg_data_left(msg)) { if (unlikely(flags & MSG_EOR)) TCP_SKB_CB(skb)->eor = 1; goto out; } if (skb->len < max || (flags & MSG_OOB) || unlikely(tp->repair)) continue; if (forced_push(tp)) { tcp_mark_push(tp, skb); __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH); } else if (skb == tcp_send_head(sk)) tcp_push_one(sk, mss_now); continue; wait_for_sndbuf: set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); wait_for_memory: if (copied) tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH, size_goal); err = sk_stream_wait_memory(sk, &timeo); if (err != 0) goto do_error; mss_now = tcp_send_mss(sk, &size_goal, flags); } out: if (copied) { tcp_tx_timestamp(sk, sockc.tsflags, tcp_write_queue_tail(sk)); tcp_push(sk, flags, mss_now, tp->nonagle, size_goal); } out_nopush: release_sock(sk); return copied + copied_syn; do_fault: if (!skb->len) { tcp_unlink_write_queue(skb, sk); /* It is the one place in all of TCP, except connection * reset, where we can be unlinking the send_head. */ tcp_check_send_head(sk, skb); sk_wmem_free_skb(sk, skb); } do_error: if (copied + copied_syn) goto out; out_err: err = sk_stream_error(sk, flags, err); /* make sure we wake any epoll edge trigger waiter */ if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 && err == -EAGAIN)) { sk->sk_write_space(sk); tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED); } release_sock(sk); return err; } EXPORT_SYMBOL(tcp_sendmsg); /* * Handle reading urgent data. BSD has very simple semantics for * this, no blocking and very strange errors 8) */ static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags) { struct tcp_sock *tp = tcp_sk(sk); /* No URG data to read. */ if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data || tp->urg_data == TCP_URG_READ) return -EINVAL; /* Yes this is right ! */ if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE)) return -ENOTCONN; if (tp->urg_data & TCP_URG_VALID) { int err = 0; char c = tp->urg_data; if (!(flags & MSG_PEEK)) tp->urg_data = TCP_URG_READ; /* Read urgent data. */ msg->msg_flags |= MSG_OOB; if (len > 0) { if (!(flags & MSG_TRUNC)) err = memcpy_to_msg(msg, &c, 1); len = 1; } else msg->msg_flags |= MSG_TRUNC; return err ? -EFAULT : len; } if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN)) return 0; /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and * the available implementations agree in this case: * this call should never block, independent of the * blocking state of the socket. * Mike <pall@rz.uni-karlsruhe.de> */ return -EAGAIN; } static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len) { struct sk_buff *skb; int copied = 0, err = 0; /* XXX -- need to support SO_PEEK_OFF */ skb_queue_walk(&sk->sk_write_queue, skb) { err = skb_copy_datagram_msg(skb, 0, msg, skb->len); if (err) break; copied += skb->len; } return err ?: copied; } /* Clean up the receive buffer for full frames taken by the user, * then send an ACK if necessary. COPIED is the number of bytes * tcp_recvmsg has given to the user so far, it speeds up the * calculation of whether or not we must ACK for the sake of * a window update. */ static void tcp_cleanup_rbuf(struct sock *sk, int copied) { struct tcp_sock *tp = tcp_sk(sk); bool time_to_ack = false; struct sk_buff *skb = skb_peek(&sk->sk_receive_queue); WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq), "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n", tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt); if (inet_csk_ack_scheduled(sk)) { const struct inet_connection_sock *icsk = inet_csk(sk); /* Delayed ACKs frequently hit locked sockets during bulk * receive. */ if (icsk->icsk_ack.blocked || /* Once-per-two-segments ACK was not sent by tcp_input.c */ tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss || /* * If this read emptied read buffer, we send ACK, if * connection is not bidirectional, user drained * receive buffer and there was a small segment * in queue. */ (copied > 0 && ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) || ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) && !icsk->icsk_ack.pingpong)) && !atomic_read(&sk->sk_rmem_alloc))) time_to_ack = true; } /* We send an ACK if we can now advertise a non-zero window * which has been raised "significantly". * * Even if window raised up to infinity, do not send window open ACK * in states, where we will not receive more. It is useless. */ if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) { __u32 rcv_window_now = tcp_receive_window(tp); /* Optimize, __tcp_select_window() is not cheap. */ if (2*rcv_window_now <= tp->window_clamp) { __u32 new_window = __tcp_select_window(sk); /* Send ACK now, if this read freed lots of space * in our buffer. Certainly, new_window is new window. * We can advertise it now, if it is not less than current one. * "Lots" means "at least twice" here. */ if (new_window && new_window >= 2 * rcv_window_now) time_to_ack = true; } } if (time_to_ack) tcp_send_ack(sk); } static void tcp_prequeue_process(struct sock *sk) { struct sk_buff *skb; struct tcp_sock *tp = tcp_sk(sk); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPREQUEUED); while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL) sk_backlog_rcv(sk, skb); /* Clear memory counter. */ tp->ucopy.memory = 0; } static struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off) { struct sk_buff *skb; u32 offset; while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) { offset = seq - TCP_SKB_CB(skb)->seq; if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) { pr_err_once("%s: found a SYN, please report !\n", __func__); offset--; } if (offset < skb->len || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) { *off = offset; return skb; } /* This looks weird, but this can happen if TCP collapsing * splitted a fat GRO packet, while we released socket lock * in skb_splice_bits() */ sk_eat_skb(sk, skb); } return NULL; } /* * This routine provides an alternative to tcp_recvmsg() for routines * that would like to handle copying from skbuffs directly in 'sendfile' * fashion. * Note: * - It is assumed that the socket was locked by the caller. * - The routine does not block. * - At present, there is no support for reading OOB data * or for 'peeking' the socket using this routine * (although both would be easy to implement). */ int tcp_read_sock(struct sock *sk, read_descriptor_t *desc, sk_read_actor_t recv_actor) { struct sk_buff *skb; struct tcp_sock *tp = tcp_sk(sk); u32 seq = tp->copied_seq; u32 offset; int copied = 0; if (sk->sk_state == TCP_LISTEN) return -ENOTCONN; while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) { if (offset < skb->len) { int used; size_t len; len = skb->len - offset; /* Stop reading if we hit a patch of urgent data */ if (tp->urg_data) { u32 urg_offset = tp->urg_seq - seq; if (urg_offset < len) len = urg_offset; if (!len) break; } used = recv_actor(desc, skb, offset, len); if (used <= 0) { if (!copied) copied = used; break; } else if (used <= len) { seq += used; copied += used; offset += used; } /* If recv_actor drops the lock (e.g. TCP splice * receive) the skb pointer might be invalid when * getting here: tcp_collapse might have deleted it * while aggregating skbs from the socket queue. */ skb = tcp_recv_skb(sk, seq - 1, &offset); if (!skb) break; /* TCP coalescing might have appended data to the skb. * Try to splice more frags */ if (offset + 1 != skb->len) continue; } if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) { sk_eat_skb(sk, skb); ++seq; break; } sk_eat_skb(sk, skb); if (!desc->count) break; tp->copied_seq = seq; } tp->copied_seq = seq; tcp_rcv_space_adjust(sk); /* Clean up data we have read: This will do ACK frames. */ if (copied > 0) { tcp_recv_skb(sk, seq, &offset); tcp_cleanup_rbuf(sk, copied); } return copied; } EXPORT_SYMBOL(tcp_read_sock); int tcp_peek_len(struct socket *sock) { return tcp_inq(sock->sk); } EXPORT_SYMBOL(tcp_peek_len); /* * This routine copies from a sock struct into the user buffer. * * Technical note: in 2.3 we work on _locked_ socket, so that * tricks with *seq access order and skb->users are not required. * Probably, code can be easily improved even more. */ int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int nonblock, int flags, int *addr_len) { struct tcp_sock *tp = tcp_sk(sk); int copied = 0; u32 peek_seq; u32 *seq; unsigned long used; int err; int target; /* Read at least this many bytes */ long timeo; struct task_struct *user_recv = NULL; struct sk_buff *skb, *last; u32 urg_hole = 0; if (unlikely(flags & MSG_ERRQUEUE)) return inet_recv_error(sk, msg, len, addr_len); if (sk_can_busy_loop(sk) && skb_queue_empty(&sk->sk_receive_queue) && (sk->sk_state == TCP_ESTABLISHED)) sk_busy_loop(sk, nonblock); lock_sock(sk); err = -ENOTCONN; if (sk->sk_state == TCP_LISTEN) goto out; timeo = sock_rcvtimeo(sk, nonblock); /* Urgent data needs to be handled specially. */ if (flags & MSG_OOB) goto recv_urg; if (unlikely(tp->repair)) { err = -EPERM; if (!(flags & MSG_PEEK)) goto out; if (tp->repair_queue == TCP_SEND_QUEUE) goto recv_sndq; err = -EINVAL; if (tp->repair_queue == TCP_NO_QUEUE) goto out; /* 'common' recv queue MSG_PEEK-ing */ } seq = &tp->copied_seq; if (flags & MSG_PEEK) { peek_seq = tp->copied_seq; seq = &peek_seq; } target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); do { u32 offset; /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */ if (tp->urg_data && tp->urg_seq == *seq) { if (copied) break; if (signal_pending(current)) { copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; break; } } /* Next get a buffer. */ last = skb_peek_tail(&sk->sk_receive_queue); skb_queue_walk(&sk->sk_receive_queue, skb) { last = skb; /* Now that we have two receive queues this * shouldn't happen. */ if (WARN(before(*seq, TCP_SKB_CB(skb)->seq), "recvmsg bug: copied %X seq %X rcvnxt %X fl %X\n", *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags)) break; offset = *seq - TCP_SKB_CB(skb)->seq; if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) { pr_err_once("%s: found a SYN, please report !\n", __func__); offset--; } if (offset < skb->len) goto found_ok_skb; if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) goto found_fin_ok; WARN(!(flags & MSG_PEEK), "recvmsg bug 2: copied %X seq %X rcvnxt %X fl %X\n", *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags); } /* Well, if we have backlog, try to process it now yet. */ if (copied >= target && !sk->sk_backlog.tail) break; if (copied) { if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || !timeo || signal_pending(current)) break; } else { if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { copied = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_state == TCP_CLOSE) { if (!sock_flag(sk, SOCK_DONE)) { /* This occurs when user tries to read * from never connected socket. */ copied = -ENOTCONN; break; } break; } if (!timeo) { copied = -EAGAIN; break; } if (signal_pending(current)) { copied = sock_intr_errno(timeo); break; } } tcp_cleanup_rbuf(sk, copied); if (!sysctl_tcp_low_latency && tp->ucopy.task == user_recv) { /* Install new reader */ if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) { user_recv = current; tp->ucopy.task = user_recv; tp->ucopy.msg = msg; } tp->ucopy.len = len; WARN_ON(tp->copied_seq != tp->rcv_nxt && !(flags & (MSG_PEEK | MSG_TRUNC))); /* Ugly... If prequeue is not empty, we have to * process it before releasing socket, otherwise * order will be broken at second iteration. * More elegant solution is required!!! * * Look: we have the following (pseudo)queues: * * 1. packets in flight * 2. backlog * 3. prequeue * 4. receive_queue * * Each queue can be processed only if the next ones * are empty. At this point we have empty receive_queue. * But prequeue _can_ be not empty after 2nd iteration, * when we jumped to start of loop because backlog * processing added something to receive_queue. * We cannot release_sock(), because backlog contains * packets arrived _after_ prequeued ones. * * Shortly, algorithm is clear --- to process all * the queues in order. We could make it more directly, * requeueing packets from backlog to prequeue, if * is not empty. It is more elegant, but eats cycles, * unfortunately. */ if (!skb_queue_empty(&tp->ucopy.prequeue)) goto do_prequeue; /* __ Set realtime policy in scheduler __ */ } if (copied >= target) { /* Do not sleep, just process backlog. */ release_sock(sk); lock_sock(sk); } else { sk_wait_data(sk, &timeo, last); } if (user_recv) { int chunk; /* __ Restore normal policy in scheduler __ */ chunk = len - tp->ucopy.len; if (chunk != 0) { NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk); len -= chunk; copied += chunk; } if (tp->rcv_nxt == tp->copied_seq && !skb_queue_empty(&tp->ucopy.prequeue)) { do_prequeue: tcp_prequeue_process(sk); chunk = len - tp->ucopy.len; if (chunk != 0) { NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk); len -= chunk; copied += chunk; } } } if ((flags & MSG_PEEK) && (peek_seq - copied - urg_hole != tp->copied_seq)) { net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n", current->comm, task_pid_nr(current)); peek_seq = tp->copied_seq; } continue; found_ok_skb: /* Ok so how much can we use? */ used = skb->len - offset; if (len < used) used = len; /* Do we have urgent data here? */ if (tp->urg_data) { u32 urg_offset = tp->urg_seq - *seq; if (urg_offset < used) { if (!urg_offset) { if (!sock_flag(sk, SOCK_URGINLINE)) { ++*seq; urg_hole++; offset++; used--; if (!used) goto skip_copy; } } else used = urg_offset; } } if (!(flags & MSG_TRUNC)) { err = skb_copy_datagram_msg(skb, offset, msg, used); if (err) { /* Exception. Bailout! */ if (!copied) copied = -EFAULT; break; } } *seq += used; copied += used; len -= used; tcp_rcv_space_adjust(sk); skip_copy: if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) { tp->urg_data = 0; tcp_fast_path_check(sk); } if (used + offset < skb->len) continue; if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) goto found_fin_ok; if (!(flags & MSG_PEEK)) sk_eat_skb(sk, skb); continue; found_fin_ok: /* Process the FIN. */ ++*seq; if (!(flags & MSG_PEEK)) sk_eat_skb(sk, skb); break; } while (len > 0); if (user_recv) { if (!skb_queue_empty(&tp->ucopy.prequeue)) { int chunk; tp->ucopy.len = copied > 0 ? len : 0; tcp_prequeue_process(sk); if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) { NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk); len -= chunk; copied += chunk; } } tp->ucopy.task = NULL; tp->ucopy.len = 0; } /* According to UNIX98, msg_name/msg_namelen are ignored * on connected socket. I was just happy when found this 8) --ANK */ /* Clean up data we have read: This will do ACK frames. */ tcp_cleanup_rbuf(sk, copied); release_sock(sk); return copied; out: release_sock(sk); return err; recv_urg: err = tcp_recv_urg(sk, msg, len, flags); goto out; recv_sndq: err = tcp_peek_sndq(sk, msg, len); goto out; } EXPORT_SYMBOL(tcp_recvmsg); void tcp_set_state(struct sock *sk, int state) { int oldstate = sk->sk_state; switch (state) { case TCP_ESTABLISHED: if (oldstate != TCP_ESTABLISHED) TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB); break; case TCP_CLOSE: if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED) TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS); sk->sk_prot->unhash(sk); if (inet_csk(sk)->icsk_bind_hash && !(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) inet_put_port(sk); /* fall through */ default: if (oldstate == TCP_ESTABLISHED) TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB); } /* Change state AFTER socket is unhashed to avoid closed * socket sitting in hash tables. */ sk_state_store(sk, state); #ifdef STATE_TRACE SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n", sk, statename[oldstate], statename[state]); #endif } EXPORT_SYMBOL_GPL(tcp_set_state); /* * State processing on a close. This implements the state shift for * sending our FIN frame. Note that we only send a FIN for some * states. A shutdown() may have already sent the FIN, or we may be * closed. */ static const unsigned char new_state[16] = { /* current state: new state: action: */ [0 /* (Invalid) */] = TCP_CLOSE, [TCP_ESTABLISHED] = TCP_FIN_WAIT1 | TCP_ACTION_FIN, [TCP_SYN_SENT] = TCP_CLOSE, [TCP_SYN_RECV] = TCP_FIN_WAIT1 | TCP_ACTION_FIN, [TCP_FIN_WAIT1] = TCP_FIN_WAIT1, [TCP_FIN_WAIT2] = TCP_FIN_WAIT2, [TCP_TIME_WAIT] = TCP_CLOSE, [TCP_CLOSE] = TCP_CLOSE, [TCP_CLOSE_WAIT] = TCP_LAST_ACK | TCP_ACTION_FIN, [TCP_LAST_ACK] = TCP_LAST_ACK, [TCP_LISTEN] = TCP_CLOSE, [TCP_CLOSING] = TCP_CLOSING, [TCP_NEW_SYN_RECV] = TCP_CLOSE, /* should not happen ! */ }; static int tcp_close_state(struct sock *sk) { int next = (int)new_state[sk->sk_state]; int ns = next & TCP_STATE_MASK; tcp_set_state(sk, ns); return next & TCP_ACTION_FIN; } /* * Shutdown the sending side of a connection. Much like close except * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD). */ void tcp_shutdown(struct sock *sk, int how) { /* We need to grab some memory, and put together a FIN, * and then put it into the queue to be sent. * Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92. */ if (!(how & SEND_SHUTDOWN)) return; /* If we've already sent a FIN, or it's a closed state, skip this. */ if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) { /* Clear out any half completed packets. FIN if needed. */ if (tcp_close_state(sk)) tcp_send_fin(sk); } } EXPORT_SYMBOL(tcp_shutdown); bool tcp_check_oom(struct sock *sk, int shift) { bool too_many_orphans, out_of_socket_memory; too_many_orphans = tcp_too_many_orphans(sk, shift); out_of_socket_memory = tcp_out_of_memory(sk); if (too_many_orphans) net_info_ratelimited("too many orphaned sockets\n"); if (out_of_socket_memory) net_info_ratelimited("out of memory -- consider tuning tcp_mem\n"); return too_many_orphans || out_of_socket_memory; } void tcp_close(struct sock *sk, long timeout) { struct sk_buff *skb; int data_was_unread = 0; int state; lock_sock(sk); sk->sk_shutdown = SHUTDOWN_MASK; if (sk->sk_state == TCP_LISTEN) { tcp_set_state(sk, TCP_CLOSE); /* Special case. */ inet_csk_listen_stop(sk); goto adjudge_to_death; } /* We need to flush the recv. buffs. We do this only on the * descriptor close, not protocol-sourced closes, because the * reader process may not have drained the data yet! */ while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) { u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq; if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) len--; data_was_unread += len; __kfree_skb(skb); } sk_mem_reclaim(sk); /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */ if (sk->sk_state == TCP_CLOSE) goto adjudge_to_death; /* As outlined in RFC 2525, section 2.17, we send a RST here because * data was lost. To witness the awful effects of the old behavior of * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk * GET in an FTP client, suspend the process, wait for the client to * advertise a zero window, then kill -9 the FTP client, wheee... * Note: timeout is always zero in such a case. */ if (unlikely(tcp_sk(sk)->repair)) { sk->sk_prot->disconnect(sk, 0); } else if (data_was_unread) { /* Unread data was tossed, zap the connection. */ NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE); tcp_set_state(sk, TCP_CLOSE); tcp_send_active_reset(sk, sk->sk_allocation); } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) { /* Check zero linger _after_ checking for unread data. */ sk->sk_prot->disconnect(sk, 0); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA); } else if (tcp_close_state(sk)) { /* We FIN if the application ate all the data before * zapping the connection. */ /* RED-PEN. Formally speaking, we have broken TCP state * machine. State transitions: * * TCP_ESTABLISHED -> TCP_FIN_WAIT1 * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible) * TCP_CLOSE_WAIT -> TCP_LAST_ACK * * are legal only when FIN has been sent (i.e. in window), * rather than queued out of window. Purists blame. * * F.e. "RFC state" is ESTABLISHED, * if Linux state is FIN-WAIT-1, but FIN is still not sent. * * The visible declinations are that sometimes * we enter time-wait state, when it is not required really * (harmless), do not send active resets, when they are * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when * they look as CLOSING or LAST_ACK for Linux) * Probably, I missed some more holelets. * --ANK * XXX (TFO) - To start off we don't support SYN+ACK+FIN * in a single packet! (May consider it later but will * probably need API support or TCP_CORK SYN-ACK until * data is written and socket is closed.) */ tcp_send_fin(sk); } sk_stream_wait_close(sk, timeout); adjudge_to_death: state = sk->sk_state; sock_hold(sk); sock_orphan(sk); /* It is the last release_sock in its life. It will remove backlog. */ release_sock(sk); /* Now socket is owned by kernel and we acquire BH lock to finish close. No need to check for user refs. */ local_bh_disable(); bh_lock_sock(sk); WARN_ON(sock_owned_by_user(sk)); percpu_counter_inc(sk->sk_prot->orphan_count); /* Have we already been destroyed by a softirq or backlog? */ if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE) goto out; /* This is a (useful) BSD violating of the RFC. There is a * problem with TCP as specified in that the other end could * keep a socket open forever with no application left this end. * We use a 1 minute timeout (about the same as BSD) then kill * our end. If they send after that then tough - BUT: long enough * that we won't make the old 4*rto = almost no time - whoops * reset mistake. * * Nope, it was not mistake. It is really desired behaviour * f.e. on http servers, when such sockets are useless, but * consume significant resources. Let's do it with special * linger2 option. --ANK */ if (sk->sk_state == TCP_FIN_WAIT2) { struct tcp_sock *tp = tcp_sk(sk); if (tp->linger2 < 0) { tcp_set_state(sk, TCP_CLOSE); tcp_send_active_reset(sk, GFP_ATOMIC); __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONLINGER); } else { const int tmo = tcp_fin_time(sk); if (tmo > TCP_TIMEWAIT_LEN) { inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN); } else { tcp_time_wait(sk, TCP_FIN_WAIT2, tmo); goto out; } } } if (sk->sk_state != TCP_CLOSE) { sk_mem_reclaim(sk); if (tcp_check_oom(sk, 0)) { tcp_set_state(sk, TCP_CLOSE); tcp_send_active_reset(sk, GFP_ATOMIC); __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONMEMORY); } } if (sk->sk_state == TCP_CLOSE) { struct request_sock *req = tcp_sk(sk)->fastopen_rsk; /* We could get here with a non-NULL req if the socket is * aborted (e.g., closed with unread data) before 3WHS * finishes. */ if (req) reqsk_fastopen_remove(sk, req, false); inet_csk_destroy_sock(sk); } /* Otherwise, socket is reprieved until protocol close. */ out: bh_unlock_sock(sk); local_bh_enable(); sock_put(sk); } EXPORT_SYMBOL(tcp_close); /* These states need RST on ABORT according to RFC793 */ static inline bool tcp_need_reset(int state) { return (1 << state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 | TCPF_FIN_WAIT2 | TCPF_SYN_RECV); } int tcp_disconnect(struct sock *sk, int flags) { struct inet_sock *inet = inet_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int err = 0; int old_state = sk->sk_state; if (old_state != TCP_CLOSE) tcp_set_state(sk, TCP_CLOSE); /* ABORT function of RFC793 */ if (old_state == TCP_LISTEN) { inet_csk_listen_stop(sk); } else if (unlikely(tp->repair)) { sk->sk_err = ECONNABORTED; } else if (tcp_need_reset(old_state) || (tp->snd_nxt != tp->write_seq && (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) { /* The last check adjusts for discrepancy of Linux wrt. RFC * states */ tcp_send_active_reset(sk, gfp_any()); sk->sk_err = ECONNRESET; } else if (old_state == TCP_SYN_SENT) sk->sk_err = ECONNRESET; tcp_clear_xmit_timers(sk); __skb_queue_purge(&sk->sk_receive_queue); tcp_write_queue_purge(sk); tcp_fastopen_active_disable_ofo_check(sk); skb_rbtree_purge(&tp->out_of_order_queue); inet->inet_dport = 0; if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) inet_reset_saddr(sk); sk->sk_shutdown = 0; sock_reset_flag(sk, SOCK_DONE); tp->srtt_us = 0; tp->write_seq += tp->max_window + 2; if (tp->write_seq == 0) tp->write_seq = 1; icsk->icsk_backoff = 0; tp->snd_cwnd = 2; icsk->icsk_probes_out = 0; tp->packets_out = 0; tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; tp->snd_cwnd_cnt = 0; tp->window_clamp = 0; tcp_set_ca_state(sk, TCP_CA_Open); tcp_clear_retrans(tp); inet_csk_delack_init(sk); tcp_init_send_head(sk); memset(&tp->rx_opt, 0, sizeof(tp->rx_opt)); __sk_dst_reset(sk); tcp_saved_syn_free(tp); /* Clean up fastopen related fields */ tcp_free_fastopen_req(tp); inet->defer_connect = 0; WARN_ON(inet->inet_num && !icsk->icsk_bind_hash); sk->sk_error_report(sk); return err; } EXPORT_SYMBOL(tcp_disconnect); static inline bool tcp_can_repair_sock(const struct sock *sk) { return ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) && (sk->sk_state != TCP_LISTEN); } static int tcp_repair_set_window(struct tcp_sock *tp, char __user *optbuf, int len) { struct tcp_repair_window opt; if (!tp->repair) return -EPERM; if (len != sizeof(opt)) return -EINVAL; if (copy_from_user(&opt, optbuf, sizeof(opt))) return -EFAULT; if (opt.max_window < opt.snd_wnd) return -EINVAL; if (after(opt.snd_wl1, tp->rcv_nxt + opt.rcv_wnd)) return -EINVAL; if (after(opt.rcv_wup, tp->rcv_nxt)) return -EINVAL; tp->snd_wl1 = opt.snd_wl1; tp->snd_wnd = opt.snd_wnd; tp->max_window = opt.max_window; tp->rcv_wnd = opt.rcv_wnd; tp->rcv_wup = opt.rcv_wup; return 0; } static int tcp_repair_options_est(struct tcp_sock *tp, struct tcp_repair_opt __user *optbuf, unsigned int len) { struct tcp_repair_opt opt; while (len >= sizeof(opt)) { if (copy_from_user(&opt, optbuf, sizeof(opt))) return -EFAULT; optbuf++; len -= sizeof(opt); switch (opt.opt_code) { case TCPOPT_MSS: tp->rx_opt.mss_clamp = opt.opt_val; break; case TCPOPT_WINDOW: { u16 snd_wscale = opt.opt_val & 0xFFFF; u16 rcv_wscale = opt.opt_val >> 16; if (snd_wscale > TCP_MAX_WSCALE || rcv_wscale > TCP_MAX_WSCALE) return -EFBIG; tp->rx_opt.snd_wscale = snd_wscale; tp->rx_opt.rcv_wscale = rcv_wscale; tp->rx_opt.wscale_ok = 1; } break; case TCPOPT_SACK_PERM: if (opt.opt_val != 0) return -EINVAL; tp->rx_opt.sack_ok |= TCP_SACK_SEEN; if (sysctl_tcp_fack) tcp_enable_fack(tp); break; case TCPOPT_TIMESTAMP: if (opt.opt_val != 0) return -EINVAL; tp->rx_opt.tstamp_ok = 1; break; } } return 0; } /* * Socket option code for TCP. */ static int do_tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); struct net *net = sock_net(sk); int val; int err = 0; /* These are data/string values, all the others are ints */ switch (optname) { case TCP_CONGESTION: { char name[TCP_CA_NAME_MAX]; if (optlen < 1) return -EINVAL; val = strncpy_from_user(name, optval, min_t(long, TCP_CA_NAME_MAX-1, optlen)); if (val < 0) return -EFAULT; name[val] = 0; lock_sock(sk); err = tcp_set_congestion_control(sk, name); release_sock(sk); return err; } default: /* fallthru */ break; } if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; lock_sock(sk); switch (optname) { case TCP_MAXSEG: /* Values greater than interface MTU won't take effect. However * at the point when this call is done we typically don't yet * know which interface is going to be used */ if (val && (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW)) { err = -EINVAL; break; } tp->rx_opt.user_mss = val; break; case TCP_NODELAY: if (val) { /* TCP_NODELAY is weaker than TCP_CORK, so that * this option on corked socket is remembered, but * it is not activated until cork is cleared. * * However, when TCP_NODELAY is set we make * an explicit push, which overrides even TCP_CORK * for currently queued segments. */ tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH; tcp_push_pending_frames(sk); } else { tp->nonagle &= ~TCP_NAGLE_OFF; } break; case TCP_THIN_LINEAR_TIMEOUTS: if (val < 0 || val > 1) err = -EINVAL; else tp->thin_lto = val; break; case TCP_THIN_DUPACK: if (val < 0 || val > 1) err = -EINVAL; break; case TCP_REPAIR: if (!tcp_can_repair_sock(sk)) err = -EPERM; else if (val == 1) { tp->repair = 1; sk->sk_reuse = SK_FORCE_REUSE; tp->repair_queue = TCP_NO_QUEUE; } else if (val == 0) { tp->repair = 0; sk->sk_reuse = SK_NO_REUSE; tcp_send_window_probe(sk); } else err = -EINVAL; break; case TCP_REPAIR_QUEUE: if (!tp->repair) err = -EPERM; else if (val < TCP_QUEUES_NR) tp->repair_queue = val; else err = -EINVAL; break; case TCP_QUEUE_SEQ: if (sk->sk_state != TCP_CLOSE) err = -EPERM; else if (tp->repair_queue == TCP_SEND_QUEUE) tp->write_seq = val; else if (tp->repair_queue == TCP_RECV_QUEUE) tp->rcv_nxt = val; else err = -EINVAL; break; case TCP_REPAIR_OPTIONS: if (!tp->repair) err = -EINVAL; else if (sk->sk_state == TCP_ESTABLISHED) err = tcp_repair_options_est(tp, (struct tcp_repair_opt __user *)optval, optlen); else err = -EPERM; break; case TCP_CORK: /* When set indicates to always queue non-full frames. * Later the user clears this option and we transmit * any pending partial frames in the queue. This is * meant to be used alongside sendfile() to get properly * filled frames when the user (for example) must write * out headers with a write() call first and then use * sendfile to send out the data parts. * * TCP_CORK can be set together with TCP_NODELAY and it is * stronger than TCP_NODELAY. */ if (val) { tp->nonagle |= TCP_NAGLE_CORK; } else { tp->nonagle &= ~TCP_NAGLE_CORK; if (tp->nonagle&TCP_NAGLE_OFF) tp->nonagle |= TCP_NAGLE_PUSH; tcp_push_pending_frames(sk); } break; case TCP_KEEPIDLE: if (val < 1 || val > MAX_TCP_KEEPIDLE) err = -EINVAL; else { tp->keepalive_time = val * HZ; if (sock_flag(sk, SOCK_KEEPOPEN) && !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { u32 elapsed = keepalive_time_elapsed(tp); if (tp->keepalive_time > elapsed) elapsed = tp->keepalive_time - elapsed; else elapsed = 0; inet_csk_reset_keepalive_timer(sk, elapsed); } } break; case TCP_KEEPINTVL: if (val < 1 || val > MAX_TCP_KEEPINTVL) err = -EINVAL; else tp->keepalive_intvl = val * HZ; break; case TCP_KEEPCNT: if (val < 1 || val > MAX_TCP_KEEPCNT) err = -EINVAL; else tp->keepalive_probes = val; break; case TCP_SYNCNT: if (val < 1 || val > MAX_TCP_SYNCNT) err = -EINVAL; else icsk->icsk_syn_retries = val; break; case TCP_SAVE_SYN: if (val < 0 || val > 1) err = -EINVAL; else tp->save_syn = val; break; case TCP_LINGER2: if (val < 0) tp->linger2 = -1; else if (val > net->ipv4.sysctl_tcp_fin_timeout / HZ) tp->linger2 = 0; else tp->linger2 = val * HZ; break; case TCP_DEFER_ACCEPT: /* Translate value in seconds to number of retransmits */ icsk->icsk_accept_queue.rskq_defer_accept = secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ); break; case TCP_WINDOW_CLAMP: if (!val) { if (sk->sk_state != TCP_CLOSE) { err = -EINVAL; break; } tp->window_clamp = 0; } else tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ? SOCK_MIN_RCVBUF / 2 : val; break; case TCP_QUICKACK: if (!val) { icsk->icsk_ack.pingpong = 1; } else { icsk->icsk_ack.pingpong = 0; if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) && inet_csk_ack_scheduled(sk)) { icsk->icsk_ack.pending |= ICSK_ACK_PUSHED; tcp_cleanup_rbuf(sk, 1); if (!(val & 1)) icsk->icsk_ack.pingpong = 1; } } break; #ifdef CONFIG_TCP_MD5SIG case TCP_MD5SIG: /* Read the IP->Key mappings from userspace */ err = tp->af_specific->md5_parse(sk, optval, optlen); break; #endif case TCP_USER_TIMEOUT: /* Cap the max time in ms TCP will retry or probe the window * before giving up and aborting (ETIMEDOUT) a connection. */ if (val < 0) err = -EINVAL; else icsk->icsk_user_timeout = msecs_to_jiffies(val); break; case TCP_FASTOPEN: if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { tcp_fastopen_init_key_once(true); fastopen_queue_tune(sk, val); } else { err = -EINVAL; } break; case TCP_FASTOPEN_CONNECT: if (val > 1 || val < 0) { err = -EINVAL; } else if (sysctl_tcp_fastopen & TFO_CLIENT_ENABLE) { if (sk->sk_state == TCP_CLOSE) tp->fastopen_connect = val; else err = -EINVAL; } else { err = -EOPNOTSUPP; } break; case TCP_TIMESTAMP: if (!tp->repair) err = -EPERM; else tp->tsoffset = val - tcp_time_stamp; break; case TCP_REPAIR_WINDOW: err = tcp_repair_set_window(tp, optval, optlen); break; case TCP_NOTSENT_LOWAT: tp->notsent_lowat = val; sk->sk_write_space(sk); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { const struct inet_connection_sock *icsk = inet_csk(sk); if (level != SOL_TCP) return icsk->icsk_af_ops->setsockopt(sk, level, optname, optval, optlen); return do_tcp_setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(tcp_setsockopt); #ifdef CONFIG_COMPAT int compat_tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level != SOL_TCP) return inet_csk_compat_setsockopt(sk, level, optname, optval, optlen); return do_tcp_setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_tcp_setsockopt); #endif static void tcp_get_info_chrono_stats(const struct tcp_sock *tp, struct tcp_info *info) { u64 stats[__TCP_CHRONO_MAX], total = 0; enum tcp_chrono i; for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) { stats[i] = tp->chrono_stat[i - 1]; if (i == tp->chrono_type) stats[i] += tcp_time_stamp - tp->chrono_start; stats[i] *= USEC_PER_SEC / HZ; total += stats[i]; } info->tcpi_busy_time = total; info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED]; info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED]; } /* Return information about state of tcp endpoint in API format. */ void tcp_get_info(struct sock *sk, struct tcp_info *info) { const struct tcp_sock *tp = tcp_sk(sk); /* iff sk_type == SOCK_STREAM */ const struct inet_connection_sock *icsk = inet_csk(sk); u32 now, intv; u64 rate64; bool slow; u32 rate; memset(info, 0, sizeof(*info)); if (sk->sk_type != SOCK_STREAM) return; info->tcpi_state = sk_state_load(sk); /* Report meaningful fields for all TCP states, including listeners */ rate = READ_ONCE(sk->sk_pacing_rate); rate64 = rate != ~0U ? rate : ~0ULL; info->tcpi_pacing_rate = rate64; rate = READ_ONCE(sk->sk_max_pacing_rate); rate64 = rate != ~0U ? rate : ~0ULL; info->tcpi_max_pacing_rate = rate64; info->tcpi_reordering = tp->reordering; info->tcpi_snd_cwnd = tp->snd_cwnd; if (info->tcpi_state == TCP_LISTEN) { /* listeners aliased fields : * tcpi_unacked -> Number of children ready for accept() * tcpi_sacked -> max backlog */ info->tcpi_unacked = sk->sk_ack_backlog; info->tcpi_sacked = sk->sk_max_ack_backlog; return; } slow = lock_sock_fast(sk); info->tcpi_ca_state = icsk->icsk_ca_state; info->tcpi_retransmits = icsk->icsk_retransmits; info->tcpi_probes = icsk->icsk_probes_out; info->tcpi_backoff = icsk->icsk_backoff; if (tp->rx_opt.tstamp_ok) info->tcpi_options |= TCPI_OPT_TIMESTAMPS; if (tcp_is_sack(tp)) info->tcpi_options |= TCPI_OPT_SACK; if (tp->rx_opt.wscale_ok) { info->tcpi_options |= TCPI_OPT_WSCALE; info->tcpi_snd_wscale = tp->rx_opt.snd_wscale; info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale; } if (tp->ecn_flags & TCP_ECN_OK) info->tcpi_options |= TCPI_OPT_ECN; if (tp->ecn_flags & TCP_ECN_SEEN) info->tcpi_options |= TCPI_OPT_ECN_SEEN; if (tp->syn_data_acked) info->tcpi_options |= TCPI_OPT_SYN_DATA; info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto); info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato); info->tcpi_snd_mss = tp->mss_cache; info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss; info->tcpi_unacked = tp->packets_out; info->tcpi_sacked = tp->sacked_out; info->tcpi_lost = tp->lost_out; info->tcpi_retrans = tp->retrans_out; info->tcpi_fackets = tp->fackets_out; now = tcp_time_stamp; info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime); info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime); info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp); info->tcpi_pmtu = icsk->icsk_pmtu_cookie; info->tcpi_rcv_ssthresh = tp->rcv_ssthresh; info->tcpi_rtt = tp->srtt_us >> 3; info->tcpi_rttvar = tp->mdev_us >> 2; info->tcpi_snd_ssthresh = tp->snd_ssthresh; info->tcpi_advmss = tp->advmss; info->tcpi_rcv_rtt = tp->rcv_rtt_est.rtt_us >> 3; info->tcpi_rcv_space = tp->rcvq_space.space; info->tcpi_total_retrans = tp->total_retrans; info->tcpi_bytes_acked = tp->bytes_acked; info->tcpi_bytes_received = tp->bytes_received; info->tcpi_notsent_bytes = max_t(int, 0, tp->write_seq - tp->snd_nxt); tcp_get_info_chrono_stats(tp, info); info->tcpi_segs_out = tp->segs_out; info->tcpi_segs_in = tp->segs_in; info->tcpi_min_rtt = tcp_min_rtt(tp); info->tcpi_data_segs_in = tp->data_segs_in; info->tcpi_data_segs_out = tp->data_segs_out; info->tcpi_delivery_rate_app_limited = tp->rate_app_limited ? 1 : 0; rate = READ_ONCE(tp->rate_delivered); intv = READ_ONCE(tp->rate_interval_us); if (rate && intv) { rate64 = (u64)rate * tp->mss_cache * USEC_PER_SEC; do_div(rate64, intv); info->tcpi_delivery_rate = rate64; } unlock_sock_fast(sk, slow); } EXPORT_SYMBOL_GPL(tcp_get_info); struct sk_buff *tcp_get_timestamping_opt_stats(const struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *stats; struct tcp_info info; stats = alloc_skb(5 * nla_total_size_64bit(sizeof(u64)), GFP_ATOMIC); if (!stats) return NULL; tcp_get_info_chrono_stats(tp, &info); nla_put_u64_64bit(stats, TCP_NLA_BUSY, info.tcpi_busy_time, TCP_NLA_PAD); nla_put_u64_64bit(stats, TCP_NLA_RWND_LIMITED, info.tcpi_rwnd_limited, TCP_NLA_PAD); nla_put_u64_64bit(stats, TCP_NLA_SNDBUF_LIMITED, info.tcpi_sndbuf_limited, TCP_NLA_PAD); nla_put_u64_64bit(stats, TCP_NLA_DATA_SEGS_OUT, tp->data_segs_out, TCP_NLA_PAD); nla_put_u64_64bit(stats, TCP_NLA_TOTAL_RETRANS, tp->total_retrans, TCP_NLA_PAD); return stats; } static int do_tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct net *net = sock_net(sk); int val, len; if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, sizeof(int)); if (len < 0) return -EINVAL; switch (optname) { case TCP_MAXSEG: val = tp->mss_cache; if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) val = tp->rx_opt.user_mss; if (tp->repair) val = tp->rx_opt.mss_clamp; break; case TCP_NODELAY: val = !!(tp->nonagle&TCP_NAGLE_OFF); break; case TCP_CORK: val = !!(tp->nonagle&TCP_NAGLE_CORK); break; case TCP_KEEPIDLE: val = keepalive_time_when(tp) / HZ; break; case TCP_KEEPINTVL: val = keepalive_intvl_when(tp) / HZ; break; case TCP_KEEPCNT: val = keepalive_probes(tp); break; case TCP_SYNCNT: val = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_syn_retries; break; case TCP_LINGER2: val = tp->linger2; if (val >= 0) val = (val ? : net->ipv4.sysctl_tcp_fin_timeout) / HZ; break; case TCP_DEFER_ACCEPT: val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept, TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ); break; case TCP_WINDOW_CLAMP: val = tp->window_clamp; break; case TCP_INFO: { struct tcp_info info; if (get_user(len, optlen)) return -EFAULT; tcp_get_info(sk, &info); len = min_t(unsigned int, len, sizeof(info)); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &info, len)) return -EFAULT; return 0; } case TCP_CC_INFO: { const struct tcp_congestion_ops *ca_ops; union tcp_cc_info info; size_t sz = 0; int attr; if (get_user(len, optlen)) return -EFAULT; ca_ops = icsk->icsk_ca_ops; if (ca_ops && ca_ops->get_info) sz = ca_ops->get_info(sk, ~0U, &attr, &info); len = min_t(unsigned int, len, sz); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &info, len)) return -EFAULT; return 0; } case TCP_QUICKACK: val = !icsk->icsk_ack.pingpong; break; case TCP_CONGESTION: if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, TCP_CA_NAME_MAX); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, icsk->icsk_ca_ops->name, len)) return -EFAULT; return 0; case TCP_THIN_LINEAR_TIMEOUTS: val = tp->thin_lto; break; case TCP_THIN_DUPACK: val = 0; break; case TCP_REPAIR: val = tp->repair; break; case TCP_REPAIR_QUEUE: if (tp->repair) val = tp->repair_queue; else return -EINVAL; break; case TCP_REPAIR_WINDOW: { struct tcp_repair_window opt; if (get_user(len, optlen)) return -EFAULT; if (len != sizeof(opt)) return -EINVAL; if (!tp->repair) return -EPERM; opt.snd_wl1 = tp->snd_wl1; opt.snd_wnd = tp->snd_wnd; opt.max_window = tp->max_window; opt.rcv_wnd = tp->rcv_wnd; opt.rcv_wup = tp->rcv_wup; if (copy_to_user(optval, &opt, len)) return -EFAULT; return 0; } case TCP_QUEUE_SEQ: if (tp->repair_queue == TCP_SEND_QUEUE) val = tp->write_seq; else if (tp->repair_queue == TCP_RECV_QUEUE) val = tp->rcv_nxt; else return -EINVAL; break; case TCP_USER_TIMEOUT: val = jiffies_to_msecs(icsk->icsk_user_timeout); break; case TCP_FASTOPEN: val = icsk->icsk_accept_queue.fastopenq.max_qlen; break; case TCP_FASTOPEN_CONNECT: val = tp->fastopen_connect; break; case TCP_TIMESTAMP: val = tcp_time_stamp + tp->tsoffset; break; case TCP_NOTSENT_LOWAT: val = tp->notsent_lowat; break; case TCP_SAVE_SYN: val = tp->save_syn; break; case TCP_SAVED_SYN: { if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); if (tp->saved_syn) { if (len < tp->saved_syn[0]) { if (put_user(tp->saved_syn[0], optlen)) { release_sock(sk); return -EFAULT; } release_sock(sk); return -EINVAL; } len = tp->saved_syn[0]; if (put_user(len, optlen)) { release_sock(sk); return -EFAULT; } if (copy_to_user(optval, tp->saved_syn + 1, len)) { release_sock(sk); return -EFAULT; } tcp_saved_syn_free(tp); release_sock(sk); } else { release_sock(sk); len = 0; if (put_user(len, optlen)) return -EFAULT; } return 0; } default: return -ENOPROTOOPT; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { struct inet_connection_sock *icsk = inet_csk(sk); if (level != SOL_TCP) return icsk->icsk_af_ops->getsockopt(sk, level, optname, optval, optlen); return do_tcp_getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(tcp_getsockopt); #ifdef CONFIG_COMPAT int compat_tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level != SOL_TCP) return inet_csk_compat_getsockopt(sk, level, optname, optval, optlen); return do_tcp_getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_tcp_getsockopt); #endif #ifdef CONFIG_TCP_MD5SIG static DEFINE_PER_CPU(struct tcp_md5sig_pool, tcp_md5sig_pool); static DEFINE_MUTEX(tcp_md5sig_mutex); static bool tcp_md5sig_pool_populated = false; static void __tcp_alloc_md5sig_pool(void) { struct crypto_ahash *hash; int cpu; hash = crypto_alloc_ahash("md5", 0, CRYPTO_ALG_ASYNC); if (IS_ERR(hash)) return; for_each_possible_cpu(cpu) { void *scratch = per_cpu(tcp_md5sig_pool, cpu).scratch; struct ahash_request *req; if (!scratch) { scratch = kmalloc_node(sizeof(union tcp_md5sum_block) + sizeof(struct tcphdr), GFP_KERNEL, cpu_to_node(cpu)); if (!scratch) return; per_cpu(tcp_md5sig_pool, cpu).scratch = scratch; } if (per_cpu(tcp_md5sig_pool, cpu).md5_req) continue; req = ahash_request_alloc(hash, GFP_KERNEL); if (!req) return; ahash_request_set_callback(req, 0, NULL, NULL); per_cpu(tcp_md5sig_pool, cpu).md5_req = req; } /* before setting tcp_md5sig_pool_populated, we must commit all writes * to memory. See smp_rmb() in tcp_get_md5sig_pool() */ smp_wmb(); tcp_md5sig_pool_populated = true; } bool tcp_alloc_md5sig_pool(void) { if (unlikely(!tcp_md5sig_pool_populated)) { mutex_lock(&tcp_md5sig_mutex); if (!tcp_md5sig_pool_populated) __tcp_alloc_md5sig_pool(); mutex_unlock(&tcp_md5sig_mutex); } return tcp_md5sig_pool_populated; } EXPORT_SYMBOL(tcp_alloc_md5sig_pool); /** * tcp_get_md5sig_pool - get md5sig_pool for this user * * We use percpu structure, so if we succeed, we exit with preemption * and BH disabled, to make sure another thread or softirq handling * wont try to get same context. */ struct tcp_md5sig_pool *tcp_get_md5sig_pool(void) { local_bh_disable(); if (tcp_md5sig_pool_populated) { /* coupled with smp_wmb() in __tcp_alloc_md5sig_pool() */ smp_rmb(); return this_cpu_ptr(&tcp_md5sig_pool); } local_bh_enable(); return NULL; } EXPORT_SYMBOL(tcp_get_md5sig_pool); int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp, const struct sk_buff *skb, unsigned int header_len) { struct scatterlist sg; const struct tcphdr *tp = tcp_hdr(skb); struct ahash_request *req = hp->md5_req; unsigned int i; const unsigned int head_data_len = skb_headlen(skb) > header_len ? skb_headlen(skb) - header_len : 0; const struct skb_shared_info *shi = skb_shinfo(skb); struct sk_buff *frag_iter; sg_init_table(&sg, 1); sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len); ahash_request_set_crypt(req, &sg, NULL, head_data_len); if (crypto_ahash_update(req)) return 1; for (i = 0; i < shi->nr_frags; ++i) { const struct skb_frag_struct *f = &shi->frags[i]; unsigned int offset = f->page_offset; struct page *page = skb_frag_page(f) + (offset >> PAGE_SHIFT); sg_set_page(&sg, page, skb_frag_size(f), offset_in_page(offset)); ahash_request_set_crypt(req, &sg, NULL, skb_frag_size(f)); if (crypto_ahash_update(req)) return 1; } skb_walk_frags(skb, frag_iter) if (tcp_md5_hash_skb_data(hp, frag_iter, 0)) return 1; return 0; } EXPORT_SYMBOL(tcp_md5_hash_skb_data); int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key) { struct scatterlist sg; sg_init_one(&sg, key->key, key->keylen); ahash_request_set_crypt(hp->md5_req, &sg, NULL, key->keylen); return crypto_ahash_update(hp->md5_req); } EXPORT_SYMBOL(tcp_md5_hash_key); #endif void tcp_done(struct sock *sk) { struct request_sock *req = tcp_sk(sk)->fastopen_rsk; if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV) TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS); tcp_set_state(sk, TCP_CLOSE); tcp_clear_xmit_timers(sk); if (req) reqsk_fastopen_remove(sk, req, false); sk->sk_shutdown = SHUTDOWN_MASK; if (!sock_flag(sk, SOCK_DEAD)) sk->sk_state_change(sk); else inet_csk_destroy_sock(sk); } EXPORT_SYMBOL_GPL(tcp_done); int tcp_abort(struct sock *sk, int err) { if (!sk_fullsock(sk)) { if (sk->sk_state == TCP_NEW_SYN_RECV) { struct request_sock *req = inet_reqsk(sk); local_bh_disable(); inet_csk_reqsk_queue_drop_and_put(req->rsk_listener, req); local_bh_enable(); return 0; } return -EOPNOTSUPP; } /* Don't race with userspace socket closes such as tcp_close. */ lock_sock(sk); if (sk->sk_state == TCP_LISTEN) { tcp_set_state(sk, TCP_CLOSE); inet_csk_listen_stop(sk); } /* Don't race with BH socket closes such as inet_csk_listen_stop. */ local_bh_disable(); bh_lock_sock(sk); if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_err = err; /* This barrier is coupled with smp_rmb() in tcp_poll() */ smp_wmb(); sk->sk_error_report(sk); if (tcp_need_reset(sk->sk_state)) tcp_send_active_reset(sk, GFP_ATOMIC); tcp_done(sk); } bh_unlock_sock(sk); local_bh_enable(); release_sock(sk); return 0; } EXPORT_SYMBOL_GPL(tcp_abort); extern struct tcp_congestion_ops tcp_reno; static __initdata unsigned long thash_entries; static int __init set_thash_entries(char *str) { ssize_t ret; if (!str) return 0; ret = kstrtoul(str, 0, &thash_entries); if (ret) return 0; return 1; } __setup("thash_entries=", set_thash_entries); static void __init tcp_init_mem(void) { unsigned long limit = nr_free_buffer_pages() / 16; limit = max(limit, 128UL); sysctl_tcp_mem[0] = limit / 4 * 3; /* 4.68 % */ sysctl_tcp_mem[1] = limit; /* 6.25 % */ sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2; /* 9.37 % */ } void __init tcp_init(void) { int max_rshare, max_wshare, cnt; unsigned long limit; unsigned int i; BUILD_BUG_ON(sizeof(struct tcp_skb_cb) > FIELD_SIZEOF(struct sk_buff, cb)); percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL); percpu_counter_init(&tcp_orphan_count, 0, GFP_KERNEL); inet_hashinfo_init(&tcp_hashinfo); tcp_hashinfo.bind_bucket_cachep = kmem_cache_create("tcp_bind_bucket", sizeof(struct inet_bind_bucket), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); /* Size and allocate the main established and bind bucket * hash tables. * * The methodology is similar to that of the buffer cache. */ tcp_hashinfo.ehash = alloc_large_system_hash("TCP established", sizeof(struct inet_ehash_bucket), thash_entries, 17, /* one slot per 128 KB of memory */ 0, NULL, &tcp_hashinfo.ehash_mask, 0, thash_entries ? 0 : 512 * 1024); for (i = 0; i <= tcp_hashinfo.ehash_mask; i++) INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i); if (inet_ehash_locks_alloc(&tcp_hashinfo)) panic("TCP: failed to alloc ehash_locks"); tcp_hashinfo.bhash = alloc_large_system_hash("TCP bind", sizeof(struct inet_bind_hashbucket), tcp_hashinfo.ehash_mask + 1, 17, /* one slot per 128 KB of memory */ 0, &tcp_hashinfo.bhash_size, NULL, 0, 64 * 1024); tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size; for (i = 0; i < tcp_hashinfo.bhash_size; i++) { spin_lock_init(&tcp_hashinfo.bhash[i].lock); INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain); } cnt = tcp_hashinfo.ehash_mask + 1; sysctl_tcp_max_orphans = cnt / 2; tcp_init_mem(); /* Set per-socket limits to no more than 1/128 the pressure threshold */ limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7); max_wshare = min(4UL*1024*1024, limit); max_rshare = min(6UL*1024*1024, limit); sysctl_tcp_wmem[0] = SK_MEM_QUANTUM; sysctl_tcp_wmem[1] = 16*1024; sysctl_tcp_wmem[2] = max(64*1024, max_wshare); sysctl_tcp_rmem[0] = SK_MEM_QUANTUM; sysctl_tcp_rmem[1] = 87380; sysctl_tcp_rmem[2] = max(87380, max_rshare); pr_info("Hash tables configured (established %u bind %u)\n", tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size); tcp_v4_init(); tcp_metrics_init(); BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0); tcp_tasklet_init(); }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_2768_0
crossvul-cpp_data_bad_967_0
// SPDX-License-Identifier: GPL-2.0-only /* * linux/drivers/block/floppy.c * * Copyright (C) 1991, 1992 Linus Torvalds * Copyright (C) 1993, 1994 Alain Knaff * Copyright (C) 1998 Alan Cox */ /* * 02.12.91 - Changed to static variables to indicate need for reset * and recalibrate. This makes some things easier (output_byte reset * checking etc), and means less interrupt jumping in case of errors, * so the code is hopefully easier to understand. */ /* * This file is certainly a mess. I've tried my best to get it working, * but I don't like programming floppies, and I have only one anyway. * Urgel. I should check for more errors, and do more graceful error * recovery. Seems there are problems with several drives. I've tried to * correct them. No promises. */ /* * As with hd.c, all routines within this file can (and will) be called * by interrupts, so extreme caution is needed. A hardware interrupt * handler may not sleep, or a kernel panic will happen. Thus I cannot * call "floppy-on" directly, but have to set a special timer interrupt * etc. */ /* * 28.02.92 - made track-buffering routines, based on the routines written * by entropy@wintermute.wpi.edu (Lawrence Foard). Linus. */ /* * Automatic floppy-detection and formatting written by Werner Almesberger * (almesber@nessie.cs.id.ethz.ch), who also corrected some problems with * the floppy-change signal detection. */ /* * 1992/7/22 -- Hennus Bergman: Added better error reporting, fixed * FDC data overrun bug, added some preliminary stuff for vertical * recording support. * * 1992/9/17: Added DMA allocation & DMA functions. -- hhb. * * TODO: Errors are still not counted properly. */ /* 1992/9/20 * Modifications for ``Sector Shifting'' by Rob Hooft (hooft@chem.ruu.nl) * modeled after the freeware MS-DOS program fdformat/88 V1.8 by * Christoph H. Hochst\"atter. * I have fixed the shift values to the ones I always use. Maybe a new * ioctl() should be created to be able to modify them. * There is a bug in the driver that makes it impossible to format a * floppy as the first thing after bootup. */ /* * 1993/4/29 -- Linus -- cleaned up the timer handling in the kernel, and * this helped the floppy driver as well. Much cleaner, and still seems to * work. */ /* 1994/6/24 --bbroad-- added the floppy table entries and made * minor modifications to allow 2.88 floppies to be run. */ /* 1994/7/13 -- Paul Vojta -- modified the probing code to allow three or more * disk types. */ /* * 1994/8/8 -- Alain Knaff -- Switched to fdpatch driver: Support for bigger * format bug fixes, but unfortunately some new bugs too... */ /* 1994/9/17 -- Koen Holtman -- added logging of physical floppy write * errors to allow safe writing by specialized programs. */ /* 1995/4/24 -- Dan Fandrich -- added support for Commodore 1581 3.5" disks * by defining bit 1 of the "stretch" parameter to mean put sectors on the * opposite side of the disk, leaving the sector IDs alone (i.e. Commodore's * drives are "upside-down"). */ /* * 1995/8/26 -- Andreas Busse -- added Mips support. */ /* * 1995/10/18 -- Ralf Baechle -- Portability cleanup; move machine dependent * features to asm/floppy.h. */ /* * 1998/1/21 -- Richard Gooch <rgooch@atnf.csiro.au> -- devfs support */ /* * 1998/05/07 -- Russell King -- More portability cleanups; moved definition of * interrupt and dma channel to asm/floppy.h. Cleaned up some formatting & * use of '0' for NULL. */ /* * 1998/06/07 -- Alan Cox -- Merged the 2.0.34 fixes for resource allocation * failures. */ /* * 1998/09/20 -- David Weinehall -- Added slow-down code for buggy PS/2-drives. */ /* * 1999/08/13 -- Paul Slootman -- floppy stopped working on Alpha after 24 * days, 6 hours, 32 minutes and 32 seconds (i.e. MAXINT jiffies; ints were * being used to store jiffies, which are unsigned longs). */ /* * 2000/08/28 -- Arnaldo Carvalho de Melo <acme@conectiva.com.br> * - get rid of check_region * - s/suser/capable/ */ /* * 2001/08/26 -- Paul Gortmaker - fix insmod oops on machines with no * floppy controller (lingering task on list after module is gone... boom.) */ /* * 2002/02/07 -- Anton Altaparmakov - Fix io ports reservation to correct range * (0x3f2-0x3f5, 0x3f7). This fix is a bit of a hack but the proper fix * requires many non-obvious changes in arch dependent code. */ /* 2003/07/28 -- Daniele Bellucci <bellucda@tiscali.it>. * Better audit of register_blkdev. */ #undef FLOPPY_SILENT_DCL_CLEAR #define REALLY_SLOW_IO #define DEBUGT 2 #define DPRINT(format, args...) \ pr_info("floppy%d: " format, current_drive, ##args) #define DCL_DEBUG /* debug disk change line */ #ifdef DCL_DEBUG #define debug_dcl(test, fmt, args...) \ do { if ((test) & FD_DEBUG) DPRINT(fmt, ##args); } while (0) #else #define debug_dcl(test, fmt, args...) \ do { if (0) DPRINT(fmt, ##args); } while (0) #endif /* do print messages for unexpected interrupts */ static int print_unex = 1; #include <linux/module.h> #include <linux/sched.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/timer.h> #include <linux/workqueue.h> #define FDPATCHES #include <linux/fdreg.h> #include <linux/fd.h> #include <linux/hdreg.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/bio.h> #include <linux/string.h> #include <linux/jiffies.h> #include <linux/fcntl.h> #include <linux/delay.h> #include <linux/mc146818rtc.h> /* CMOS defines */ #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/mod_devicetable.h> #include <linux/mutex.h> #include <linux/io.h> #include <linux/uaccess.h> #include <linux/async.h> #include <linux/compat.h> /* * PS/2 floppies have much slower step rates than regular floppies. * It's been recommended that take about 1/4 of the default speed * in some more extreme cases. */ static DEFINE_MUTEX(floppy_mutex); static int slow_floppy; #include <asm/dma.h> #include <asm/irq.h> static int FLOPPY_IRQ = 6; static int FLOPPY_DMA = 2; static int can_use_virtual_dma = 2; /* ======= * can use virtual DMA: * 0 = use of virtual DMA disallowed by config * 1 = use of virtual DMA prescribed by config * 2 = no virtual DMA preference configured. By default try hard DMA, * but fall back on virtual DMA when not enough memory available */ static int use_virtual_dma; /* ======= * use virtual DMA * 0 using hard DMA * 1 using virtual DMA * This variable is set to virtual when a DMA mem problem arises, and * reset back in floppy_grab_irq_and_dma. * It is not safe to reset it in other circumstances, because the floppy * driver may have several buffers in use at once, and we do currently not * record each buffers capabilities */ static DEFINE_SPINLOCK(floppy_lock); static unsigned short virtual_dma_port = 0x3f0; irqreturn_t floppy_interrupt(int irq, void *dev_id); static int set_dor(int fdc, char mask, char data); #define K_64 0x10000 /* 64KB */ /* the following is the mask of allowed drives. By default units 2 and * 3 of both floppy controllers are disabled, because switching on the * motor of these drives causes system hangs on some PCI computers. drive * 0 is the low bit (0x1), and drive 7 is the high bit (0x80). Bits are on if * a drive is allowed. * * NOTE: This must come before we include the arch floppy header because * some ports reference this variable from there. -DaveM */ static int allowed_drive_mask = 0x33; #include <asm/floppy.h> static int irqdma_allocated; #include <linux/blk-mq.h> #include <linux/blkpg.h> #include <linux/cdrom.h> /* for the compatibility eject ioctl */ #include <linux/completion.h> static LIST_HEAD(floppy_reqs); static struct request *current_req; static int set_next_request(void); #ifndef fd_get_dma_residue #define fd_get_dma_residue() get_dma_residue(FLOPPY_DMA) #endif /* Dma Memory related stuff */ #ifndef fd_dma_mem_free #define fd_dma_mem_free(addr, size) free_pages(addr, get_order(size)) #endif #ifndef fd_dma_mem_alloc #define fd_dma_mem_alloc(size) __get_dma_pages(GFP_KERNEL, get_order(size)) #endif #ifndef fd_cacheflush #define fd_cacheflush(addr, size) /* nothing... */ #endif static inline void fallback_on_nodma_alloc(char **addr, size_t l) { #ifdef FLOPPY_CAN_FALLBACK_ON_NODMA if (*addr) return; /* we have the memory */ if (can_use_virtual_dma != 2) return; /* no fallback allowed */ pr_info("DMA memory shortage. Temporarily falling back on virtual DMA\n"); *addr = (char *)nodma_mem_alloc(l); #else return; #endif } /* End dma memory related stuff */ static unsigned long fake_change; static bool initialized; #define ITYPE(x) (((x) >> 2) & 0x1f) #define TOMINOR(x) ((x & 3) | ((x & 4) << 5)) #define UNIT(x) ((x) & 0x03) /* drive on fdc */ #define FDC(x) (((x) & 0x04) >> 2) /* fdc of drive */ /* reverse mapping from unit and fdc to drive */ #define REVDRIVE(fdc, unit) ((unit) + ((fdc) << 2)) #define DP (&drive_params[current_drive]) #define DRS (&drive_state[current_drive]) #define DRWE (&write_errors[current_drive]) #define FDCS (&fdc_state[fdc]) #define UDP (&drive_params[drive]) #define UDRS (&drive_state[drive]) #define UDRWE (&write_errors[drive]) #define UFDCS (&fdc_state[FDC(drive)]) #define PH_HEAD(floppy, head) (((((floppy)->stretch & 2) >> 1) ^ head) << 2) #define STRETCH(floppy) ((floppy)->stretch & FD_STRETCH) /* read/write */ #define COMMAND (raw_cmd->cmd[0]) #define DR_SELECT (raw_cmd->cmd[1]) #define TRACK (raw_cmd->cmd[2]) #define HEAD (raw_cmd->cmd[3]) #define SECTOR (raw_cmd->cmd[4]) #define SIZECODE (raw_cmd->cmd[5]) #define SECT_PER_TRACK (raw_cmd->cmd[6]) #define GAP (raw_cmd->cmd[7]) #define SIZECODE2 (raw_cmd->cmd[8]) #define NR_RW 9 /* format */ #define F_SIZECODE (raw_cmd->cmd[2]) #define F_SECT_PER_TRACK (raw_cmd->cmd[3]) #define F_GAP (raw_cmd->cmd[4]) #define F_FILL (raw_cmd->cmd[5]) #define NR_F 6 /* * Maximum disk size (in kilobytes). * This default is used whenever the current disk size is unknown. * [Now it is rather a minimum] */ #define MAX_DISK_SIZE 4 /* 3984 */ /* * globals used by 'result()' */ #define MAX_REPLIES 16 static unsigned char reply_buffer[MAX_REPLIES]; static int inr; /* size of reply buffer, when called from interrupt */ #define ST0 (reply_buffer[0]) #define ST1 (reply_buffer[1]) #define ST2 (reply_buffer[2]) #define ST3 (reply_buffer[0]) /* result of GETSTATUS */ #define R_TRACK (reply_buffer[3]) #define R_HEAD (reply_buffer[4]) #define R_SECTOR (reply_buffer[5]) #define R_SIZECODE (reply_buffer[6]) #define SEL_DLY (2 * HZ / 100) /* * this struct defines the different floppy drive types. */ static struct { struct floppy_drive_params params; const char *name; /* name printed while booting */ } default_drive_params[] = { /* NOTE: the time values in jiffies should be in msec! CMOS drive type | Maximum data rate supported by drive type | | Head load time, msec | | | Head unload time, msec (not used) | | | | Step rate interval, usec | | | | | Time needed for spinup time (jiffies) | | | | | | Timeout for spinning down (jiffies) | | | | | | | Spindown offset (where disk stops) | | | | | | | | Select delay | | | | | | | | | RPS | | | | | | | | | | Max number of tracks | | | | | | | | | | | Interrupt timeout | | | | | | | | | | | | Max nonintlv. sectors | | | | | | | | | | | | | -Max Errors- flags */ {{0, 500, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 80, 3*HZ, 20, {3,1,2,0,2}, 0, 0, { 7, 4, 8, 2, 1, 5, 3,10}, 3*HZ/2, 0 }, "unknown" }, {{1, 300, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 40, 3*HZ, 17, {3,1,2,0,2}, 0, 0, { 1, 0, 0, 0, 0, 0, 0, 0}, 3*HZ/2, 1 }, "360K PC" }, /*5 1/4 360 KB PC*/ {{2, 500, 16, 16, 6000, 4*HZ/10, 3*HZ, 14, SEL_DLY, 6, 83, 3*HZ, 17, {3,1,2,0,2}, 0, 0, { 2, 5, 6,23,10,20,12, 0}, 3*HZ/2, 2 }, "1.2M" }, /*5 1/4 HD AT*/ {{3, 250, 16, 16, 3000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0, 0, { 4,22,21,30, 3, 0, 0, 0}, 3*HZ/2, 4 }, "720k" }, /*3 1/2 DD*/ {{4, 500, 16, 16, 4000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0, 0, { 7, 4,25,22,31,21,29,11}, 3*HZ/2, 7 }, "1.44M" }, /*3 1/2 HD*/ {{5, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0, 0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M AMI BIOS" }, /*3 1/2 ED*/ {{6, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0, 0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M" } /*3 1/2 ED*/ /* | --autodetected formats--- | | | * read_track | | Name printed when booting * | Native format * Frequency of disk change checks */ }; static struct floppy_drive_params drive_params[N_DRIVE]; static struct floppy_drive_struct drive_state[N_DRIVE]; static struct floppy_write_errors write_errors[N_DRIVE]; static struct timer_list motor_off_timer[N_DRIVE]; static struct gendisk *disks[N_DRIVE]; static struct blk_mq_tag_set tag_sets[N_DRIVE]; static struct block_device *opened_bdev[N_DRIVE]; static DEFINE_MUTEX(open_lock); static struct floppy_raw_cmd *raw_cmd, default_raw_cmd; /* * This struct defines the different floppy types. * * Bit 0 of 'stretch' tells if the tracks need to be doubled for some * types (e.g. 360kB diskette in 1.2MB drive, etc.). Bit 1 of 'stretch' * tells if the disk is in Commodore 1581 format, which means side 0 sectors * are located on side 1 of the disk but with a side 0 ID, and vice-versa. * This is the same as the Sharp MZ-80 5.25" CP/M disk format, except that the * 1581's logical side 0 is on physical side 1, whereas the Sharp's logical * side 0 is on physical side 0 (but with the misnamed sector IDs). * 'stretch' should probably be renamed to something more general, like * 'options'. * * Bits 2 through 9 of 'stretch' tell the number of the first sector. * The LSB (bit 2) is flipped. For most disks, the first sector * is 1 (represented by 0x00<<2). For some CP/M and music sampler * disks (such as Ensoniq EPS 16plus) it is 0 (represented as 0x01<<2). * For Amstrad CPC disks it is 0xC1 (represented as 0xC0<<2). * * Other parameters should be self-explanatory (see also setfdprm(8)). */ /* Size | Sectors per track | | Head | | | Tracks | | | | Stretch | | | | | Gap 1 size | | | | | | Data rate, | 0x40 for perp | | | | | | | Spec1 (stepping rate, head unload | | | | | | | | /fmt gap (gap2) */ static struct floppy_struct floppy_type[32] = { { 0, 0,0, 0,0,0x00,0x00,0x00,0x00,NULL }, /* 0 no testing */ { 720, 9,2,40,0,0x2A,0x02,0xDF,0x50,"d360" }, /* 1 360KB PC */ { 2400,15,2,80,0,0x1B,0x00,0xDF,0x54,"h1200" }, /* 2 1.2MB AT */ { 720, 9,1,80,0,0x2A,0x02,0xDF,0x50,"D360" }, /* 3 360KB SS 3.5" */ { 1440, 9,2,80,0,0x2A,0x02,0xDF,0x50,"D720" }, /* 4 720KB 3.5" */ { 720, 9,2,40,1,0x23,0x01,0xDF,0x50,"h360" }, /* 5 360KB AT */ { 1440, 9,2,80,0,0x23,0x01,0xDF,0x50,"h720" }, /* 6 720KB AT */ { 2880,18,2,80,0,0x1B,0x00,0xCF,0x6C,"H1440" }, /* 7 1.44MB 3.5" */ { 5760,36,2,80,0,0x1B,0x43,0xAF,0x54,"E2880" }, /* 8 2.88MB 3.5" */ { 6240,39,2,80,0,0x1B,0x43,0xAF,0x28,"E3120" }, /* 9 3.12MB 3.5" */ { 2880,18,2,80,0,0x25,0x00,0xDF,0x02,"h1440" }, /* 10 1.44MB 5.25" */ { 3360,21,2,80,0,0x1C,0x00,0xCF,0x0C,"H1680" }, /* 11 1.68MB 3.5" */ { 820,10,2,41,1,0x25,0x01,0xDF,0x2E,"h410" }, /* 12 410KB 5.25" */ { 1640,10,2,82,0,0x25,0x02,0xDF,0x2E,"H820" }, /* 13 820KB 3.5" */ { 2952,18,2,82,0,0x25,0x00,0xDF,0x02,"h1476" }, /* 14 1.48MB 5.25" */ { 3444,21,2,82,0,0x25,0x00,0xDF,0x0C,"H1722" }, /* 15 1.72MB 3.5" */ { 840,10,2,42,1,0x25,0x01,0xDF,0x2E,"h420" }, /* 16 420KB 5.25" */ { 1660,10,2,83,0,0x25,0x02,0xDF,0x2E,"H830" }, /* 17 830KB 3.5" */ { 2988,18,2,83,0,0x25,0x00,0xDF,0x02,"h1494" }, /* 18 1.49MB 5.25" */ { 3486,21,2,83,0,0x25,0x00,0xDF,0x0C,"H1743" }, /* 19 1.74 MB 3.5" */ { 1760,11,2,80,0,0x1C,0x09,0xCF,0x00,"h880" }, /* 20 880KB 5.25" */ { 2080,13,2,80,0,0x1C,0x01,0xCF,0x00,"D1040" }, /* 21 1.04MB 3.5" */ { 2240,14,2,80,0,0x1C,0x19,0xCF,0x00,"D1120" }, /* 22 1.12MB 3.5" */ { 3200,20,2,80,0,0x1C,0x20,0xCF,0x2C,"h1600" }, /* 23 1.6MB 5.25" */ { 3520,22,2,80,0,0x1C,0x08,0xCF,0x2e,"H1760" }, /* 24 1.76MB 3.5" */ { 3840,24,2,80,0,0x1C,0x20,0xCF,0x00,"H1920" }, /* 25 1.92MB 3.5" */ { 6400,40,2,80,0,0x25,0x5B,0xCF,0x00,"E3200" }, /* 26 3.20MB 3.5" */ { 7040,44,2,80,0,0x25,0x5B,0xCF,0x00,"E3520" }, /* 27 3.52MB 3.5" */ { 7680,48,2,80,0,0x25,0x63,0xCF,0x00,"E3840" }, /* 28 3.84MB 3.5" */ { 3680,23,2,80,0,0x1C,0x10,0xCF,0x00,"H1840" }, /* 29 1.84MB 3.5" */ { 1600,10,2,80,0,0x25,0x02,0xDF,0x2E,"D800" }, /* 30 800KB 3.5" */ { 3200,20,2,80,0,0x1C,0x00,0xCF,0x2C,"H1600" }, /* 31 1.6MB 3.5" */ }; #define SECTSIZE (_FD_SECTSIZE(*floppy)) /* Auto-detection: Disk type used until the next media change occurs. */ static struct floppy_struct *current_type[N_DRIVE]; /* * User-provided type information. current_type points to * the respective entry of this array. */ static struct floppy_struct user_params[N_DRIVE]; static sector_t floppy_sizes[256]; static char floppy_device_name[] = "floppy"; /* * The driver is trying to determine the correct media format * while probing is set. rw_interrupt() clears it after a * successful access. */ static int probing; /* Synchronization of FDC access. */ #define FD_COMMAND_NONE -1 #define FD_COMMAND_ERROR 2 #define FD_COMMAND_OKAY 3 static volatile int command_status = FD_COMMAND_NONE; static unsigned long fdc_busy; static DECLARE_WAIT_QUEUE_HEAD(fdc_wait); static DECLARE_WAIT_QUEUE_HEAD(command_done); /* Errors during formatting are counted here. */ static int format_errors; /* Format request descriptor. */ static struct format_descr format_req; /* * Rate is 0 for 500kb/s, 1 for 300kbps, 2 for 250kbps * Spec1 is 0xSH, where S is stepping rate (F=1ms, E=2ms, D=3ms etc), * H is head unload time (1=16ms, 2=32ms, etc) */ /* * Track buffer * Because these are written to by the DMA controller, they must * not contain a 64k byte boundary crossing, or data will be * corrupted/lost. */ static char *floppy_track_buffer; static int max_buffer_sectors; static int *errors; typedef void (*done_f)(int); static const struct cont_t { void (*interrupt)(void); /* this is called after the interrupt of the * main command */ void (*redo)(void); /* this is called to retry the operation */ void (*error)(void); /* this is called to tally an error */ done_f done; /* this is called to say if the operation has * succeeded/failed */ } *cont; static void floppy_ready(void); static void floppy_start(void); static void process_fd_request(void); static void recalibrate_floppy(void); static void floppy_shutdown(struct work_struct *); static int floppy_request_regions(int); static void floppy_release_regions(int); static int floppy_grab_irq_and_dma(void); static void floppy_release_irq_and_dma(void); /* * The "reset" variable should be tested whenever an interrupt is scheduled, * after the commands have been sent. This is to ensure that the driver doesn't * get wedged when the interrupt doesn't come because of a failed command. * reset doesn't need to be tested before sending commands, because * output_byte is automatically disabled when reset is set. */ static void reset_fdc(void); /* * These are global variables, as that's the easiest way to give * information to interrupts. They are the data used for the current * request. */ #define NO_TRACK -1 #define NEED_1_RECAL -2 #define NEED_2_RECAL -3 static atomic_t usage_count = ATOMIC_INIT(0); /* buffer related variables */ static int buffer_track = -1; static int buffer_drive = -1; static int buffer_min = -1; static int buffer_max = -1; /* fdc related variables, should end up in a struct */ static struct floppy_fdc_state fdc_state[N_FDC]; static int fdc; /* current fdc */ static struct workqueue_struct *floppy_wq; static struct floppy_struct *_floppy = floppy_type; static unsigned char current_drive; static long current_count_sectors; static unsigned char fsector_t; /* sector in track */ static unsigned char in_sector_offset; /* offset within physical sector, * expressed in units of 512 bytes */ static inline bool drive_no_geom(int drive) { return !current_type[drive] && !ITYPE(UDRS->fd_device); } #ifndef fd_eject static inline int fd_eject(int drive) { return -EINVAL; } #endif /* * Debugging * ========= */ #ifdef DEBUGT static long unsigned debugtimer; static inline void set_debugt(void) { debugtimer = jiffies; } static inline void debugt(const char *func, const char *msg) { if (DP->flags & DEBUGT) pr_info("%s:%s dtime=%lu\n", func, msg, jiffies - debugtimer); } #else static inline void set_debugt(void) { } static inline void debugt(const char *func, const char *msg) { } #endif /* DEBUGT */ static DECLARE_DELAYED_WORK(fd_timeout, floppy_shutdown); static const char *timeout_message; static void is_alive(const char *func, const char *message) { /* this routine checks whether the floppy driver is "alive" */ if (test_bit(0, &fdc_busy) && command_status < 2 && !delayed_work_pending(&fd_timeout)) { DPRINT("%s: timeout handler died. %s\n", func, message); } } static void (*do_floppy)(void) = NULL; #define OLOGSIZE 20 static void (*lasthandler)(void); static unsigned long interruptjiffies; static unsigned long resultjiffies; static int resultsize; static unsigned long lastredo; static struct output_log { unsigned char data; unsigned char status; unsigned long jiffies; } output_log[OLOGSIZE]; static int output_log_pos; #define current_reqD -1 #define MAXTIMEOUT -2 static void __reschedule_timeout(int drive, const char *message) { unsigned long delay; if (drive == current_reqD) drive = current_drive; if (drive < 0 || drive >= N_DRIVE) { delay = 20UL * HZ; drive = 0; } else delay = UDP->timeout; mod_delayed_work(floppy_wq, &fd_timeout, delay); if (UDP->flags & FD_DEBUG) DPRINT("reschedule timeout %s\n", message); timeout_message = message; } static void reschedule_timeout(int drive, const char *message) { unsigned long flags; spin_lock_irqsave(&floppy_lock, flags); __reschedule_timeout(drive, message); spin_unlock_irqrestore(&floppy_lock, flags); } #define INFBOUND(a, b) (a) = max_t(int, a, b) #define SUPBOUND(a, b) (a) = min_t(int, a, b) /* * Bottom half floppy driver. * ========================== * * This part of the file contains the code talking directly to the hardware, * and also the main service loop (seek-configure-spinup-command) */ /* * disk change. * This routine is responsible for maintaining the FD_DISK_CHANGE flag, * and the last_checked date. * * last_checked is the date of the last check which showed 'no disk change' * FD_DISK_CHANGE is set under two conditions: * 1. The floppy has been changed after some i/o to that floppy already * took place. * 2. No floppy disk is in the drive. This is done in order to ensure that * requests are quickly flushed in case there is no disk in the drive. It * follows that FD_DISK_CHANGE can only be cleared if there is a disk in * the drive. * * For 1., maxblock is observed. Maxblock is 0 if no i/o has taken place yet. * For 2., FD_DISK_NEWCHANGE is watched. FD_DISK_NEWCHANGE is cleared on * each seek. If a disk is present, the disk change line should also be * cleared on each seek. Thus, if FD_DISK_NEWCHANGE is clear, but the disk * change line is set, this means either that no disk is in the drive, or * that it has been removed since the last seek. * * This means that we really have a third possibility too: * The floppy has been changed after the last seek. */ static int disk_change(int drive) { int fdc = FDC(drive); if (time_before(jiffies, UDRS->select_date + UDP->select_delay)) DPRINT("WARNING disk change called early\n"); if (!(FDCS->dor & (0x10 << UNIT(drive))) || (FDCS->dor & 3) != UNIT(drive) || fdc != FDC(drive)) { DPRINT("probing disk change on unselected drive\n"); DPRINT("drive=%d fdc=%d dor=%x\n", drive, FDC(drive), (unsigned int)FDCS->dor); } debug_dcl(UDP->flags, "checking disk change line for drive %d\n", drive); debug_dcl(UDP->flags, "jiffies=%lu\n", jiffies); debug_dcl(UDP->flags, "disk change line=%x\n", fd_inb(FD_DIR) & 0x80); debug_dcl(UDP->flags, "flags=%lx\n", UDRS->flags); if (UDP->flags & FD_BROKEN_DCL) return test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); if ((fd_inb(FD_DIR) ^ UDP->flags) & 0x80) { set_bit(FD_VERIFY_BIT, &UDRS->flags); /* verify write protection */ if (UDRS->maxblock) /* mark it changed */ set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); /* invalidate its geometry */ if (UDRS->keep_data >= 0) { if ((UDP->flags & FTD_MSG) && current_type[drive] != NULL) DPRINT("Disk type is undefined after disk change\n"); current_type[drive] = NULL; floppy_sizes[TOMINOR(drive)] = MAX_DISK_SIZE << 1; } return 1; } else { UDRS->last_checked = jiffies; clear_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags); } return 0; } static inline int is_selected(int dor, int unit) { return ((dor & (0x10 << unit)) && (dor & 3) == unit); } static bool is_ready_state(int status) { int state = status & (STATUS_READY | STATUS_DIR | STATUS_DMA); return state == STATUS_READY; } static int set_dor(int fdc, char mask, char data) { unsigned char unit; unsigned char drive; unsigned char newdor; unsigned char olddor; if (FDCS->address == -1) return -1; olddor = FDCS->dor; newdor = (olddor & mask) | data; if (newdor != olddor) { unit = olddor & 0x3; if (is_selected(olddor, unit) && !is_selected(newdor, unit)) { drive = REVDRIVE(fdc, unit); debug_dcl(UDP->flags, "calling disk change from set_dor\n"); disk_change(drive); } FDCS->dor = newdor; fd_outb(newdor, FD_DOR); unit = newdor & 0x3; if (!is_selected(olddor, unit) && is_selected(newdor, unit)) { drive = REVDRIVE(fdc, unit); UDRS->select_date = jiffies; } } return olddor; } static void twaddle(void) { if (DP->select_delay) return; fd_outb(FDCS->dor & ~(0x10 << UNIT(current_drive)), FD_DOR); fd_outb(FDCS->dor, FD_DOR); DRS->select_date = jiffies; } /* * Reset all driver information about the current fdc. * This is needed after a reset, and after a raw command. */ static void reset_fdc_info(int mode) { int drive; FDCS->spec1 = FDCS->spec2 = -1; FDCS->need_configure = 1; FDCS->perp_mode = 1; FDCS->rawcmd = 0; for (drive = 0; drive < N_DRIVE; drive++) if (FDC(drive) == fdc && (mode || UDRS->track != NEED_1_RECAL)) UDRS->track = NEED_2_RECAL; } /* selects the fdc and drive, and enables the fdc's input/dma. */ static void set_fdc(int drive) { if (drive >= 0 && drive < N_DRIVE) { fdc = FDC(drive); current_drive = drive; } if (fdc != 1 && fdc != 0) { pr_info("bad fdc value\n"); return; } set_dor(fdc, ~0, 8); #if N_FDC > 1 set_dor(1 - fdc, ~8, 0); #endif if (FDCS->rawcmd == 2) reset_fdc_info(1); if (fd_inb(FD_STATUS) != STATUS_READY) FDCS->reset = 1; } /* locks the driver */ static int lock_fdc(int drive) { if (WARN(atomic_read(&usage_count) == 0, "Trying to lock fdc while usage count=0\n")) return -1; if (wait_event_interruptible(fdc_wait, !test_and_set_bit(0, &fdc_busy))) return -EINTR; command_status = FD_COMMAND_NONE; reschedule_timeout(drive, "lock fdc"); set_fdc(drive); return 0; } /* unlocks the driver */ static void unlock_fdc(void) { if (!test_bit(0, &fdc_busy)) DPRINT("FDC access conflict!\n"); raw_cmd = NULL; command_status = FD_COMMAND_NONE; cancel_delayed_work(&fd_timeout); do_floppy = NULL; cont = NULL; clear_bit(0, &fdc_busy); wake_up(&fdc_wait); } /* switches the motor off after a given timeout */ static void motor_off_callback(struct timer_list *t) { unsigned long nr = t - motor_off_timer; unsigned char mask = ~(0x10 << UNIT(nr)); if (WARN_ON_ONCE(nr >= N_DRIVE)) return; set_dor(FDC(nr), mask, 0); } /* schedules motor off */ static void floppy_off(unsigned int drive) { unsigned long volatile delta; int fdc = FDC(drive); if (!(FDCS->dor & (0x10 << UNIT(drive)))) return; del_timer(motor_off_timer + drive); /* make spindle stop in a position which minimizes spinup time * next time */ if (UDP->rps) { delta = jiffies - UDRS->first_read_date + HZ - UDP->spindown_offset; delta = ((delta * UDP->rps) % HZ) / UDP->rps; motor_off_timer[drive].expires = jiffies + UDP->spindown - delta; } add_timer(motor_off_timer + drive); } /* * cycle through all N_DRIVE floppy drives, for disk change testing. * stopping at current drive. This is done before any long operation, to * be sure to have up to date disk change information. */ static void scandrives(void) { int i; int drive; int saved_drive; if (DP->select_delay) return; saved_drive = current_drive; for (i = 0; i < N_DRIVE; i++) { drive = (saved_drive + i + 1) % N_DRIVE; if (UDRS->fd_ref == 0 || UDP->select_delay != 0) continue; /* skip closed drives */ set_fdc(drive); if (!(set_dor(fdc, ~3, UNIT(drive) | (0x10 << UNIT(drive))) & (0x10 << UNIT(drive)))) /* switch the motor off again, if it was off to * begin with */ set_dor(fdc, ~(0x10 << UNIT(drive)), 0); } set_fdc(saved_drive); } static void empty(void) { } static void (*floppy_work_fn)(void); static void floppy_work_workfn(struct work_struct *work) { floppy_work_fn(); } static DECLARE_WORK(floppy_work, floppy_work_workfn); static void schedule_bh(void (*handler)(void)) { WARN_ON(work_pending(&floppy_work)); floppy_work_fn = handler; queue_work(floppy_wq, &floppy_work); } static void (*fd_timer_fn)(void) = NULL; static void fd_timer_workfn(struct work_struct *work) { fd_timer_fn(); } static DECLARE_DELAYED_WORK(fd_timer, fd_timer_workfn); static void cancel_activity(void) { do_floppy = NULL; cancel_delayed_work_sync(&fd_timer); cancel_work_sync(&floppy_work); } /* this function makes sure that the disk stays in the drive during the * transfer */ static void fd_watchdog(void) { debug_dcl(DP->flags, "calling disk change from watchdog\n"); if (disk_change(current_drive)) { DPRINT("disk removed during i/o\n"); cancel_activity(); cont->done(0); reset_fdc(); } else { cancel_delayed_work(&fd_timer); fd_timer_fn = fd_watchdog; queue_delayed_work(floppy_wq, &fd_timer, HZ / 10); } } static void main_command_interrupt(void) { cancel_delayed_work(&fd_timer); cont->interrupt(); } /* waits for a delay (spinup or select) to pass */ static int fd_wait_for_completion(unsigned long expires, void (*function)(void)) { if (FDCS->reset) { reset_fdc(); /* do the reset during sleep to win time * if we don't need to sleep, it's a good * occasion anyways */ return 1; } if (time_before(jiffies, expires)) { cancel_delayed_work(&fd_timer); fd_timer_fn = function; queue_delayed_work(floppy_wq, &fd_timer, expires - jiffies); return 1; } return 0; } static void setup_DMA(void) { unsigned long f; if (raw_cmd->length == 0) { int i; pr_info("zero dma transfer size:"); for (i = 0; i < raw_cmd->cmd_count; i++) pr_cont("%x,", raw_cmd->cmd[i]); pr_cont("\n"); cont->done(0); FDCS->reset = 1; return; } if (((unsigned long)raw_cmd->kernel_data) % 512) { pr_info("non aligned address: %p\n", raw_cmd->kernel_data); cont->done(0); FDCS->reset = 1; return; } f = claim_dma_lock(); fd_disable_dma(); #ifdef fd_dma_setup if (fd_dma_setup(raw_cmd->kernel_data, raw_cmd->length, (raw_cmd->flags & FD_RAW_READ) ? DMA_MODE_READ : DMA_MODE_WRITE, FDCS->address) < 0) { release_dma_lock(f); cont->done(0); FDCS->reset = 1; return; } release_dma_lock(f); #else fd_clear_dma_ff(); fd_cacheflush(raw_cmd->kernel_data, raw_cmd->length); fd_set_dma_mode((raw_cmd->flags & FD_RAW_READ) ? DMA_MODE_READ : DMA_MODE_WRITE); fd_set_dma_addr(raw_cmd->kernel_data); fd_set_dma_count(raw_cmd->length); virtual_dma_port = FDCS->address; fd_enable_dma(); release_dma_lock(f); #endif } static void show_floppy(void); /* waits until the fdc becomes ready */ static int wait_til_ready(void) { int status; int counter; if (FDCS->reset) return -1; for (counter = 0; counter < 10000; counter++) { status = fd_inb(FD_STATUS); if (status & STATUS_READY) return status; } if (initialized) { DPRINT("Getstatus times out (%x) on fdc %d\n", status, fdc); show_floppy(); } FDCS->reset = 1; return -1; } /* sends a command byte to the fdc */ static int output_byte(char byte) { int status = wait_til_ready(); if (status < 0) return -1; if (is_ready_state(status)) { fd_outb(byte, FD_DATA); output_log[output_log_pos].data = byte; output_log[output_log_pos].status = status; output_log[output_log_pos].jiffies = jiffies; output_log_pos = (output_log_pos + 1) % OLOGSIZE; return 0; } FDCS->reset = 1; if (initialized) { DPRINT("Unable to send byte %x to FDC. Fdc=%x Status=%x\n", byte, fdc, status); show_floppy(); } return -1; } /* gets the response from the fdc */ static int result(void) { int i; int status = 0; for (i = 0; i < MAX_REPLIES; i++) { status = wait_til_ready(); if (status < 0) break; status &= STATUS_DIR | STATUS_READY | STATUS_BUSY | STATUS_DMA; if ((status & ~STATUS_BUSY) == STATUS_READY) { resultjiffies = jiffies; resultsize = i; return i; } if (status == (STATUS_DIR | STATUS_READY | STATUS_BUSY)) reply_buffer[i] = fd_inb(FD_DATA); else break; } if (initialized) { DPRINT("get result error. Fdc=%d Last status=%x Read bytes=%d\n", fdc, status, i); show_floppy(); } FDCS->reset = 1; return -1; } #define MORE_OUTPUT -2 /* does the fdc need more output? */ static int need_more_output(void) { int status = wait_til_ready(); if (status < 0) return -1; if (is_ready_state(status)) return MORE_OUTPUT; return result(); } /* Set perpendicular mode as required, based on data rate, if supported. * 82077 Now tested. 1Mbps data rate only possible with 82077-1. */ static void perpendicular_mode(void) { unsigned char perp_mode; if (raw_cmd->rate & 0x40) { switch (raw_cmd->rate & 3) { case 0: perp_mode = 2; break; case 3: perp_mode = 3; break; default: DPRINT("Invalid data rate for perpendicular mode!\n"); cont->done(0); FDCS->reset = 1; /* * convenient way to return to * redo without too much hassle * (deep stack et al.) */ return; } } else perp_mode = 0; if (FDCS->perp_mode == perp_mode) return; if (FDCS->version >= FDC_82077_ORIG) { output_byte(FD_PERPENDICULAR); output_byte(perp_mode); FDCS->perp_mode = perp_mode; } else if (perp_mode) { DPRINT("perpendicular mode not supported by this FDC.\n"); } } /* perpendicular_mode */ static int fifo_depth = 0xa; static int no_fifo; static int fdc_configure(void) { /* Turn on FIFO */ output_byte(FD_CONFIGURE); if (need_more_output() != MORE_OUTPUT) return 0; output_byte(0); output_byte(0x10 | (no_fifo & 0x20) | (fifo_depth & 0xf)); output_byte(0); /* pre-compensation from track 0 upwards */ return 1; } #define NOMINAL_DTR 500 /* Issue a "SPECIFY" command to set the step rate time, head unload time, * head load time, and DMA disable flag to values needed by floppy. * * The value "dtr" is the data transfer rate in Kbps. It is needed * to account for the data rate-based scaling done by the 82072 and 82077 * FDC types. This parameter is ignored for other types of FDCs (i.e. * 8272a). * * Note that changing the data transfer rate has a (probably deleterious) * effect on the parameters subject to scaling for 82072/82077 FDCs, so * fdc_specify is called again after each data transfer rate * change. * * srt: 1000 to 16000 in microseconds * hut: 16 to 240 milliseconds * hlt: 2 to 254 milliseconds * * These values are rounded up to the next highest available delay time. */ static void fdc_specify(void) { unsigned char spec1; unsigned char spec2; unsigned long srt; unsigned long hlt; unsigned long hut; unsigned long dtr = NOMINAL_DTR; unsigned long scale_dtr = NOMINAL_DTR; int hlt_max_code = 0x7f; int hut_max_code = 0xf; if (FDCS->need_configure && FDCS->version >= FDC_82072A) { fdc_configure(); FDCS->need_configure = 0; } switch (raw_cmd->rate & 0x03) { case 3: dtr = 1000; break; case 1: dtr = 300; if (FDCS->version >= FDC_82078) { /* chose the default rate table, not the one * where 1 = 2 Mbps */ output_byte(FD_DRIVESPEC); if (need_more_output() == MORE_OUTPUT) { output_byte(UNIT(current_drive)); output_byte(0xc0); } } break; case 2: dtr = 250; break; } if (FDCS->version >= FDC_82072) { scale_dtr = dtr; hlt_max_code = 0x00; /* 0==256msec*dtr0/dtr (not linear!) */ hut_max_code = 0x0; /* 0==256msec*dtr0/dtr (not linear!) */ } /* Convert step rate from microseconds to milliseconds and 4 bits */ srt = 16 - DIV_ROUND_UP(DP->srt * scale_dtr / 1000, NOMINAL_DTR); if (slow_floppy) srt = srt / 4; SUPBOUND(srt, 0xf); INFBOUND(srt, 0); hlt = DIV_ROUND_UP(DP->hlt * scale_dtr / 2, NOMINAL_DTR); if (hlt < 0x01) hlt = 0x01; else if (hlt > 0x7f) hlt = hlt_max_code; hut = DIV_ROUND_UP(DP->hut * scale_dtr / 16, NOMINAL_DTR); if (hut < 0x1) hut = 0x1; else if (hut > 0xf) hut = hut_max_code; spec1 = (srt << 4) | hut; spec2 = (hlt << 1) | (use_virtual_dma & 1); /* If these parameters did not change, just return with success */ if (FDCS->spec1 != spec1 || FDCS->spec2 != spec2) { /* Go ahead and set spec1 and spec2 */ output_byte(FD_SPECIFY); output_byte(FDCS->spec1 = spec1); output_byte(FDCS->spec2 = spec2); } } /* fdc_specify */ /* Set the FDC's data transfer rate on behalf of the specified drive. * NOTE: with 82072/82077 FDCs, changing the data rate requires a reissue * of the specify command (i.e. using the fdc_specify function). */ static int fdc_dtr(void) { /* If data rate not already set to desired value, set it. */ if ((raw_cmd->rate & 3) == FDCS->dtr) return 0; /* Set dtr */ fd_outb(raw_cmd->rate & 3, FD_DCR); /* TODO: some FDC/drive combinations (C&T 82C711 with TEAC 1.2MB) * need a stabilization period of several milliseconds to be * enforced after data rate changes before R/W operations. * Pause 5 msec to avoid trouble. (Needs to be 2 jiffies) */ FDCS->dtr = raw_cmd->rate & 3; return fd_wait_for_completion(jiffies + 2UL * HZ / 100, floppy_ready); } /* fdc_dtr */ static void tell_sector(void) { pr_cont(": track %d, head %d, sector %d, size %d", R_TRACK, R_HEAD, R_SECTOR, R_SIZECODE); } /* tell_sector */ static void print_errors(void) { DPRINT(""); if (ST0 & ST0_ECE) { pr_cont("Recalibrate failed!"); } else if (ST2 & ST2_CRC) { pr_cont("data CRC error"); tell_sector(); } else if (ST1 & ST1_CRC) { pr_cont("CRC error"); tell_sector(); } else if ((ST1 & (ST1_MAM | ST1_ND)) || (ST2 & ST2_MAM)) { if (!probing) { pr_cont("sector not found"); tell_sector(); } else pr_cont("probe failed..."); } else if (ST2 & ST2_WC) { /* seek error */ pr_cont("wrong cylinder"); } else if (ST2 & ST2_BC) { /* cylinder marked as bad */ pr_cont("bad cylinder"); } else { pr_cont("unknown error. ST[0..2] are: 0x%x 0x%x 0x%x", ST0, ST1, ST2); tell_sector(); } pr_cont("\n"); } /* * OK, this error interpreting routine is called after a * DMA read/write has succeeded * or failed, so we check the results, and copy any buffers. * hhb: Added better error reporting. * ak: Made this into a separate routine. */ static int interpret_errors(void) { char bad; if (inr != 7) { DPRINT("-- FDC reply error\n"); FDCS->reset = 1; return 1; } /* check IC to find cause of interrupt */ switch (ST0 & ST0_INTR) { case 0x40: /* error occurred during command execution */ if (ST1 & ST1_EOC) return 0; /* occurs with pseudo-DMA */ bad = 1; if (ST1 & ST1_WP) { DPRINT("Drive is write protected\n"); clear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags); cont->done(0); bad = 2; } else if (ST1 & ST1_ND) { set_bit(FD_NEED_TWADDLE_BIT, &DRS->flags); } else if (ST1 & ST1_OR) { if (DP->flags & FTD_MSG) DPRINT("Over/Underrun - retrying\n"); bad = 0; } else if (*errors >= DP->max_errors.reporting) { print_errors(); } if (ST2 & ST2_WC || ST2 & ST2_BC) /* wrong cylinder => recal */ DRS->track = NEED_2_RECAL; return bad; case 0x80: /* invalid command given */ DPRINT("Invalid FDC command given!\n"); cont->done(0); return 2; case 0xc0: DPRINT("Abnormal termination caused by polling\n"); cont->error(); return 2; default: /* (0) Normal command termination */ return 0; } } /* * This routine is called when everything should be correctly set up * for the transfer (i.e. floppy motor is on, the correct floppy is * selected, and the head is sitting on the right track). */ static void setup_rw_floppy(void) { int i; int r; int flags; unsigned long ready_date; void (*function)(void); flags = raw_cmd->flags; if (flags & (FD_RAW_READ | FD_RAW_WRITE)) flags |= FD_RAW_INTR; if ((flags & FD_RAW_SPIN) && !(flags & FD_RAW_NO_MOTOR)) { ready_date = DRS->spinup_date + DP->spinup; /* If spinup will take a long time, rerun scandrives * again just before spinup completion. Beware that * after scandrives, we must again wait for selection. */ if (time_after(ready_date, jiffies + DP->select_delay)) { ready_date -= DP->select_delay; function = floppy_start; } else function = setup_rw_floppy; /* wait until the floppy is spinning fast enough */ if (fd_wait_for_completion(ready_date, function)) return; } if ((flags & FD_RAW_READ) || (flags & FD_RAW_WRITE)) setup_DMA(); if (flags & FD_RAW_INTR) do_floppy = main_command_interrupt; r = 0; for (i = 0; i < raw_cmd->cmd_count; i++) r |= output_byte(raw_cmd->cmd[i]); debugt(__func__, "rw_command"); if (r) { cont->error(); reset_fdc(); return; } if (!(flags & FD_RAW_INTR)) { inr = result(); cont->interrupt(); } else if (flags & FD_RAW_NEED_DISK) fd_watchdog(); } static int blind_seek; /* * This is the routine called after every seek (or recalibrate) interrupt * from the floppy controller. */ static void seek_interrupt(void) { debugt(__func__, ""); if (inr != 2 || (ST0 & 0xF8) != 0x20) { DPRINT("seek failed\n"); DRS->track = NEED_2_RECAL; cont->error(); cont->redo(); return; } if (DRS->track >= 0 && DRS->track != ST1 && !blind_seek) { debug_dcl(DP->flags, "clearing NEWCHANGE flag because of effective seek\n"); debug_dcl(DP->flags, "jiffies=%lu\n", jiffies); clear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); /* effective seek */ DRS->select_date = jiffies; } DRS->track = ST1; floppy_ready(); } static void check_wp(void) { if (test_bit(FD_VERIFY_BIT, &DRS->flags)) { /* check write protection */ output_byte(FD_GETSTATUS); output_byte(UNIT(current_drive)); if (result() != 1) { FDCS->reset = 1; return; } clear_bit(FD_VERIFY_BIT, &DRS->flags); clear_bit(FD_NEED_TWADDLE_BIT, &DRS->flags); debug_dcl(DP->flags, "checking whether disk is write protected\n"); debug_dcl(DP->flags, "wp=%x\n", ST3 & 0x40); if (!(ST3 & 0x40)) set_bit(FD_DISK_WRITABLE_BIT, &DRS->flags); else clear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags); } } static void seek_floppy(void) { int track; blind_seek = 0; debug_dcl(DP->flags, "calling disk change from %s\n", __func__); if (!test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) && disk_change(current_drive) && (raw_cmd->flags & FD_RAW_NEED_DISK)) { /* the media changed flag should be cleared after the seek. * If it isn't, this means that there is really no disk in * the drive. */ set_bit(FD_DISK_CHANGED_BIT, &DRS->flags); cont->done(0); cont->redo(); return; } if (DRS->track <= NEED_1_RECAL) { recalibrate_floppy(); return; } else if (test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) && (raw_cmd->flags & FD_RAW_NEED_DISK) && (DRS->track <= NO_TRACK || DRS->track == raw_cmd->track)) { /* we seek to clear the media-changed condition. Does anybody * know a more elegant way, which works on all drives? */ if (raw_cmd->track) track = raw_cmd->track - 1; else { if (DP->flags & FD_SILENT_DCL_CLEAR) { set_dor(fdc, ~(0x10 << UNIT(current_drive)), 0); blind_seek = 1; raw_cmd->flags |= FD_RAW_NEED_SEEK; } track = 1; } } else { check_wp(); if (raw_cmd->track != DRS->track && (raw_cmd->flags & FD_RAW_NEED_SEEK)) track = raw_cmd->track; else { setup_rw_floppy(); return; } } do_floppy = seek_interrupt; output_byte(FD_SEEK); output_byte(UNIT(current_drive)); if (output_byte(track) < 0) { reset_fdc(); return; } debugt(__func__, ""); } static void recal_interrupt(void) { debugt(__func__, ""); if (inr != 2) FDCS->reset = 1; else if (ST0 & ST0_ECE) { switch (DRS->track) { case NEED_1_RECAL: debugt(__func__, "need 1 recal"); /* after a second recalibrate, we still haven't * reached track 0. Probably no drive. Raise an * error, as failing immediately might upset * computers possessed by the Devil :-) */ cont->error(); cont->redo(); return; case NEED_2_RECAL: debugt(__func__, "need 2 recal"); /* If we already did a recalibrate, * and we are not at track 0, this * means we have moved. (The only way * not to move at recalibration is to * be already at track 0.) Clear the * new change flag */ debug_dcl(DP->flags, "clearing NEWCHANGE flag because of second recalibrate\n"); clear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); DRS->select_date = jiffies; /* fall through */ default: debugt(__func__, "default"); /* Recalibrate moves the head by at * most 80 steps. If after one * recalibrate we don't have reached * track 0, this might mean that we * started beyond track 80. Try * again. */ DRS->track = NEED_1_RECAL; break; } } else DRS->track = ST1; floppy_ready(); } static void print_result(char *message, int inr) { int i; DPRINT("%s ", message); if (inr >= 0) for (i = 0; i < inr; i++) pr_cont("repl[%d]=%x ", i, reply_buffer[i]); pr_cont("\n"); } /* interrupt handler. Note that this can be called externally on the Sparc */ irqreturn_t floppy_interrupt(int irq, void *dev_id) { int do_print; unsigned long f; void (*handler)(void) = do_floppy; lasthandler = handler; interruptjiffies = jiffies; f = claim_dma_lock(); fd_disable_dma(); release_dma_lock(f); do_floppy = NULL; if (fdc >= N_FDC || FDCS->address == -1) { /* we don't even know which FDC is the culprit */ pr_info("DOR0=%x\n", fdc_state[0].dor); pr_info("floppy interrupt on bizarre fdc %d\n", fdc); pr_info("handler=%ps\n", handler); is_alive(__func__, "bizarre fdc"); return IRQ_NONE; } FDCS->reset = 0; /* We have to clear the reset flag here, because apparently on boxes * with level triggered interrupts (PS/2, Sparc, ...), it is needed to * emit SENSEI's to clear the interrupt line. And FDCS->reset blocks the * emission of the SENSEI's. * It is OK to emit floppy commands because we are in an interrupt * handler here, and thus we have to fear no interference of other * activity. */ do_print = !handler && print_unex && initialized; inr = result(); if (do_print) print_result("unexpected interrupt", inr); if (inr == 0) { int max_sensei = 4; do { output_byte(FD_SENSEI); inr = result(); if (do_print) print_result("sensei", inr); max_sensei--; } while ((ST0 & 0x83) != UNIT(current_drive) && inr == 2 && max_sensei); } if (!handler) { FDCS->reset = 1; return IRQ_NONE; } schedule_bh(handler); is_alive(__func__, "normal interrupt end"); /* FIXME! Was it really for us? */ return IRQ_HANDLED; } static void recalibrate_floppy(void) { debugt(__func__, ""); do_floppy = recal_interrupt; output_byte(FD_RECALIBRATE); if (output_byte(UNIT(current_drive)) < 0) reset_fdc(); } /* * Must do 4 FD_SENSEIs after reset because of ``drive polling''. */ static void reset_interrupt(void) { debugt(__func__, ""); result(); /* get the status ready for set_fdc */ if (FDCS->reset) { pr_info("reset set in interrupt, calling %ps\n", cont->error); cont->error(); /* a reset just after a reset. BAD! */ } cont->redo(); } /* * reset is done by pulling bit 2 of DOR low for a while (old FDCs), * or by setting the self clearing bit 7 of STATUS (newer FDCs) */ static void reset_fdc(void) { unsigned long flags; do_floppy = reset_interrupt; FDCS->reset = 0; reset_fdc_info(0); /* Pseudo-DMA may intercept 'reset finished' interrupt. */ /* Irrelevant for systems with true DMA (i386). */ flags = claim_dma_lock(); fd_disable_dma(); release_dma_lock(flags); if (FDCS->version >= FDC_82072A) fd_outb(0x80 | (FDCS->dtr & 3), FD_STATUS); else { fd_outb(FDCS->dor & ~0x04, FD_DOR); udelay(FD_RESET_DELAY); fd_outb(FDCS->dor, FD_DOR); } } static void show_floppy(void) { int i; pr_info("\n"); pr_info("floppy driver state\n"); pr_info("-------------------\n"); pr_info("now=%lu last interrupt=%lu diff=%lu last called handler=%ps\n", jiffies, interruptjiffies, jiffies - interruptjiffies, lasthandler); pr_info("timeout_message=%s\n", timeout_message); pr_info("last output bytes:\n"); for (i = 0; i < OLOGSIZE; i++) pr_info("%2x %2x %lu\n", output_log[(i + output_log_pos) % OLOGSIZE].data, output_log[(i + output_log_pos) % OLOGSIZE].status, output_log[(i + output_log_pos) % OLOGSIZE].jiffies); pr_info("last result at %lu\n", resultjiffies); pr_info("last redo_fd_request at %lu\n", lastredo); print_hex_dump(KERN_INFO, "", DUMP_PREFIX_NONE, 16, 1, reply_buffer, resultsize, true); pr_info("status=%x\n", fd_inb(FD_STATUS)); pr_info("fdc_busy=%lu\n", fdc_busy); if (do_floppy) pr_info("do_floppy=%ps\n", do_floppy); if (work_pending(&floppy_work)) pr_info("floppy_work.func=%ps\n", floppy_work.func); if (delayed_work_pending(&fd_timer)) pr_info("delayed work.function=%p expires=%ld\n", fd_timer.work.func, fd_timer.timer.expires - jiffies); if (delayed_work_pending(&fd_timeout)) pr_info("timer_function=%p expires=%ld\n", fd_timeout.work.func, fd_timeout.timer.expires - jiffies); pr_info("cont=%p\n", cont); pr_info("current_req=%p\n", current_req); pr_info("command_status=%d\n", command_status); pr_info("\n"); } static void floppy_shutdown(struct work_struct *arg) { unsigned long flags; if (initialized) show_floppy(); cancel_activity(); flags = claim_dma_lock(); fd_disable_dma(); release_dma_lock(flags); /* avoid dma going to a random drive after shutdown */ if (initialized) DPRINT("floppy timeout called\n"); FDCS->reset = 1; if (cont) { cont->done(0); cont->redo(); /* this will recall reset when needed */ } else { pr_info("no cont in shutdown!\n"); process_fd_request(); } is_alive(__func__, ""); } /* start motor, check media-changed condition and write protection */ static int start_motor(void (*function)(void)) { int mask; int data; mask = 0xfc; data = UNIT(current_drive); if (!(raw_cmd->flags & FD_RAW_NO_MOTOR)) { if (!(FDCS->dor & (0x10 << UNIT(current_drive)))) { set_debugt(); /* no read since this drive is running */ DRS->first_read_date = 0; /* note motor start time if motor is not yet running */ DRS->spinup_date = jiffies; data |= (0x10 << UNIT(current_drive)); } } else if (FDCS->dor & (0x10 << UNIT(current_drive))) mask &= ~(0x10 << UNIT(current_drive)); /* starts motor and selects floppy */ del_timer(motor_off_timer + current_drive); set_dor(fdc, mask, data); /* wait_for_completion also schedules reset if needed. */ return fd_wait_for_completion(DRS->select_date + DP->select_delay, function); } static void floppy_ready(void) { if (FDCS->reset) { reset_fdc(); return; } if (start_motor(floppy_ready)) return; if (fdc_dtr()) return; debug_dcl(DP->flags, "calling disk change from floppy_ready\n"); if (!(raw_cmd->flags & FD_RAW_NO_MOTOR) && disk_change(current_drive) && !DP->select_delay) twaddle(); /* this clears the dcl on certain * drive/controller combinations */ #ifdef fd_chose_dma_mode if ((raw_cmd->flags & FD_RAW_READ) || (raw_cmd->flags & FD_RAW_WRITE)) { unsigned long flags = claim_dma_lock(); fd_chose_dma_mode(raw_cmd->kernel_data, raw_cmd->length); release_dma_lock(flags); } #endif if (raw_cmd->flags & (FD_RAW_NEED_SEEK | FD_RAW_NEED_DISK)) { perpendicular_mode(); fdc_specify(); /* must be done here because of hut, hlt ... */ seek_floppy(); } else { if ((raw_cmd->flags & FD_RAW_READ) || (raw_cmd->flags & FD_RAW_WRITE)) fdc_specify(); setup_rw_floppy(); } } static void floppy_start(void) { reschedule_timeout(current_reqD, "floppy start"); scandrives(); debug_dcl(DP->flags, "setting NEWCHANGE in floppy_start\n"); set_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); floppy_ready(); } /* * ======================================================================== * here ends the bottom half. Exported routines are: * floppy_start, floppy_off, floppy_ready, lock_fdc, unlock_fdc, set_fdc, * start_motor, reset_fdc, reset_fdc_info, interpret_errors. * Initialization also uses output_byte, result, set_dor, floppy_interrupt * and set_dor. * ======================================================================== */ /* * General purpose continuations. * ============================== */ static void do_wakeup(void) { reschedule_timeout(MAXTIMEOUT, "do wakeup"); cont = NULL; command_status += 2; wake_up(&command_done); } static const struct cont_t wakeup_cont = { .interrupt = empty, .redo = do_wakeup, .error = empty, .done = (done_f)empty }; static const struct cont_t intr_cont = { .interrupt = empty, .redo = process_fd_request, .error = empty, .done = (done_f)empty }; static int wait_til_done(void (*handler)(void), bool interruptible) { int ret; schedule_bh(handler); if (interruptible) wait_event_interruptible(command_done, command_status >= 2); else wait_event(command_done, command_status >= 2); if (command_status < 2) { cancel_activity(); cont = &intr_cont; reset_fdc(); return -EINTR; } if (FDCS->reset) command_status = FD_COMMAND_ERROR; if (command_status == FD_COMMAND_OKAY) ret = 0; else ret = -EIO; command_status = FD_COMMAND_NONE; return ret; } static void generic_done(int result) { command_status = result; cont = &wakeup_cont; } static void generic_success(void) { cont->done(1); } static void generic_failure(void) { cont->done(0); } static void success_and_wakeup(void) { generic_success(); cont->redo(); } /* * formatting and rw support. * ========================== */ static int next_valid_format(void) { int probed_format; probed_format = DRS->probed_format; while (1) { if (probed_format >= 8 || !DP->autodetect[probed_format]) { DRS->probed_format = 0; return 1; } if (floppy_type[DP->autodetect[probed_format]].sect) { DRS->probed_format = probed_format; return 0; } probed_format++; } } static void bad_flp_intr(void) { int err_count; if (probing) { DRS->probed_format++; if (!next_valid_format()) return; } err_count = ++(*errors); INFBOUND(DRWE->badness, err_count); if (err_count > DP->max_errors.abort) cont->done(0); if (err_count > DP->max_errors.reset) FDCS->reset = 1; else if (err_count > DP->max_errors.recal) DRS->track = NEED_2_RECAL; } static void set_floppy(int drive) { int type = ITYPE(UDRS->fd_device); if (type) _floppy = floppy_type + type; else _floppy = current_type[drive]; } /* * formatting support. * =================== */ static void format_interrupt(void) { switch (interpret_errors()) { case 1: cont->error(); case 2: break; case 0: cont->done(1); } cont->redo(); } #define FM_MODE(x, y) ((y) & ~(((x)->rate & 0x80) >> 1)) #define CT(x) ((x) | 0xc0) static void setup_format_params(int track) { int n; int il; int count; int head_shift; int track_shift; struct fparm { unsigned char track, head, sect, size; } *here = (struct fparm *)floppy_track_buffer; raw_cmd = &default_raw_cmd; raw_cmd->track = track; raw_cmd->flags = (FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK); raw_cmd->rate = _floppy->rate & 0x43; raw_cmd->cmd_count = NR_F; COMMAND = FM_MODE(_floppy, FD_FORMAT); DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, format_req.head); F_SIZECODE = FD_SIZECODE(_floppy); F_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE; F_GAP = _floppy->fmt_gap; F_FILL = FD_FILL_BYTE; raw_cmd->kernel_data = floppy_track_buffer; raw_cmd->length = 4 * F_SECT_PER_TRACK; /* allow for about 30ms for data transport per track */ head_shift = (F_SECT_PER_TRACK + 5) / 6; /* a ``cylinder'' is two tracks plus a little stepping time */ track_shift = 2 * head_shift + 3; /* position of logical sector 1 on this track */ n = (track_shift * format_req.track + head_shift * format_req.head) % F_SECT_PER_TRACK; /* determine interleave */ il = 1; if (_floppy->fmt_gap < 0x22) il++; /* initialize field */ for (count = 0; count < F_SECT_PER_TRACK; ++count) { here[count].track = format_req.track; here[count].head = format_req.head; here[count].sect = 0; here[count].size = F_SIZECODE; } /* place logical sectors */ for (count = 1; count <= F_SECT_PER_TRACK; ++count) { here[n].sect = count; n = (n + il) % F_SECT_PER_TRACK; if (here[n].sect) { /* sector busy, find next free sector */ ++n; if (n >= F_SECT_PER_TRACK) { n -= F_SECT_PER_TRACK; while (here[n].sect) ++n; } } } if (_floppy->stretch & FD_SECTBASEMASK) { for (count = 0; count < F_SECT_PER_TRACK; count++) here[count].sect += FD_SECTBASE(_floppy) - 1; } } static void redo_format(void) { buffer_track = -1; setup_format_params(format_req.track << STRETCH(_floppy)); floppy_start(); debugt(__func__, "queue format request"); } static const struct cont_t format_cont = { .interrupt = format_interrupt, .redo = redo_format, .error = bad_flp_intr, .done = generic_done }; static int do_format(int drive, struct format_descr *tmp_format_req) { int ret; if (lock_fdc(drive)) return -EINTR; set_floppy(drive); if (!_floppy || _floppy->track > DP->tracks || tmp_format_req->track >= _floppy->track || tmp_format_req->head >= _floppy->head || (_floppy->sect << 2) % (1 << FD_SIZECODE(_floppy)) || !_floppy->fmt_gap) { process_fd_request(); return -EINVAL; } format_req = *tmp_format_req; format_errors = 0; cont = &format_cont; errors = &format_errors; ret = wait_til_done(redo_format, true); if (ret == -EINTR) return -EINTR; process_fd_request(); return ret; } /* * Buffer read/write and support * ============================= */ static void floppy_end_request(struct request *req, blk_status_t error) { unsigned int nr_sectors = current_count_sectors; unsigned int drive = (unsigned long)req->rq_disk->private_data; /* current_count_sectors can be zero if transfer failed */ if (error) nr_sectors = blk_rq_cur_sectors(req); if (blk_update_request(req, error, nr_sectors << 9)) return; __blk_mq_end_request(req, error); /* We're done with the request */ floppy_off(drive); current_req = NULL; } /* new request_done. Can handle physical sectors which are smaller than a * logical buffer */ static void request_done(int uptodate) { struct request *req = current_req; int block; char msg[sizeof("request done ") + sizeof(int) * 3]; probing = 0; snprintf(msg, sizeof(msg), "request done %d", uptodate); reschedule_timeout(MAXTIMEOUT, msg); if (!req) { pr_info("floppy.c: no request in request_done\n"); return; } if (uptodate) { /* maintain values for invalidation on geometry * change */ block = current_count_sectors + blk_rq_pos(req); INFBOUND(DRS->maxblock, block); if (block > _floppy->sect) DRS->maxtrack = 1; floppy_end_request(req, 0); } else { if (rq_data_dir(req) == WRITE) { /* record write error information */ DRWE->write_errors++; if (DRWE->write_errors == 1) { DRWE->first_error_sector = blk_rq_pos(req); DRWE->first_error_generation = DRS->generation; } DRWE->last_error_sector = blk_rq_pos(req); DRWE->last_error_generation = DRS->generation; } floppy_end_request(req, BLK_STS_IOERR); } } /* Interrupt handler evaluating the result of the r/w operation */ static void rw_interrupt(void) { int eoc; int ssize; int heads; int nr_sectors; if (R_HEAD >= 2) { /* some Toshiba floppy controllers occasionnally seem to * return bogus interrupts after read/write operations, which * can be recognized by a bad head number (>= 2) */ return; } if (!DRS->first_read_date) DRS->first_read_date = jiffies; nr_sectors = 0; ssize = DIV_ROUND_UP(1 << SIZECODE, 4); if (ST1 & ST1_EOC) eoc = 1; else eoc = 0; if (COMMAND & 0x80) heads = 2; else heads = 1; nr_sectors = (((R_TRACK - TRACK) * heads + R_HEAD - HEAD) * SECT_PER_TRACK + R_SECTOR - SECTOR + eoc) << SIZECODE >> 2; if (nr_sectors / ssize > DIV_ROUND_UP(in_sector_offset + current_count_sectors, ssize)) { DPRINT("long rw: %x instead of %lx\n", nr_sectors, current_count_sectors); pr_info("rs=%d s=%d\n", R_SECTOR, SECTOR); pr_info("rh=%d h=%d\n", R_HEAD, HEAD); pr_info("rt=%d t=%d\n", R_TRACK, TRACK); pr_info("heads=%d eoc=%d\n", heads, eoc); pr_info("spt=%d st=%d ss=%d\n", SECT_PER_TRACK, fsector_t, ssize); pr_info("in_sector_offset=%d\n", in_sector_offset); } nr_sectors -= in_sector_offset; INFBOUND(nr_sectors, 0); SUPBOUND(current_count_sectors, nr_sectors); switch (interpret_errors()) { case 2: cont->redo(); return; case 1: if (!current_count_sectors) { cont->error(); cont->redo(); return; } break; case 0: if (!current_count_sectors) { cont->redo(); return; } current_type[current_drive] = _floppy; floppy_sizes[TOMINOR(current_drive)] = _floppy->size; break; } if (probing) { if (DP->flags & FTD_MSG) DPRINT("Auto-detected floppy type %s in fd%d\n", _floppy->name, current_drive); current_type[current_drive] = _floppy; floppy_sizes[TOMINOR(current_drive)] = _floppy->size; probing = 0; } if (CT(COMMAND) != FD_READ || raw_cmd->kernel_data == bio_data(current_req->bio)) { /* transfer directly from buffer */ cont->done(1); } else if (CT(COMMAND) == FD_READ) { buffer_track = raw_cmd->track; buffer_drive = current_drive; INFBOUND(buffer_max, nr_sectors + fsector_t); } cont->redo(); } /* Compute maximal contiguous buffer size. */ static int buffer_chain_size(void) { struct bio_vec bv; int size; struct req_iterator iter; char *base; base = bio_data(current_req->bio); size = 0; rq_for_each_segment(bv, current_req, iter) { if (page_address(bv.bv_page) + bv.bv_offset != base + size) break; size += bv.bv_len; } return size >> 9; } /* Compute the maximal transfer size */ static int transfer_size(int ssize, int max_sector, int max_size) { SUPBOUND(max_sector, fsector_t + max_size); /* alignment */ max_sector -= (max_sector % _floppy->sect) % ssize; /* transfer size, beginning not aligned */ current_count_sectors = max_sector - fsector_t; return max_sector; } /* * Move data from/to the track buffer to/from the buffer cache. */ static void copy_buffer(int ssize, int max_sector, int max_sector_2) { int remaining; /* number of transferred 512-byte sectors */ struct bio_vec bv; char *buffer; char *dma_buffer; int size; struct req_iterator iter; max_sector = transfer_size(ssize, min(max_sector, max_sector_2), blk_rq_sectors(current_req)); if (current_count_sectors <= 0 && CT(COMMAND) == FD_WRITE && buffer_max > fsector_t + blk_rq_sectors(current_req)) current_count_sectors = min_t(int, buffer_max - fsector_t, blk_rq_sectors(current_req)); remaining = current_count_sectors << 9; if (remaining > blk_rq_bytes(current_req) && CT(COMMAND) == FD_WRITE) { DPRINT("in copy buffer\n"); pr_info("current_count_sectors=%ld\n", current_count_sectors); pr_info("remaining=%d\n", remaining >> 9); pr_info("current_req->nr_sectors=%u\n", blk_rq_sectors(current_req)); pr_info("current_req->current_nr_sectors=%u\n", blk_rq_cur_sectors(current_req)); pr_info("max_sector=%d\n", max_sector); pr_info("ssize=%d\n", ssize); } buffer_max = max(max_sector, buffer_max); dma_buffer = floppy_track_buffer + ((fsector_t - buffer_min) << 9); size = blk_rq_cur_bytes(current_req); rq_for_each_segment(bv, current_req, iter) { if (!remaining) break; size = bv.bv_len; SUPBOUND(size, remaining); buffer = page_address(bv.bv_page) + bv.bv_offset; if (dma_buffer + size > floppy_track_buffer + (max_buffer_sectors << 10) || dma_buffer < floppy_track_buffer) { DPRINT("buffer overrun in copy buffer %d\n", (int)((floppy_track_buffer - dma_buffer) >> 9)); pr_info("fsector_t=%d buffer_min=%d\n", fsector_t, buffer_min); pr_info("current_count_sectors=%ld\n", current_count_sectors); if (CT(COMMAND) == FD_READ) pr_info("read\n"); if (CT(COMMAND) == FD_WRITE) pr_info("write\n"); break; } if (((unsigned long)buffer) % 512) DPRINT("%p buffer not aligned\n", buffer); if (CT(COMMAND) == FD_READ) memcpy(buffer, dma_buffer, size); else memcpy(dma_buffer, buffer, size); remaining -= size; dma_buffer += size; } if (remaining) { if (remaining > 0) max_sector -= remaining >> 9; DPRINT("weirdness: remaining %d\n", remaining >> 9); } } /* work around a bug in pseudo DMA * (on some FDCs) pseudo DMA does not stop when the CPU stops * sending data. Hence we need a different way to signal the * transfer length: We use SECT_PER_TRACK. Unfortunately, this * does not work with MT, hence we can only transfer one head at * a time */ static void virtualdmabug_workaround(void) { int hard_sectors; int end_sector; if (CT(COMMAND) == FD_WRITE) { COMMAND &= ~0x80; /* switch off multiple track mode */ hard_sectors = raw_cmd->length >> (7 + SIZECODE); end_sector = SECTOR + hard_sectors - 1; if (end_sector > SECT_PER_TRACK) { pr_info("too many sectors %d > %d\n", end_sector, SECT_PER_TRACK); return; } SECT_PER_TRACK = end_sector; /* make sure SECT_PER_TRACK * points to end of transfer */ } } /* * Formulate a read/write request. * this routine decides where to load the data (directly to buffer, or to * tmp floppy area), how much data to load (the size of the buffer, the whole * track, or a single sector) * All floppy_track_buffer handling goes in here. If we ever add track buffer * allocation on the fly, it should be done here. No other part should need * modification. */ static int make_raw_rw_request(void) { int aligned_sector_t; int max_sector; int max_size; int tracksize; int ssize; if (WARN(max_buffer_sectors == 0, "VFS: Block I/O scheduled on unopened device\n")) return 0; set_fdc((long)current_req->rq_disk->private_data); raw_cmd = &default_raw_cmd; raw_cmd->flags = FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK; raw_cmd->cmd_count = NR_RW; if (rq_data_dir(current_req) == READ) { raw_cmd->flags |= FD_RAW_READ; COMMAND = FM_MODE(_floppy, FD_READ); } else if (rq_data_dir(current_req) == WRITE) { raw_cmd->flags |= FD_RAW_WRITE; COMMAND = FM_MODE(_floppy, FD_WRITE); } else { DPRINT("%s: unknown command\n", __func__); return 0; } max_sector = _floppy->sect * _floppy->head; TRACK = (int)blk_rq_pos(current_req) / max_sector; fsector_t = (int)blk_rq_pos(current_req) % max_sector; if (_floppy->track && TRACK >= _floppy->track) { if (blk_rq_cur_sectors(current_req) & 1) { current_count_sectors = 1; return 1; } else return 0; } HEAD = fsector_t / _floppy->sect; if (((_floppy->stretch & (FD_SWAPSIDES | FD_SECTBASEMASK)) || test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) && fsector_t < _floppy->sect) max_sector = _floppy->sect; /* 2M disks have phantom sectors on the first track */ if ((_floppy->rate & FD_2M) && (!TRACK) && (!HEAD)) { max_sector = 2 * _floppy->sect / 3; if (fsector_t >= max_sector) { current_count_sectors = min_t(int, _floppy->sect - fsector_t, blk_rq_sectors(current_req)); return 1; } SIZECODE = 2; } else SIZECODE = FD_SIZECODE(_floppy); raw_cmd->rate = _floppy->rate & 0x43; if ((_floppy->rate & FD_2M) && (TRACK || HEAD) && raw_cmd->rate == 2) raw_cmd->rate = 1; if (SIZECODE) SIZECODE2 = 0xff; else SIZECODE2 = 0x80; raw_cmd->track = TRACK << STRETCH(_floppy); DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, HEAD); GAP = _floppy->gap; ssize = DIV_ROUND_UP(1 << SIZECODE, 4); SECT_PER_TRACK = _floppy->sect << 2 >> SIZECODE; SECTOR = ((fsector_t % _floppy->sect) << 2 >> SIZECODE) + FD_SECTBASE(_floppy); /* tracksize describes the size which can be filled up with sectors * of size ssize. */ tracksize = _floppy->sect - _floppy->sect % ssize; if (tracksize < _floppy->sect) { SECT_PER_TRACK++; if (tracksize <= fsector_t % _floppy->sect) SECTOR--; /* if we are beyond tracksize, fill up using smaller sectors */ while (tracksize <= fsector_t % _floppy->sect) { while (tracksize + ssize > _floppy->sect) { SIZECODE--; ssize >>= 1; } SECTOR++; SECT_PER_TRACK++; tracksize += ssize; } max_sector = HEAD * _floppy->sect + tracksize; } else if (!TRACK && !HEAD && !(_floppy->rate & FD_2M) && probing) { max_sector = _floppy->sect; } else if (!HEAD && CT(COMMAND) == FD_WRITE) { /* for virtual DMA bug workaround */ max_sector = _floppy->sect; } in_sector_offset = (fsector_t % _floppy->sect) % ssize; aligned_sector_t = fsector_t - in_sector_offset; max_size = blk_rq_sectors(current_req); if ((raw_cmd->track == buffer_track) && (current_drive == buffer_drive) && (fsector_t >= buffer_min) && (fsector_t < buffer_max)) { /* data already in track buffer */ if (CT(COMMAND) == FD_READ) { copy_buffer(1, max_sector, buffer_max); return 1; } } else if (in_sector_offset || blk_rq_sectors(current_req) < ssize) { if (CT(COMMAND) == FD_WRITE) { unsigned int sectors; sectors = fsector_t + blk_rq_sectors(current_req); if (sectors > ssize && sectors < ssize + ssize) max_size = ssize + ssize; else max_size = ssize; } raw_cmd->flags &= ~FD_RAW_WRITE; raw_cmd->flags |= FD_RAW_READ; COMMAND = FM_MODE(_floppy, FD_READ); } else if ((unsigned long)bio_data(current_req->bio) < MAX_DMA_ADDRESS) { unsigned long dma_limit; int direct, indirect; indirect = transfer_size(ssize, max_sector, max_buffer_sectors * 2) - fsector_t; /* * Do NOT use minimum() here---MAX_DMA_ADDRESS is 64 bits wide * on a 64 bit machine! */ max_size = buffer_chain_size(); dma_limit = (MAX_DMA_ADDRESS - ((unsigned long)bio_data(current_req->bio))) >> 9; if ((unsigned long)max_size > dma_limit) max_size = dma_limit; /* 64 kb boundaries */ if (CROSS_64KB(bio_data(current_req->bio), max_size << 9)) max_size = (K_64 - ((unsigned long)bio_data(current_req->bio)) % K_64) >> 9; direct = transfer_size(ssize, max_sector, max_size) - fsector_t; /* * We try to read tracks, but if we get too many errors, we * go back to reading just one sector at a time. * * This means we should be able to read a sector even if there * are other bad sectors on this track. */ if (!direct || (indirect * 2 > direct * 3 && *errors < DP->max_errors.read_track && ((!probing || (DP->read_track & (1 << DRS->probed_format)))))) { max_size = blk_rq_sectors(current_req); } else { raw_cmd->kernel_data = bio_data(current_req->bio); raw_cmd->length = current_count_sectors << 9; if (raw_cmd->length == 0) { DPRINT("%s: zero dma transfer attempted\n", __func__); DPRINT("indirect=%d direct=%d fsector_t=%d\n", indirect, direct, fsector_t); return 0; } virtualdmabug_workaround(); return 2; } } if (CT(COMMAND) == FD_READ) max_size = max_sector; /* unbounded */ /* claim buffer track if needed */ if (buffer_track != raw_cmd->track || /* bad track */ buffer_drive != current_drive || /* bad drive */ fsector_t > buffer_max || fsector_t < buffer_min || ((CT(COMMAND) == FD_READ || (!in_sector_offset && blk_rq_sectors(current_req) >= ssize)) && max_sector > 2 * max_buffer_sectors + buffer_min && max_size + fsector_t > 2 * max_buffer_sectors + buffer_min)) { /* not enough space */ buffer_track = -1; buffer_drive = current_drive; buffer_max = buffer_min = aligned_sector_t; } raw_cmd->kernel_data = floppy_track_buffer + ((aligned_sector_t - buffer_min) << 9); if (CT(COMMAND) == FD_WRITE) { /* copy write buffer to track buffer. * if we get here, we know that the write * is either aligned or the data already in the buffer * (buffer will be overwritten) */ if (in_sector_offset && buffer_track == -1) DPRINT("internal error offset !=0 on write\n"); buffer_track = raw_cmd->track; buffer_drive = current_drive; copy_buffer(ssize, max_sector, 2 * max_buffer_sectors + buffer_min); } else transfer_size(ssize, max_sector, 2 * max_buffer_sectors + buffer_min - aligned_sector_t); /* round up current_count_sectors to get dma xfer size */ raw_cmd->length = in_sector_offset + current_count_sectors; raw_cmd->length = ((raw_cmd->length - 1) | (ssize - 1)) + 1; raw_cmd->length <<= 9; if ((raw_cmd->length < current_count_sectors << 9) || (raw_cmd->kernel_data != bio_data(current_req->bio) && CT(COMMAND) == FD_WRITE && (aligned_sector_t + (raw_cmd->length >> 9) > buffer_max || aligned_sector_t < buffer_min)) || raw_cmd->length % (128 << SIZECODE) || raw_cmd->length <= 0 || current_count_sectors <= 0) { DPRINT("fractionary current count b=%lx s=%lx\n", raw_cmd->length, current_count_sectors); if (raw_cmd->kernel_data != bio_data(current_req->bio)) pr_info("addr=%d, length=%ld\n", (int)((raw_cmd->kernel_data - floppy_track_buffer) >> 9), current_count_sectors); pr_info("st=%d ast=%d mse=%d msi=%d\n", fsector_t, aligned_sector_t, max_sector, max_size); pr_info("ssize=%x SIZECODE=%d\n", ssize, SIZECODE); pr_info("command=%x SECTOR=%d HEAD=%d, TRACK=%d\n", COMMAND, SECTOR, HEAD, TRACK); pr_info("buffer drive=%d\n", buffer_drive); pr_info("buffer track=%d\n", buffer_track); pr_info("buffer_min=%d\n", buffer_min); pr_info("buffer_max=%d\n", buffer_max); return 0; } if (raw_cmd->kernel_data != bio_data(current_req->bio)) { if (raw_cmd->kernel_data < floppy_track_buffer || current_count_sectors < 0 || raw_cmd->length < 0 || raw_cmd->kernel_data + raw_cmd->length > floppy_track_buffer + (max_buffer_sectors << 10)) { DPRINT("buffer overrun in schedule dma\n"); pr_info("fsector_t=%d buffer_min=%d current_count=%ld\n", fsector_t, buffer_min, raw_cmd->length >> 9); pr_info("current_count_sectors=%ld\n", current_count_sectors); if (CT(COMMAND) == FD_READ) pr_info("read\n"); if (CT(COMMAND) == FD_WRITE) pr_info("write\n"); return 0; } } else if (raw_cmd->length > blk_rq_bytes(current_req) || current_count_sectors > blk_rq_sectors(current_req)) { DPRINT("buffer overrun in direct transfer\n"); return 0; } else if (raw_cmd->length < current_count_sectors << 9) { DPRINT("more sectors than bytes\n"); pr_info("bytes=%ld\n", raw_cmd->length >> 9); pr_info("sectors=%ld\n", current_count_sectors); } if (raw_cmd->length == 0) { DPRINT("zero dma transfer attempted from make_raw_request\n"); return 0; } virtualdmabug_workaround(); return 2; } static int set_next_request(void) { current_req = list_first_entry_or_null(&floppy_reqs, struct request, queuelist); if (current_req) { current_req->error_count = 0; list_del_init(&current_req->queuelist); } return current_req != NULL; } static void redo_fd_request(void) { int drive; int tmp; lastredo = jiffies; if (current_drive < N_DRIVE) floppy_off(current_drive); do_request: if (!current_req) { int pending; spin_lock_irq(&floppy_lock); pending = set_next_request(); spin_unlock_irq(&floppy_lock); if (!pending) { do_floppy = NULL; unlock_fdc(); return; } } drive = (long)current_req->rq_disk->private_data; set_fdc(drive); reschedule_timeout(current_reqD, "redo fd request"); set_floppy(drive); raw_cmd = &default_raw_cmd; raw_cmd->flags = 0; if (start_motor(redo_fd_request)) return; disk_change(current_drive); if (test_bit(current_drive, &fake_change) || test_bit(FD_DISK_CHANGED_BIT, &DRS->flags)) { DPRINT("disk absent or changed during operation\n"); request_done(0); goto do_request; } if (!_floppy) { /* Autodetection */ if (!probing) { DRS->probed_format = 0; if (next_valid_format()) { DPRINT("no autodetectable formats\n"); _floppy = NULL; request_done(0); goto do_request; } } probing = 1; _floppy = floppy_type + DP->autodetect[DRS->probed_format]; } else probing = 0; errors = &(current_req->error_count); tmp = make_raw_rw_request(); if (tmp < 2) { request_done(tmp); goto do_request; } if (test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) twaddle(); schedule_bh(floppy_start); debugt(__func__, "queue fd request"); return; } static const struct cont_t rw_cont = { .interrupt = rw_interrupt, .redo = redo_fd_request, .error = bad_flp_intr, .done = request_done }; static void process_fd_request(void) { cont = &rw_cont; schedule_bh(redo_fd_request); } static blk_status_t floppy_queue_rq(struct blk_mq_hw_ctx *hctx, const struct blk_mq_queue_data *bd) { blk_mq_start_request(bd->rq); if (WARN(max_buffer_sectors == 0, "VFS: %s called on non-open device\n", __func__)) return BLK_STS_IOERR; if (WARN(atomic_read(&usage_count) == 0, "warning: usage count=0, current_req=%p sect=%ld flags=%llx\n", current_req, (long)blk_rq_pos(current_req), (unsigned long long) current_req->cmd_flags)) return BLK_STS_IOERR; spin_lock_irq(&floppy_lock); list_add_tail(&bd->rq->queuelist, &floppy_reqs); spin_unlock_irq(&floppy_lock); if (test_and_set_bit(0, &fdc_busy)) { /* fdc busy, this new request will be treated when the current one is done */ is_alive(__func__, "old request running"); return BLK_STS_OK; } command_status = FD_COMMAND_NONE; __reschedule_timeout(MAXTIMEOUT, "fd_request"); set_fdc(0); process_fd_request(); is_alive(__func__, ""); return BLK_STS_OK; } static const struct cont_t poll_cont = { .interrupt = success_and_wakeup, .redo = floppy_ready, .error = generic_failure, .done = generic_done }; static int poll_drive(bool interruptible, int flag) { /* no auto-sense, just clear dcl */ raw_cmd = &default_raw_cmd; raw_cmd->flags = flag; raw_cmd->track = 0; raw_cmd->cmd_count = 0; cont = &poll_cont; debug_dcl(DP->flags, "setting NEWCHANGE in poll_drive\n"); set_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); return wait_til_done(floppy_ready, interruptible); } /* * User triggered reset * ==================== */ static void reset_intr(void) { pr_info("weird, reset interrupt called\n"); } static const struct cont_t reset_cont = { .interrupt = reset_intr, .redo = success_and_wakeup, .error = generic_failure, .done = generic_done }; static int user_reset_fdc(int drive, int arg, bool interruptible) { int ret; if (lock_fdc(drive)) return -EINTR; if (arg == FD_RESET_ALWAYS) FDCS->reset = 1; if (FDCS->reset) { cont = &reset_cont; ret = wait_til_done(reset_fdc, interruptible); if (ret == -EINTR) return -EINTR; } process_fd_request(); return 0; } /* * Misc Ioctl's and support * ======================== */ static inline int fd_copyout(void __user *param, const void *address, unsigned long size) { return copy_to_user(param, address, size) ? -EFAULT : 0; } static inline int fd_copyin(void __user *param, void *address, unsigned long size) { return copy_from_user(address, param, size) ? -EFAULT : 0; } static const char *drive_name(int type, int drive) { struct floppy_struct *floppy; if (type) floppy = floppy_type + type; else { if (UDP->native_format) floppy = floppy_type + UDP->native_format; else return "(null)"; } if (floppy->name) return floppy->name; else return "(null)"; } /* raw commands */ static void raw_cmd_done(int flag) { int i; if (!flag) { raw_cmd->flags |= FD_RAW_FAILURE; raw_cmd->flags |= FD_RAW_HARDFAILURE; } else { raw_cmd->reply_count = inr; if (raw_cmd->reply_count > MAX_REPLIES) raw_cmd->reply_count = 0; for (i = 0; i < raw_cmd->reply_count; i++) raw_cmd->reply[i] = reply_buffer[i]; if (raw_cmd->flags & (FD_RAW_READ | FD_RAW_WRITE)) { unsigned long flags; flags = claim_dma_lock(); raw_cmd->length = fd_get_dma_residue(); release_dma_lock(flags); } if ((raw_cmd->flags & FD_RAW_SOFTFAILURE) && (!raw_cmd->reply_count || (raw_cmd->reply[0] & 0xc0))) raw_cmd->flags |= FD_RAW_FAILURE; if (disk_change(current_drive)) raw_cmd->flags |= FD_RAW_DISK_CHANGE; else raw_cmd->flags &= ~FD_RAW_DISK_CHANGE; if (raw_cmd->flags & FD_RAW_NO_MOTOR_AFTER) motor_off_callback(&motor_off_timer[current_drive]); if (raw_cmd->next && (!(raw_cmd->flags & FD_RAW_FAILURE) || !(raw_cmd->flags & FD_RAW_STOP_IF_FAILURE)) && ((raw_cmd->flags & FD_RAW_FAILURE) || !(raw_cmd->flags & FD_RAW_STOP_IF_SUCCESS))) { raw_cmd = raw_cmd->next; return; } } generic_done(flag); } static const struct cont_t raw_cmd_cont = { .interrupt = success_and_wakeup, .redo = floppy_start, .error = generic_failure, .done = raw_cmd_done }; static int raw_cmd_copyout(int cmd, void __user *param, struct floppy_raw_cmd *ptr) { int ret; while (ptr) { struct floppy_raw_cmd cmd = *ptr; cmd.next = NULL; cmd.kernel_data = NULL; ret = copy_to_user(param, &cmd, sizeof(cmd)); if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) { if (ptr->length >= 0 && ptr->length <= ptr->buffer_length) { long length = ptr->buffer_length - ptr->length; ret = fd_copyout(ptr->data, ptr->kernel_data, length); if (ret) return ret; } } ptr = ptr->next; } return 0; } static void raw_cmd_free(struct floppy_raw_cmd **ptr) { struct floppy_raw_cmd *next; struct floppy_raw_cmd *this; this = *ptr; *ptr = NULL; while (this) { if (this->buffer_length) { fd_dma_mem_free((unsigned long)this->kernel_data, this->buffer_length); this->buffer_length = 0; } next = this->next; kfree(this); this = next; } } static int raw_cmd_copyin(int cmd, void __user *param, struct floppy_raw_cmd **rcmd) { struct floppy_raw_cmd *ptr; int ret; int i; *rcmd = NULL; loop: ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_KERNEL); if (!ptr) return -ENOMEM; *rcmd = ptr; ret = copy_from_user(ptr, param, sizeof(*ptr)); ptr->next = NULL; ptr->buffer_length = 0; ptr->kernel_data = NULL; if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if (ptr->cmd_count > 33) /* the command may now also take up the space * initially intended for the reply & the * reply count. Needed for long 82078 commands * such as RESTORE, which takes ... 17 command * bytes. Murphy's law #137: When you reserve * 16 bytes for a structure, you'll one day * discover that you really need 17... */ return -EINVAL; for (i = 0; i < 16; i++) ptr->reply[i] = 0; ptr->resultcode = 0; if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) { if (ptr->length <= 0) return -EINVAL; ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length); fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length); if (!ptr->kernel_data) return -ENOMEM; ptr->buffer_length = ptr->length; } if (ptr->flags & FD_RAW_WRITE) { ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length); if (ret) return ret; } if (ptr->flags & FD_RAW_MORE) { rcmd = &(ptr->next); ptr->rate &= 0x43; goto loop; } return 0; } static int raw_cmd_ioctl(int cmd, void __user *param) { struct floppy_raw_cmd *my_raw_cmd; int drive; int ret2; int ret; if (FDCS->rawcmd <= 1) FDCS->rawcmd = 1; for (drive = 0; drive < N_DRIVE; drive++) { if (FDC(drive) != fdc) continue; if (drive == current_drive) { if (UDRS->fd_ref > 1) { FDCS->rawcmd = 2; break; } } else if (UDRS->fd_ref) { FDCS->rawcmd = 2; break; } } if (FDCS->reset) return -EIO; ret = raw_cmd_copyin(cmd, param, &my_raw_cmd); if (ret) { raw_cmd_free(&my_raw_cmd); return ret; } raw_cmd = my_raw_cmd; cont = &raw_cmd_cont; ret = wait_til_done(floppy_start, true); debug_dcl(DP->flags, "calling disk change from raw_cmd ioctl\n"); if (ret != -EINTR && FDCS->reset) ret = -EIO; DRS->track = NO_TRACK; ret2 = raw_cmd_copyout(cmd, param, my_raw_cmd); if (!ret) ret = ret2; raw_cmd_free(&my_raw_cmd); return ret; } static int invalidate_drive(struct block_device *bdev) { /* invalidate the buffer track to force a reread */ set_bit((long)bdev->bd_disk->private_data, &fake_change); process_fd_request(); check_disk_change(bdev); return 0; } static int set_geometry(unsigned int cmd, struct floppy_struct *g, int drive, int type, struct block_device *bdev) { int cnt; /* sanity checking for parameters. */ if (g->sect <= 0 || g->head <= 0 || g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) || /* check if reserved bits are set */ (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0) return -EINVAL; if (type) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&open_lock); if (lock_fdc(drive)) { mutex_unlock(&open_lock); return -EINTR; } floppy_type[type] = *g; floppy_type[type].name = "user format"; for (cnt = type << 2; cnt < (type << 2) + 4; cnt++) floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] = floppy_type[type].size + 1; process_fd_request(); for (cnt = 0; cnt < N_DRIVE; cnt++) { struct block_device *bdev = opened_bdev[cnt]; if (!bdev || ITYPE(drive_state[cnt].fd_device) != type) continue; __invalidate_device(bdev, true); } mutex_unlock(&open_lock); } else { int oldStretch; if (lock_fdc(drive)) return -EINTR; if (cmd != FDDEFPRM) { /* notice a disk change immediately, else * we lose our settings immediately*/ if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; } oldStretch = g->stretch; user_params[drive] = *g; if (buffer_drive == drive) SUPBOUND(buffer_max, user_params[drive].sect); current_type[drive] = &user_params[drive]; floppy_sizes[drive] = user_params[drive].size; if (cmd == FDDEFPRM) DRS->keep_data = -1; else DRS->keep_data = 1; /* invalidation. Invalidate only when needed, i.e. * when there are already sectors in the buffer cache * whose number will change. This is useful, because * mtools often changes the geometry of the disk after * looking at the boot block */ if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack || ((user_params[drive].sect ^ oldStretch) & (FD_SWAPSIDES | FD_SECTBASEMASK))) invalidate_drive(bdev); else process_fd_request(); } return 0; } /* handle obsolete ioctl's */ static unsigned int ioctl_table[] = { FDCLRPRM, FDSETPRM, FDDEFPRM, FDGETPRM, FDMSGON, FDMSGOFF, FDFMTBEG, FDFMTTRK, FDFMTEND, FDSETEMSGTRESH, FDFLUSH, FDSETMAXERRS, FDGETMAXERRS, FDGETDRVTYP, FDSETDRVPRM, FDGETDRVPRM, FDGETDRVSTAT, FDPOLLDRVSTAT, FDRESET, FDGETFDCSTAT, FDWERRORCLR, FDWERRORGET, FDRAWCMD, FDEJECT, FDTWADDLE }; static int normalize_ioctl(unsigned int *cmd, int *size) { int i; for (i = 0; i < ARRAY_SIZE(ioctl_table); i++) { if ((*cmd & 0xffff) == (ioctl_table[i] & 0xffff)) { *size = _IOC_SIZE(*cmd); *cmd = ioctl_table[i]; if (*size > _IOC_SIZE(*cmd)) { pr_info("ioctl not yet supported\n"); return -EFAULT; } return 0; } } return -EINVAL; } static int get_floppy_geometry(int drive, int type, struct floppy_struct **g) { if (type) *g = &floppy_type[type]; else { if (lock_fdc(drive)) return -EINTR; if (poll_drive(false, 0) == -EINTR) return -EINTR; process_fd_request(); *g = current_type[drive]; } if (!*g) return -ENODEV; return 0; } static int fd_getgeo(struct block_device *bdev, struct hd_geometry *geo) { int drive = (long)bdev->bd_disk->private_data; int type = ITYPE(drive_state[drive].fd_device); struct floppy_struct *g; int ret; ret = get_floppy_geometry(drive, type, &g); if (ret) return ret; geo->heads = g->head; geo->sectors = g->sect; geo->cylinders = g->track; return 0; } static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long param) { int drive = (long)bdev->bd_disk->private_data; int type = ITYPE(UDRS->fd_device); int i; int ret; int size; union inparam { struct floppy_struct g; /* geometry */ struct format_descr f; struct floppy_max_errors max_errors; struct floppy_drive_params dp; } inparam; /* parameters coming from user space */ const void *outparam; /* parameters passed back to user space */ /* convert compatibility eject ioctls into floppy eject ioctl. * We do this in order to provide a means to eject floppy disks before * installing the new fdutils package */ if (cmd == CDROMEJECT || /* CD-ROM eject */ cmd == 0x6470) { /* SunOS floppy eject */ DPRINT("obsolete eject ioctl\n"); DPRINT("please use floppycontrol --eject\n"); cmd = FDEJECT; } if (!((cmd & 0xff00) == 0x0200)) return -EINVAL; /* convert the old style command into a new style command */ ret = normalize_ioctl(&cmd, &size); if (ret) return ret; /* permission checks */ if (((cmd & 0x40) && !(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) || ((cmd & 0x80) && !capable(CAP_SYS_ADMIN))) return -EPERM; if (WARN_ON(size < 0 || size > sizeof(inparam))) return -EINVAL; /* copyin */ memset(&inparam, 0, sizeof(inparam)); if (_IOC_DIR(cmd) & _IOC_WRITE) { ret = fd_copyin((void __user *)param, &inparam, size); if (ret) return ret; } switch (cmd) { case FDEJECT: if (UDRS->fd_ref != 1) /* somebody else has this drive open */ return -EBUSY; if (lock_fdc(drive)) return -EINTR; /* do the actual eject. Fails on * non-Sparc architectures */ ret = fd_eject(UNIT(drive)); set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); set_bit(FD_VERIFY_BIT, &UDRS->flags); process_fd_request(); return ret; case FDCLRPRM: if (lock_fdc(drive)) return -EINTR; current_type[drive] = NULL; floppy_sizes[drive] = MAX_DISK_SIZE << 1; UDRS->keep_data = 0; return invalidate_drive(bdev); case FDSETPRM: case FDDEFPRM: return set_geometry(cmd, &inparam.g, drive, type, bdev); case FDGETPRM: ret = get_floppy_geometry(drive, type, (struct floppy_struct **)&outparam); if (ret) return ret; memcpy(&inparam.g, outparam, offsetof(struct floppy_struct, name)); outparam = &inparam.g; break; case FDMSGON: UDP->flags |= FTD_MSG; return 0; case FDMSGOFF: UDP->flags &= ~FTD_MSG; return 0; case FDFMTBEG: if (lock_fdc(drive)) return -EINTR; if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; ret = UDRS->flags; process_fd_request(); if (ret & FD_VERIFY) return -ENODEV; if (!(ret & FD_DISK_WRITABLE)) return -EROFS; return 0; case FDFMTTRK: if (UDRS->fd_ref != 1) return -EBUSY; return do_format(drive, &inparam.f); case FDFMTEND: case FDFLUSH: if (lock_fdc(drive)) return -EINTR; return invalidate_drive(bdev); case FDSETEMSGTRESH: UDP->max_errors.reporting = (unsigned short)(param & 0x0f); return 0; case FDGETMAXERRS: outparam = &UDP->max_errors; break; case FDSETMAXERRS: UDP->max_errors = inparam.max_errors; break; case FDGETDRVTYP: outparam = drive_name(type, drive); SUPBOUND(size, strlen((const char *)outparam) + 1); break; case FDSETDRVPRM: *UDP = inparam.dp; break; case FDGETDRVPRM: outparam = UDP; break; case FDPOLLDRVSTAT: if (lock_fdc(drive)) return -EINTR; if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; process_fd_request(); /* fall through */ case FDGETDRVSTAT: outparam = UDRS; break; case FDRESET: return user_reset_fdc(drive, (int)param, true); case FDGETFDCSTAT: outparam = UFDCS; break; case FDWERRORCLR: memset(UDRWE, 0, sizeof(*UDRWE)); return 0; case FDWERRORGET: outparam = UDRWE; break; case FDRAWCMD: if (type) return -EINVAL; if (lock_fdc(drive)) return -EINTR; set_floppy(drive); i = raw_cmd_ioctl(cmd, (void __user *)param); if (i == -EINTR) return -EINTR; process_fd_request(); return i; case FDTWADDLE: if (lock_fdc(drive)) return -EINTR; twaddle(); process_fd_request(); return 0; default: return -EINVAL; } if (_IOC_DIR(cmd) & _IOC_READ) return fd_copyout((void __user *)param, outparam, size); return 0; } static int fd_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long param) { int ret; mutex_lock(&floppy_mutex); ret = fd_locked_ioctl(bdev, mode, cmd, param); mutex_unlock(&floppy_mutex); return ret; } #ifdef CONFIG_COMPAT struct compat_floppy_drive_params { char cmos; compat_ulong_t max_dtr; compat_ulong_t hlt; compat_ulong_t hut; compat_ulong_t srt; compat_ulong_t spinup; compat_ulong_t spindown; unsigned char spindown_offset; unsigned char select_delay; unsigned char rps; unsigned char tracks; compat_ulong_t timeout; unsigned char interleave_sect; struct floppy_max_errors max_errors; char flags; char read_track; short autodetect[8]; compat_int_t checkfreq; compat_int_t native_format; }; struct compat_floppy_drive_struct { signed char flags; compat_ulong_t spinup_date; compat_ulong_t select_date; compat_ulong_t first_read_date; short probed_format; short track; short maxblock; short maxtrack; compat_int_t generation; compat_int_t keep_data; compat_int_t fd_ref; compat_int_t fd_device; compat_int_t last_checked; compat_caddr_t dmabuf; compat_int_t bufblocks; }; struct compat_floppy_fdc_state { compat_int_t spec1; compat_int_t spec2; compat_int_t dtr; unsigned char version; unsigned char dor; compat_ulong_t address; unsigned int rawcmd:2; unsigned int reset:1; unsigned int need_configure:1; unsigned int perp_mode:2; unsigned int has_fifo:1; unsigned int driver_version; unsigned char track[4]; }; struct compat_floppy_write_errors { unsigned int write_errors; compat_ulong_t first_error_sector; compat_int_t first_error_generation; compat_ulong_t last_error_sector; compat_int_t last_error_generation; compat_uint_t badness; }; #define FDSETPRM32 _IOW(2, 0x42, struct compat_floppy_struct) #define FDDEFPRM32 _IOW(2, 0x43, struct compat_floppy_struct) #define FDSETDRVPRM32 _IOW(2, 0x90, struct compat_floppy_drive_params) #define FDGETDRVPRM32 _IOR(2, 0x11, struct compat_floppy_drive_params) #define FDGETDRVSTAT32 _IOR(2, 0x12, struct compat_floppy_drive_struct) #define FDPOLLDRVSTAT32 _IOR(2, 0x13, struct compat_floppy_drive_struct) #define FDGETFDCSTAT32 _IOR(2, 0x15, struct compat_floppy_fdc_state) #define FDWERRORGET32 _IOR(2, 0x17, struct compat_floppy_write_errors) static int compat_set_geometry(struct block_device *bdev, fmode_t mode, unsigned int cmd, struct compat_floppy_struct __user *arg) { struct floppy_struct v; int drive, type; int err; BUILD_BUG_ON(offsetof(struct floppy_struct, name) != offsetof(struct compat_floppy_struct, name)); if (!(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) return -EPERM; memset(&v, 0, sizeof(struct floppy_struct)); if (copy_from_user(&v, arg, offsetof(struct floppy_struct, name))) return -EFAULT; mutex_lock(&floppy_mutex); drive = (long)bdev->bd_disk->private_data; type = ITYPE(UDRS->fd_device); err = set_geometry(cmd == FDSETPRM32 ? FDSETPRM : FDDEFPRM, &v, drive, type, bdev); mutex_unlock(&floppy_mutex); return err; } static int compat_get_prm(int drive, struct compat_floppy_struct __user *arg) { struct compat_floppy_struct v; struct floppy_struct *p; int err; memset(&v, 0, sizeof(v)); mutex_lock(&floppy_mutex); err = get_floppy_geometry(drive, ITYPE(UDRS->fd_device), &p); if (err) { mutex_unlock(&floppy_mutex); return err; } memcpy(&v, p, offsetof(struct floppy_struct, name)); mutex_unlock(&floppy_mutex); if (copy_to_user(arg, &v, sizeof(struct compat_floppy_struct))) return -EFAULT; return 0; } static int compat_setdrvprm(int drive, struct compat_floppy_drive_params __user *arg) { struct compat_floppy_drive_params v; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (copy_from_user(&v, arg, sizeof(struct compat_floppy_drive_params))) return -EFAULT; mutex_lock(&floppy_mutex); UDP->cmos = v.cmos; UDP->max_dtr = v.max_dtr; UDP->hlt = v.hlt; UDP->hut = v.hut; UDP->srt = v.srt; UDP->spinup = v.spinup; UDP->spindown = v.spindown; UDP->spindown_offset = v.spindown_offset; UDP->select_delay = v.select_delay; UDP->rps = v.rps; UDP->tracks = v.tracks; UDP->timeout = v.timeout; UDP->interleave_sect = v.interleave_sect; UDP->max_errors = v.max_errors; UDP->flags = v.flags; UDP->read_track = v.read_track; memcpy(UDP->autodetect, v.autodetect, sizeof(v.autodetect)); UDP->checkfreq = v.checkfreq; UDP->native_format = v.native_format; mutex_unlock(&floppy_mutex); return 0; } static int compat_getdrvprm(int drive, struct compat_floppy_drive_params __user *arg) { struct compat_floppy_drive_params v; memset(&v, 0, sizeof(struct compat_floppy_drive_params)); mutex_lock(&floppy_mutex); v.cmos = UDP->cmos; v.max_dtr = UDP->max_dtr; v.hlt = UDP->hlt; v.hut = UDP->hut; v.srt = UDP->srt; v.spinup = UDP->spinup; v.spindown = UDP->spindown; v.spindown_offset = UDP->spindown_offset; v.select_delay = UDP->select_delay; v.rps = UDP->rps; v.tracks = UDP->tracks; v.timeout = UDP->timeout; v.interleave_sect = UDP->interleave_sect; v.max_errors = UDP->max_errors; v.flags = UDP->flags; v.read_track = UDP->read_track; memcpy(v.autodetect, UDP->autodetect, sizeof(v.autodetect)); v.checkfreq = UDP->checkfreq; v.native_format = UDP->native_format; mutex_unlock(&floppy_mutex); if (copy_from_user(arg, &v, sizeof(struct compat_floppy_drive_params))) return -EFAULT; return 0; } static int compat_getdrvstat(int drive, bool poll, struct compat_floppy_drive_struct __user *arg) { struct compat_floppy_drive_struct v; memset(&v, 0, sizeof(struct compat_floppy_drive_struct)); mutex_lock(&floppy_mutex); if (poll) { if (lock_fdc(drive)) goto Eintr; if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) goto Eintr; process_fd_request(); } v.spinup_date = UDRS->spinup_date; v.select_date = UDRS->select_date; v.first_read_date = UDRS->first_read_date; v.probed_format = UDRS->probed_format; v.track = UDRS->track; v.maxblock = UDRS->maxblock; v.maxtrack = UDRS->maxtrack; v.generation = UDRS->generation; v.keep_data = UDRS->keep_data; v.fd_ref = UDRS->fd_ref; v.fd_device = UDRS->fd_device; v.last_checked = UDRS->last_checked; v.dmabuf = (uintptr_t)UDRS->dmabuf; v.bufblocks = UDRS->bufblocks; mutex_unlock(&floppy_mutex); if (copy_from_user(arg, &v, sizeof(struct compat_floppy_drive_struct))) return -EFAULT; return 0; Eintr: mutex_unlock(&floppy_mutex); return -EINTR; } static int compat_getfdcstat(int drive, struct compat_floppy_fdc_state __user *arg) { struct compat_floppy_fdc_state v32; struct floppy_fdc_state v; mutex_lock(&floppy_mutex); v = *UFDCS; mutex_unlock(&floppy_mutex); memset(&v32, 0, sizeof(struct compat_floppy_fdc_state)); v32.spec1 = v.spec1; v32.spec2 = v.spec2; v32.dtr = v.dtr; v32.version = v.version; v32.dor = v.dor; v32.address = v.address; v32.rawcmd = v.rawcmd; v32.reset = v.reset; v32.need_configure = v.need_configure; v32.perp_mode = v.perp_mode; v32.has_fifo = v.has_fifo; v32.driver_version = v.driver_version; memcpy(v32.track, v.track, 4); if (copy_to_user(arg, &v32, sizeof(struct compat_floppy_fdc_state))) return -EFAULT; return 0; } static int compat_werrorget(int drive, struct compat_floppy_write_errors __user *arg) { struct compat_floppy_write_errors v32; struct floppy_write_errors v; memset(&v32, 0, sizeof(struct compat_floppy_write_errors)); mutex_lock(&floppy_mutex); v = *UDRWE; mutex_unlock(&floppy_mutex); v32.write_errors = v.write_errors; v32.first_error_sector = v.first_error_sector; v32.first_error_generation = v.first_error_generation; v32.last_error_sector = v.last_error_sector; v32.last_error_generation = v.last_error_generation; v32.badness = v.badness; if (copy_to_user(arg, &v32, sizeof(struct compat_floppy_write_errors))) return -EFAULT; return 0; } static int fd_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long param) { int drive = (long)bdev->bd_disk->private_data; switch (cmd) { case FDMSGON: case FDMSGOFF: case FDSETEMSGTRESH: case FDFLUSH: case FDWERRORCLR: case FDEJECT: case FDCLRPRM: case FDFMTBEG: case FDRESET: case FDTWADDLE: return fd_ioctl(bdev, mode, cmd, param); case FDSETMAXERRS: case FDGETMAXERRS: case FDGETDRVTYP: case FDFMTEND: case FDFMTTRK: case FDRAWCMD: return fd_ioctl(bdev, mode, cmd, (unsigned long)compat_ptr(param)); case FDSETPRM32: case FDDEFPRM32: return compat_set_geometry(bdev, mode, cmd, compat_ptr(param)); case FDGETPRM32: return compat_get_prm(drive, compat_ptr(param)); case FDSETDRVPRM32: return compat_setdrvprm(drive, compat_ptr(param)); case FDGETDRVPRM32: return compat_getdrvprm(drive, compat_ptr(param)); case FDPOLLDRVSTAT32: return compat_getdrvstat(drive, true, compat_ptr(param)); case FDGETDRVSTAT32: return compat_getdrvstat(drive, false, compat_ptr(param)); case FDGETFDCSTAT32: return compat_getfdcstat(drive, compat_ptr(param)); case FDWERRORGET32: return compat_werrorget(drive, compat_ptr(param)); } return -EINVAL; } #endif static void __init config_types(void) { bool has_drive = false; int drive; /* read drive info out of physical CMOS */ drive = 0; if (!UDP->cmos) UDP->cmos = FLOPPY0_TYPE; drive = 1; if (!UDP->cmos && FLOPPY1_TYPE) UDP->cmos = FLOPPY1_TYPE; /* FIXME: additional physical CMOS drive detection should go here */ for (drive = 0; drive < N_DRIVE; drive++) { unsigned int type = UDP->cmos; struct floppy_drive_params *params; const char *name = NULL; char temparea[32]; if (type < ARRAY_SIZE(default_drive_params)) { params = &default_drive_params[type].params; if (type) { name = default_drive_params[type].name; allowed_drive_mask |= 1 << drive; } else allowed_drive_mask &= ~(1 << drive); } else { params = &default_drive_params[0].params; snprintf(temparea, sizeof(temparea), "unknown type %d (usb?)", type); name = temparea; } if (name) { const char *prepend; if (!has_drive) { prepend = ""; has_drive = true; pr_info("Floppy drive(s):"); } else { prepend = ","; } pr_cont("%s fd%d is %s", prepend, drive, name); } *UDP = *params; } if (has_drive) pr_cont("\n"); } static void floppy_release(struct gendisk *disk, fmode_t mode) { int drive = (long)disk->private_data; mutex_lock(&floppy_mutex); mutex_lock(&open_lock); if (!UDRS->fd_ref--) { DPRINT("floppy_release with fd_ref == 0"); UDRS->fd_ref = 0; } if (!UDRS->fd_ref) opened_bdev[drive] = NULL; mutex_unlock(&open_lock); mutex_unlock(&floppy_mutex); } /* * floppy_open check for aliasing (/dev/fd0 can be the same as * /dev/PS0 etc), and disallows simultaneous access to the same * drive with different device numbers. */ static int floppy_open(struct block_device *bdev, fmode_t mode) { int drive = (long)bdev->bd_disk->private_data; int old_dev, new_dev; int try; int res = -EBUSY; char *tmp; mutex_lock(&floppy_mutex); mutex_lock(&open_lock); old_dev = UDRS->fd_device; if (opened_bdev[drive] && opened_bdev[drive] != bdev) goto out2; if (!UDRS->fd_ref && (UDP->flags & FD_BROKEN_DCL)) { set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); set_bit(FD_VERIFY_BIT, &UDRS->flags); } UDRS->fd_ref++; opened_bdev[drive] = bdev; res = -ENXIO; if (!floppy_track_buffer) { /* if opening an ED drive, reserve a big buffer, * else reserve a small one */ if ((UDP->cmos == 6) || (UDP->cmos == 5)) try = 64; /* Only 48 actually useful */ else try = 32; /* Only 24 actually useful */ tmp = (char *)fd_dma_mem_alloc(1024 * try); if (!tmp && !floppy_track_buffer) { try >>= 1; /* buffer only one side */ INFBOUND(try, 16); tmp = (char *)fd_dma_mem_alloc(1024 * try); } if (!tmp && !floppy_track_buffer) fallback_on_nodma_alloc(&tmp, 2048 * try); if (!tmp && !floppy_track_buffer) { DPRINT("Unable to allocate DMA memory\n"); goto out; } if (floppy_track_buffer) { if (tmp) fd_dma_mem_free((unsigned long)tmp, try * 1024); } else { buffer_min = buffer_max = -1; floppy_track_buffer = tmp; max_buffer_sectors = try; } } new_dev = MINOR(bdev->bd_dev); UDRS->fd_device = new_dev; set_capacity(disks[drive], floppy_sizes[new_dev]); if (old_dev != -1 && old_dev != new_dev) { if (buffer_drive == drive) buffer_track = -1; } if (UFDCS->rawcmd == 1) UFDCS->rawcmd = 2; if (!(mode & FMODE_NDELAY)) { if (mode & (FMODE_READ|FMODE_WRITE)) { UDRS->last_checked = 0; clear_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags); check_disk_change(bdev); if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags)) goto out; if (test_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags)) goto out; } res = -EROFS; if ((mode & FMODE_WRITE) && !test_bit(FD_DISK_WRITABLE_BIT, &UDRS->flags)) goto out; } mutex_unlock(&open_lock); mutex_unlock(&floppy_mutex); return 0; out: UDRS->fd_ref--; if (!UDRS->fd_ref) opened_bdev[drive] = NULL; out2: mutex_unlock(&open_lock); mutex_unlock(&floppy_mutex); return res; } /* * Check if the disk has been changed or if a change has been faked. */ static unsigned int floppy_check_events(struct gendisk *disk, unsigned int clearing) { int drive = (long)disk->private_data; if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags)) return DISK_EVENT_MEDIA_CHANGE; if (time_after(jiffies, UDRS->last_checked + UDP->checkfreq)) { if (lock_fdc(drive)) return 0; poll_drive(false, 0); process_fd_request(); } if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags) || test_bit(drive, &fake_change) || drive_no_geom(drive)) return DISK_EVENT_MEDIA_CHANGE; return 0; } /* * This implements "read block 0" for floppy_revalidate(). * Needed for format autodetection, checking whether there is * a disk in the drive, and whether that disk is writable. */ struct rb0_cbdata { int drive; struct completion complete; }; static void floppy_rb0_cb(struct bio *bio) { struct rb0_cbdata *cbdata = (struct rb0_cbdata *)bio->bi_private; int drive = cbdata->drive; if (bio->bi_status) { pr_info("floppy: error %d while reading block 0\n", bio->bi_status); set_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags); } complete(&cbdata->complete); } static int __floppy_read_block_0(struct block_device *bdev, int drive) { struct bio bio; struct bio_vec bio_vec; struct page *page; struct rb0_cbdata cbdata; size_t size; page = alloc_page(GFP_NOIO); if (!page) { process_fd_request(); return -ENOMEM; } size = bdev->bd_block_size; if (!size) size = 1024; cbdata.drive = drive; bio_init(&bio, &bio_vec, 1); bio_set_dev(&bio, bdev); bio_add_page(&bio, page, size, 0); bio.bi_iter.bi_sector = 0; bio.bi_flags |= (1 << BIO_QUIET); bio.bi_private = &cbdata; bio.bi_end_io = floppy_rb0_cb; bio_set_op_attrs(&bio, REQ_OP_READ, 0); init_completion(&cbdata.complete); submit_bio(&bio); process_fd_request(); wait_for_completion(&cbdata.complete); __free_page(page); return 0; } /* revalidate the floppy disk, i.e. trigger format autodetection by reading * the bootblock (block 0). "Autodetection" is also needed to check whether * there is a disk in the drive at all... Thus we also do it for fixed * geometry formats */ static int floppy_revalidate(struct gendisk *disk) { int drive = (long)disk->private_data; int cf; int res = 0; if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags) || test_bit(drive, &fake_change) || drive_no_geom(drive)) { if (WARN(atomic_read(&usage_count) == 0, "VFS: revalidate called on non-open device.\n")) return -EFAULT; res = lock_fdc(drive); if (res) return res; cf = (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags)); if (!(cf || test_bit(drive, &fake_change) || drive_no_geom(drive))) { process_fd_request(); /*already done by another thread */ return 0; } UDRS->maxblock = 0; UDRS->maxtrack = 0; if (buffer_drive == drive) buffer_track = -1; clear_bit(drive, &fake_change); clear_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); if (cf) UDRS->generation++; if (drive_no_geom(drive)) { /* auto-sensing */ res = __floppy_read_block_0(opened_bdev[drive], drive); } else { if (cf) poll_drive(false, FD_RAW_NEED_DISK); process_fd_request(); } } set_capacity(disk, floppy_sizes[UDRS->fd_device]); return res; } static const struct block_device_operations floppy_fops = { .owner = THIS_MODULE, .open = floppy_open, .release = floppy_release, .ioctl = fd_ioctl, .getgeo = fd_getgeo, .check_events = floppy_check_events, .revalidate_disk = floppy_revalidate, #ifdef CONFIG_COMPAT .compat_ioctl = fd_compat_ioctl, #endif }; /* * Floppy Driver initialization * ============================= */ /* Determine the floppy disk controller type */ /* This routine was written by David C. Niemi */ static char __init get_fdc_version(void) { int r; output_byte(FD_DUMPREGS); /* 82072 and better know DUMPREGS */ if (FDCS->reset) return FDC_NONE; r = result(); if (r <= 0x00) return FDC_NONE; /* No FDC present ??? */ if ((r == 1) && (reply_buffer[0] == 0x80)) { pr_info("FDC %d is an 8272A\n", fdc); return FDC_8272A; /* 8272a/765 don't know DUMPREGS */ } if (r != 10) { pr_info("FDC %d init: DUMPREGS: unexpected return of %d bytes.\n", fdc, r); return FDC_UNKNOWN; } if (!fdc_configure()) { pr_info("FDC %d is an 82072\n", fdc); return FDC_82072; /* 82072 doesn't know CONFIGURE */ } output_byte(FD_PERPENDICULAR); if (need_more_output() == MORE_OUTPUT) { output_byte(0); } else { pr_info("FDC %d is an 82072A\n", fdc); return FDC_82072A; /* 82072A as found on Sparcs. */ } output_byte(FD_UNLOCK); r = result(); if ((r == 1) && (reply_buffer[0] == 0x80)) { pr_info("FDC %d is a pre-1991 82077\n", fdc); return FDC_82077_ORIG; /* Pre-1991 82077, doesn't know * LOCK/UNLOCK */ } if ((r != 1) || (reply_buffer[0] != 0x00)) { pr_info("FDC %d init: UNLOCK: unexpected return of %d bytes.\n", fdc, r); return FDC_UNKNOWN; } output_byte(FD_PARTID); r = result(); if (r != 1) { pr_info("FDC %d init: PARTID: unexpected return of %d bytes.\n", fdc, r); return FDC_UNKNOWN; } if (reply_buffer[0] == 0x80) { pr_info("FDC %d is a post-1991 82077\n", fdc); return FDC_82077; /* Revised 82077AA passes all the tests */ } switch (reply_buffer[0] >> 5) { case 0x0: /* Either a 82078-1 or a 82078SL running at 5Volt */ pr_info("FDC %d is an 82078.\n", fdc); return FDC_82078; case 0x1: pr_info("FDC %d is a 44pin 82078\n", fdc); return FDC_82078; case 0x2: pr_info("FDC %d is a S82078B\n", fdc); return FDC_S82078B; case 0x3: pr_info("FDC %d is a National Semiconductor PC87306\n", fdc); return FDC_87306; default: pr_info("FDC %d init: 82078 variant with unknown PARTID=%d.\n", fdc, reply_buffer[0] >> 5); return FDC_82078_UNKN; } } /* get_fdc_version */ /* lilo configuration */ static void __init floppy_set_flags(int *ints, int param, int param2) { int i; for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) { if (param) default_drive_params[i].params.flags |= param2; else default_drive_params[i].params.flags &= ~param2; } DPRINT("%s flag 0x%x\n", param2 ? "Setting" : "Clearing", param); } static void __init daring(int *ints, int param, int param2) { int i; for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) { if (param) { default_drive_params[i].params.select_delay = 0; default_drive_params[i].params.flags |= FD_SILENT_DCL_CLEAR; } else { default_drive_params[i].params.select_delay = 2 * HZ / 100; default_drive_params[i].params.flags &= ~FD_SILENT_DCL_CLEAR; } } DPRINT("Assuming %s floppy hardware\n", param ? "standard" : "broken"); } static void __init set_cmos(int *ints, int dummy, int dummy2) { int current_drive = 0; if (ints[0] != 2) { DPRINT("wrong number of parameters for CMOS\n"); return; } current_drive = ints[1]; if (current_drive < 0 || current_drive >= 8) { DPRINT("bad drive for set_cmos\n"); return; } #if N_FDC > 1 if (current_drive >= 4 && !FDC2) FDC2 = 0x370; #endif DP->cmos = ints[2]; DPRINT("setting CMOS code to %d\n", ints[2]); } static struct param_table { const char *name; void (*fn) (int *ints, int param, int param2); int *var; int def_param; int param2; } config_params[] __initdata = { {"allowed_drive_mask", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */ {"all_drives", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */ {"asus_pci", NULL, &allowed_drive_mask, 0x33, 0}, {"irq", NULL, &FLOPPY_IRQ, 6, 0}, {"dma", NULL, &FLOPPY_DMA, 2, 0}, {"daring", daring, NULL, 1, 0}, #if N_FDC > 1 {"two_fdc", NULL, &FDC2, 0x370, 0}, {"one_fdc", NULL, &FDC2, 0, 0}, #endif {"thinkpad", floppy_set_flags, NULL, 1, FD_INVERTED_DCL}, {"broken_dcl", floppy_set_flags, NULL, 1, FD_BROKEN_DCL}, {"messages", floppy_set_flags, NULL, 1, FTD_MSG}, {"silent_dcl_clear", floppy_set_flags, NULL, 1, FD_SILENT_DCL_CLEAR}, {"debug", floppy_set_flags, NULL, 1, FD_DEBUG}, {"nodma", NULL, &can_use_virtual_dma, 1, 0}, {"omnibook", NULL, &can_use_virtual_dma, 1, 0}, {"yesdma", NULL, &can_use_virtual_dma, 0, 0}, {"fifo_depth", NULL, &fifo_depth, 0xa, 0}, {"nofifo", NULL, &no_fifo, 0x20, 0}, {"usefifo", NULL, &no_fifo, 0, 0}, {"cmos", set_cmos, NULL, 0, 0}, {"slow", NULL, &slow_floppy, 1, 0}, {"unexpected_interrupts", NULL, &print_unex, 1, 0}, {"no_unexpected_interrupts", NULL, &print_unex, 0, 0}, {"L40SX", NULL, &print_unex, 0, 0} EXTRA_FLOPPY_PARAMS }; static int __init floppy_setup(char *str) { int i; int param; int ints[11]; str = get_options(str, ARRAY_SIZE(ints), ints); if (str) { for (i = 0; i < ARRAY_SIZE(config_params); i++) { if (strcmp(str, config_params[i].name) == 0) { if (ints[0]) param = ints[1]; else param = config_params[i].def_param; if (config_params[i].fn) config_params[i].fn(ints, param, config_params[i]. param2); if (config_params[i].var) { DPRINT("%s=%d\n", str, param); *config_params[i].var = param; } return 1; } } } if (str) { DPRINT("unknown floppy option [%s]\n", str); DPRINT("allowed options are:"); for (i = 0; i < ARRAY_SIZE(config_params); i++) pr_cont(" %s", config_params[i].name); pr_cont("\n"); } else DPRINT("botched floppy option\n"); DPRINT("Read Documentation/blockdev/floppy.txt\n"); return 0; } static int have_no_fdc = -ENODEV; static ssize_t floppy_cmos_show(struct device *dev, struct device_attribute *attr, char *buf) { struct platform_device *p = to_platform_device(dev); int drive; drive = p->id; return sprintf(buf, "%X\n", UDP->cmos); } static DEVICE_ATTR(cmos, 0444, floppy_cmos_show, NULL); static struct attribute *floppy_dev_attrs[] = { &dev_attr_cmos.attr, NULL }; ATTRIBUTE_GROUPS(floppy_dev); static void floppy_device_release(struct device *dev) { } static int floppy_resume(struct device *dev) { int fdc; for (fdc = 0; fdc < N_FDC; fdc++) if (FDCS->address != -1) user_reset_fdc(-1, FD_RESET_ALWAYS, false); return 0; } static const struct dev_pm_ops floppy_pm_ops = { .resume = floppy_resume, .restore = floppy_resume, }; static struct platform_driver floppy_driver = { .driver = { .name = "floppy", .pm = &floppy_pm_ops, }, }; static const struct blk_mq_ops floppy_mq_ops = { .queue_rq = floppy_queue_rq, }; static struct platform_device floppy_device[N_DRIVE]; static bool floppy_available(int drive) { if (!(allowed_drive_mask & (1 << drive))) return false; if (fdc_state[FDC(drive)].version == FDC_NONE) return false; return true; } static struct kobject *floppy_find(dev_t dev, int *part, void *data) { int drive = (*part & 3) | ((*part & 0x80) >> 5); if (drive >= N_DRIVE || !floppy_available(drive)) return NULL; if (((*part >> 2) & 0x1f) >= ARRAY_SIZE(floppy_type)) return NULL; *part = 0; return get_disk_and_module(disks[drive]); } static int __init do_floppy_init(void) { int i, unit, drive, err; set_debugt(); interruptjiffies = resultjiffies = jiffies; #if defined(CONFIG_PPC) if (check_legacy_ioport(FDC1)) return -ENODEV; #endif raw_cmd = NULL; floppy_wq = alloc_ordered_workqueue("floppy", 0); if (!floppy_wq) return -ENOMEM; for (drive = 0; drive < N_DRIVE; drive++) { disks[drive] = alloc_disk(1); if (!disks[drive]) { err = -ENOMEM; goto out_put_disk; } disks[drive]->queue = blk_mq_init_sq_queue(&tag_sets[drive], &floppy_mq_ops, 2, BLK_MQ_F_SHOULD_MERGE); if (IS_ERR(disks[drive]->queue)) { err = PTR_ERR(disks[drive]->queue); disks[drive]->queue = NULL; goto out_put_disk; } blk_queue_bounce_limit(disks[drive]->queue, BLK_BOUNCE_HIGH); blk_queue_max_hw_sectors(disks[drive]->queue, 64); disks[drive]->major = FLOPPY_MAJOR; disks[drive]->first_minor = TOMINOR(drive); disks[drive]->fops = &floppy_fops; disks[drive]->events = DISK_EVENT_MEDIA_CHANGE; sprintf(disks[drive]->disk_name, "fd%d", drive); timer_setup(&motor_off_timer[drive], motor_off_callback, 0); } err = register_blkdev(FLOPPY_MAJOR, "fd"); if (err) goto out_put_disk; err = platform_driver_register(&floppy_driver); if (err) goto out_unreg_blkdev; blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE, floppy_find, NULL, NULL); for (i = 0; i < 256; i++) if (ITYPE(i)) floppy_sizes[i] = floppy_type[ITYPE(i)].size; else floppy_sizes[i] = MAX_DISK_SIZE << 1; reschedule_timeout(MAXTIMEOUT, "floppy init"); config_types(); for (i = 0; i < N_FDC; i++) { fdc = i; memset(FDCS, 0, sizeof(*FDCS)); FDCS->dtr = -1; FDCS->dor = 0x4; #if defined(__sparc__) || defined(__mc68000__) /*sparcs/sun3x don't have a DOR reset which we can fall back on to */ #ifdef __mc68000__ if (MACH_IS_SUN3X) #endif FDCS->version = FDC_82072A; #endif } use_virtual_dma = can_use_virtual_dma & 1; fdc_state[0].address = FDC1; if (fdc_state[0].address == -1) { cancel_delayed_work(&fd_timeout); err = -ENODEV; goto out_unreg_region; } #if N_FDC > 1 fdc_state[1].address = FDC2; #endif fdc = 0; /* reset fdc in case of unexpected interrupt */ err = floppy_grab_irq_and_dma(); if (err) { cancel_delayed_work(&fd_timeout); err = -EBUSY; goto out_unreg_region; } /* initialise drive state */ for (drive = 0; drive < N_DRIVE; drive++) { memset(UDRS, 0, sizeof(*UDRS)); memset(UDRWE, 0, sizeof(*UDRWE)); set_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags); set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); set_bit(FD_VERIFY_BIT, &UDRS->flags); UDRS->fd_device = -1; floppy_track_buffer = NULL; max_buffer_sectors = 0; } /* * Small 10 msec delay to let through any interrupt that * initialization might have triggered, to not * confuse detection: */ msleep(10); for (i = 0; i < N_FDC; i++) { fdc = i; FDCS->driver_version = FD_DRIVER_VERSION; for (unit = 0; unit < 4; unit++) FDCS->track[unit] = 0; if (FDCS->address == -1) continue; FDCS->rawcmd = 2; if (user_reset_fdc(-1, FD_RESET_ALWAYS, false)) { /* free ioports reserved by floppy_grab_irq_and_dma() */ floppy_release_regions(fdc); FDCS->address = -1; FDCS->version = FDC_NONE; continue; } /* Try to determine the floppy controller type */ FDCS->version = get_fdc_version(); if (FDCS->version == FDC_NONE) { /* free ioports reserved by floppy_grab_irq_and_dma() */ floppy_release_regions(fdc); FDCS->address = -1; continue; } if (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A) can_use_virtual_dma = 0; have_no_fdc = 0; /* Not all FDCs seem to be able to handle the version command * properly, so force a reset for the standard FDC clones, * to avoid interrupt garbage. */ user_reset_fdc(-1, FD_RESET_ALWAYS, false); } fdc = 0; cancel_delayed_work(&fd_timeout); current_drive = 0; initialized = true; if (have_no_fdc) { DPRINT("no floppy controllers found\n"); err = have_no_fdc; goto out_release_dma; } for (drive = 0; drive < N_DRIVE; drive++) { if (!floppy_available(drive)) continue; floppy_device[drive].name = floppy_device_name; floppy_device[drive].id = drive; floppy_device[drive].dev.release = floppy_device_release; floppy_device[drive].dev.groups = floppy_dev_groups; err = platform_device_register(&floppy_device[drive]); if (err) goto out_remove_drives; /* to be cleaned up... */ disks[drive]->private_data = (void *)(long)drive; disks[drive]->flags |= GENHD_FL_REMOVABLE; device_add_disk(&floppy_device[drive].dev, disks[drive], NULL); } return 0; out_remove_drives: while (drive--) { if (floppy_available(drive)) { del_gendisk(disks[drive]); platform_device_unregister(&floppy_device[drive]); } } out_release_dma: if (atomic_read(&usage_count)) floppy_release_irq_and_dma(); out_unreg_region: blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256); platform_driver_unregister(&floppy_driver); out_unreg_blkdev: unregister_blkdev(FLOPPY_MAJOR, "fd"); out_put_disk: destroy_workqueue(floppy_wq); for (drive = 0; drive < N_DRIVE; drive++) { if (!disks[drive]) break; if (disks[drive]->queue) { del_timer_sync(&motor_off_timer[drive]); blk_cleanup_queue(disks[drive]->queue); disks[drive]->queue = NULL; blk_mq_free_tag_set(&tag_sets[drive]); } put_disk(disks[drive]); } return err; } #ifndef MODULE static __init void floppy_async_init(void *data, async_cookie_t cookie) { do_floppy_init(); } #endif static int __init floppy_init(void) { #ifdef MODULE return do_floppy_init(); #else /* Don't hold up the bootup by the floppy initialization */ async_schedule(floppy_async_init, NULL); return 0; #endif } static const struct io_region { int offset; int size; } io_regions[] = { { 2, 1 }, /* address + 3 is sometimes reserved by pnp bios for motherboard */ { 4, 2 }, /* address + 6 is reserved, and may be taken by IDE. * Unfortunately, Adaptec doesn't know this :-(, */ { 7, 1 }, }; static void floppy_release_allocated_regions(int fdc, const struct io_region *p) { while (p != io_regions) { p--; release_region(FDCS->address + p->offset, p->size); } } #define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)])) static int floppy_request_regions(int fdc) { const struct io_region *p; for (p = io_regions; p < ARRAY_END(io_regions); p++) { if (!request_region(FDCS->address + p->offset, p->size, "floppy")) { DPRINT("Floppy io-port 0x%04lx in use\n", FDCS->address + p->offset); floppy_release_allocated_regions(fdc, p); return -EBUSY; } } return 0; } static void floppy_release_regions(int fdc) { floppy_release_allocated_regions(fdc, ARRAY_END(io_regions)); } static int floppy_grab_irq_and_dma(void) { if (atomic_inc_return(&usage_count) > 1) return 0; /* * We might have scheduled a free_irq(), wait it to * drain first: */ flush_workqueue(floppy_wq); if (fd_request_irq()) { DPRINT("Unable to grab IRQ%d for the floppy driver\n", FLOPPY_IRQ); atomic_dec(&usage_count); return -1; } if (fd_request_dma()) { DPRINT("Unable to grab DMA%d for the floppy driver\n", FLOPPY_DMA); if (can_use_virtual_dma & 2) use_virtual_dma = can_use_virtual_dma = 1; if (!(can_use_virtual_dma & 1)) { fd_free_irq(); atomic_dec(&usage_count); return -1; } } for (fdc = 0; fdc < N_FDC; fdc++) { if (FDCS->address != -1) { if (floppy_request_regions(fdc)) goto cleanup; } } for (fdc = 0; fdc < N_FDC; fdc++) { if (FDCS->address != -1) { reset_fdc_info(1); fd_outb(FDCS->dor, FD_DOR); } } fdc = 0; set_dor(0, ~0, 8); /* avoid immediate interrupt */ for (fdc = 0; fdc < N_FDC; fdc++) if (FDCS->address != -1) fd_outb(FDCS->dor, FD_DOR); /* * The driver will try and free resources and relies on us * to know if they were allocated or not. */ fdc = 0; irqdma_allocated = 1; return 0; cleanup: fd_free_irq(); fd_free_dma(); while (--fdc >= 0) floppy_release_regions(fdc); atomic_dec(&usage_count); return -1; } static void floppy_release_irq_and_dma(void) { int old_fdc; #ifndef __sparc__ int drive; #endif long tmpsize; unsigned long tmpaddr; if (!atomic_dec_and_test(&usage_count)) return; if (irqdma_allocated) { fd_disable_dma(); fd_free_dma(); fd_free_irq(); irqdma_allocated = 0; } set_dor(0, ~0, 8); #if N_FDC > 1 set_dor(1, ~8, 0); #endif if (floppy_track_buffer && max_buffer_sectors) { tmpsize = max_buffer_sectors * 1024; tmpaddr = (unsigned long)floppy_track_buffer; floppy_track_buffer = NULL; max_buffer_sectors = 0; buffer_min = buffer_max = -1; fd_dma_mem_free(tmpaddr, tmpsize); } #ifndef __sparc__ for (drive = 0; drive < N_FDC * 4; drive++) if (timer_pending(motor_off_timer + drive)) pr_info("motor off timer %d still active\n", drive); #endif if (delayed_work_pending(&fd_timeout)) pr_info("floppy timer still active:%s\n", timeout_message); if (delayed_work_pending(&fd_timer)) pr_info("auxiliary floppy timer still active\n"); if (work_pending(&floppy_work)) pr_info("work still pending\n"); old_fdc = fdc; for (fdc = 0; fdc < N_FDC; fdc++) if (FDCS->address != -1) floppy_release_regions(fdc); fdc = old_fdc; } #ifdef MODULE static char *floppy; static void __init parse_floppy_cfg_string(char *cfg) { char *ptr; while (*cfg) { ptr = cfg; while (*cfg && *cfg != ' ' && *cfg != '\t') cfg++; if (*cfg) { *cfg = '\0'; cfg++; } if (*ptr) floppy_setup(ptr); } } static int __init floppy_module_init(void) { if (floppy) parse_floppy_cfg_string(floppy); return floppy_init(); } module_init(floppy_module_init); static void __exit floppy_module_exit(void) { int drive; blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256); unregister_blkdev(FLOPPY_MAJOR, "fd"); platform_driver_unregister(&floppy_driver); destroy_workqueue(floppy_wq); for (drive = 0; drive < N_DRIVE; drive++) { del_timer_sync(&motor_off_timer[drive]); if (floppy_available(drive)) { del_gendisk(disks[drive]); platform_device_unregister(&floppy_device[drive]); } blk_cleanup_queue(disks[drive]->queue); blk_mq_free_tag_set(&tag_sets[drive]); /* * These disks have not called add_disk(). Don't put down * queue reference in put_disk(). */ if (!(allowed_drive_mask & (1 << drive)) || fdc_state[FDC(drive)].version == FDC_NONE) disks[drive]->queue = NULL; put_disk(disks[drive]); } cancel_delayed_work_sync(&fd_timeout); cancel_delayed_work_sync(&fd_timer); if (atomic_read(&usage_count)) floppy_release_irq_and_dma(); /* eject disk, if any */ fd_eject(0); } module_exit(floppy_module_exit); module_param(floppy, charp, 0); module_param(FLOPPY_IRQ, int, 0); module_param(FLOPPY_DMA, int, 0); MODULE_AUTHOR("Alain L. Knaff"); MODULE_SUPPORTED_DEVICE("fd"); MODULE_LICENSE("GPL"); /* This doesn't actually get used other than for module information */ static const struct pnp_device_id floppy_pnpids[] = { {"PNP0700", 0}, {} }; MODULE_DEVICE_TABLE(pnp, floppy_pnpids); #else __setup("floppy=", floppy_setup); module_init(floppy_init) #endif MODULE_ALIAS_BLOCKDEV_MAJOR(FLOPPY_MAJOR);
./CrossVul/dataset_final_sorted/CWE-369/c/bad_967_0
crossvul-cpp_data_good_2580_0
/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* vim: set sw=4 sts=4 expandtab: */ /* rsvg-filter.c: Provides filters Copyright (C) 2004 Caleb Moore This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Author: Caleb Moore <c.moore@student.unsw.edu.au> */ #include "config.h" #include "rsvg-private.h" #include "rsvg-filter.h" #include "rsvg-styles.h" #include "rsvg-image.h" #include "rsvg-css.h" #include "rsvg-cairo-render.h" #include <string.h> #include <math.h> /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveOutput RsvgFilterPrimitiveOutput; struct _RsvgFilterPrimitiveOutput { cairo_surface_t *surface; RsvgIRect bounds; }; typedef struct _RsvgFilterContext RsvgFilterContext; struct _RsvgFilterContext { gint width, height; RsvgFilter *filter; GHashTable *results; cairo_surface_t *source_surface; cairo_surface_t *bg_surface; RsvgFilterPrimitiveOutput lastresult; cairo_matrix_t affine; cairo_matrix_t paffine; int channelmap[4]; RsvgDrawingCtx *ctx; }; typedef struct _RsvgFilterPrimitive RsvgFilterPrimitive; /* We don't have real subclassing here. If you derive something from * RsvgFilterPrimitive, and don't need any special code to free your * RsvgFilterPrimitiveFoo structure, you can just pass rsvg_filter_primitive_free * to rsvg_rust_cnode_new() for the destructor. Otherwise, create a custom destructor like this: * * static void * rsvg_filter_primitive_foo_free (gpointer impl) * { * RsvgFilterPrimitiveFoo *foo = impl; * * g_free (foo->my_custom_stuff); * g_free (foo->more_custom_stuff); * ... etc ... * * rsvg_filter_primitive_free (impl); * } * * That last call to rsvg_filter_primitive_free() will free the base RsvgFilterPrimitive's own fields, * and your whole structure itself, via g_free(). */ struct _RsvgFilterPrimitive { RsvgLength x, y, width, height; gboolean x_specified; gboolean y_specified; gboolean width_specified; gboolean height_specified; GString *in; GString *result; void (*render) (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx); }; /*************************************************************/ /*************************************************************/ static void rsvg_filter_primitive_free (gpointer impl) { RsvgFilterPrimitive *primitive = impl; g_string_free (primitive->in, TRUE); g_string_free (primitive->result, TRUE); g_free (primitive); } static void filter_primitive_set_x_y_width_height_atts (RsvgFilterPrimitive *prim, RsvgPropertyBag *atts) { const char *value; if ((value = rsvg_property_bag_lookup (atts, "x"))) { prim->x = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); prim->x_specified = TRUE; } if ((value = rsvg_property_bag_lookup (atts, "y"))) { prim->y = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); prim->y_specified = TRUE; } if ((value = rsvg_property_bag_lookup (atts, "width"))) { prim->width = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); prim->width_specified = TRUE; } if ((value = rsvg_property_bag_lookup (atts, "height"))) { prim->height = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); prim->height_specified = TRUE; } } static void rsvg_filter_primitive_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { primitive->render (node, primitive, ctx); } static RsvgIRect rsvg_filter_primitive_get_bounds (RsvgFilterPrimitive * self, RsvgFilterContext * ctx) { RsvgBbox box, otherbox; cairo_matrix_t affine; cairo_matrix_init_identity (&affine); rsvg_bbox_init (&box, &affine); rsvg_bbox_init (&otherbox, &ctx->affine); otherbox.virgin = 0; if (ctx->filter->filterunits == objectBoundingBox) rsvg_drawing_ctx_push_view_box (ctx->ctx, 1., 1.); otherbox.rect.x = rsvg_length_normalize (&ctx->filter->x, ctx->ctx); otherbox.rect.y = rsvg_length_normalize (&ctx->filter->y, ctx->ctx); otherbox.rect.width = rsvg_length_normalize (&ctx->filter->width, ctx->ctx); otherbox.rect.height = rsvg_length_normalize (&ctx->filter->height, ctx->ctx); if (ctx->filter->filterunits == objectBoundingBox) rsvg_drawing_ctx_pop_view_box (ctx->ctx); rsvg_bbox_insert (&box, &otherbox); if (self != NULL) { if (self->x_specified || self->y_specified || self->width_specified || self->height_specified) { rsvg_bbox_init (&otherbox, &ctx->paffine); otherbox.virgin = 0; if (ctx->filter->primitiveunits == objectBoundingBox) rsvg_drawing_ctx_push_view_box (ctx->ctx, 1., 1.); if (self->x_specified) otherbox.rect.x = rsvg_length_normalize (&self->x, ctx->ctx); else otherbox.rect.x = 0; if (self->y_specified) otherbox.rect.y = rsvg_length_normalize (&self->y, ctx->ctx); else otherbox.rect.y = 0; if (self->width_specified || self->height_specified) { double curr_vbox_w, curr_vbox_h; rsvg_drawing_ctx_get_view_box_size (ctx->ctx, &curr_vbox_w, &curr_vbox_h); if (self->width_specified) otherbox.rect.width = rsvg_length_normalize (&self->width, ctx->ctx); else otherbox.rect.width = curr_vbox_w; if (self->height_specified) otherbox.rect.height = rsvg_length_normalize (&self->height, ctx->ctx); else otherbox.rect.height = curr_vbox_h; } if (ctx->filter->primitiveunits == objectBoundingBox) rsvg_drawing_ctx_pop_view_box (ctx->ctx); rsvg_bbox_clip (&box, &otherbox); } } rsvg_bbox_init (&otherbox, &affine); otherbox.virgin = 0; otherbox.rect.x = 0; otherbox.rect.y = 0; otherbox.rect.width = ctx->width; otherbox.rect.height = ctx->height; rsvg_bbox_clip (&box, &otherbox); { RsvgIRect output = { box.rect.x, box.rect.y, box.rect.x + box.rect.width, box.rect.y + box.rect.height }; return output; } } static cairo_surface_t * _rsvg_image_surface_new (int width, int height) { cairo_surface_t *surface; surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); if (cairo_surface_status (surface) != CAIRO_STATUS_SUCCESS) { cairo_surface_destroy (surface); return NULL; } return surface; } static guchar get_interp_pixel (guchar * src, gdouble ox, gdouble oy, guchar ch, RsvgIRect boundarys, guint rowstride) { double xmod, ymod; double dist1, dist2, dist3, dist4; double c, c1, c2, c3, c4; double fox, foy, cox, coy; xmod = fmod (ox, 1.0); ymod = fmod (oy, 1.0); dist1 = (1 - xmod) * (1 - ymod); dist2 = (xmod) * (1 - ymod); dist3 = (xmod) * (ymod); dist4 = (1 - xmod) * (ymod); fox = floor (ox); foy = floor (oy); cox = ceil (ox); coy = ceil (oy); if (fox <= boundarys.x0 || fox >= boundarys.x1 || foy <= boundarys.y0 || foy >= boundarys.y1) c1 = 0; else c1 = src[(guint) foy * rowstride + (guint) fox * 4 + ch]; if (cox <= boundarys.x0 || cox >= boundarys.x1 || foy <= boundarys.y0 || foy >= boundarys.y1) c2 = 0; else c2 = src[(guint) foy * rowstride + (guint) cox * 4 + ch]; if (cox <= boundarys.x0 || cox >= boundarys.x1 || coy <= boundarys.y0 || coy >= boundarys.y1) c3 = 0; else c3 = src[(guint) coy * rowstride + (guint) cox * 4 + ch]; if (fox <= boundarys.x0 || fox >= boundarys.x1 || coy <= boundarys.y0 || coy >= boundarys.y1) c4 = 0; else c4 = src[(guint) coy * rowstride + (guint) fox * 4 + ch]; c = (c1 * dist1 + c2 * dist2 + c3 * dist3 + c4 * dist4) / (dist1 + dist2 + dist3 + dist4); return (guchar) c; } static void rsvg_filter_fix_coordinate_system (RsvgFilterContext * ctx, RsvgState * state, RsvgBbox *bbox) { int x, y, height, width; x = bbox->rect.x; y = bbox->rect.y; width = bbox->rect.width; height = bbox->rect.height; ctx->width = cairo_image_surface_get_width (ctx->source_surface); ctx->height = cairo_image_surface_get_height (ctx->source_surface); ctx->affine = state->affine; if (ctx->filter->filterunits == objectBoundingBox) { cairo_matrix_t affine; cairo_matrix_init (&affine, width, 0, 0, height, x, y); cairo_matrix_multiply (&ctx->affine, &affine, &ctx->affine); } ctx->paffine = state->affine; if (ctx->filter->primitiveunits == objectBoundingBox) { cairo_matrix_t affine; cairo_matrix_init (&affine, width, 0, 0, height, x, y); cairo_matrix_multiply (&ctx->paffine, &affine, &ctx->paffine); } } static gboolean rectangle_intersect (gint ax, gint ay, gint awidth, gint aheight, gint bx, gint by, gint bwidth, gint bheight, gint *rx, gint *ry, gint *rwidth, gint *rheight) { gint rx1, ry1, rx2, ry2; rx1 = MAX (ax, bx); ry1 = MAX (ay, by); rx2 = MIN (ax + awidth, bx + bwidth); ry2 = MIN (ay + aheight, by + bheight); if (rx2 > rx1 && ry2 > ry1) { *rx = rx1; *ry = ry1; *rwidth = rx2 - rx1; *rheight = ry2 - ry1; return TRUE; } else { *rx = *ry = *rwidth = *rheight = 0; return FALSE; } } static void rsvg_alpha_blt (cairo_surface_t *src, gint srcx, gint srcy, gint srcwidth, gint srcheight, cairo_surface_t *dst, gint dstx, gint dsty) { gint src_surf_width, src_surf_height; gint dst_surf_width, dst_surf_height; gint src_clipped_x, src_clipped_y, src_clipped_width, src_clipped_height; gint dst_clipped_x, dst_clipped_y, dst_clipped_width, dst_clipped_height; gint x, y, srcrowstride, dstrowstride, sx, sy, dx, dy; guchar *src_pixels, *dst_pixels; g_assert (cairo_image_surface_get_format (src) == CAIRO_FORMAT_ARGB32); g_assert (cairo_image_surface_get_format (dst) == CAIRO_FORMAT_ARGB32); cairo_surface_flush (src); src_surf_width = cairo_image_surface_get_width (src); src_surf_height = cairo_image_surface_get_height (src); dst_surf_width = cairo_image_surface_get_width (dst); dst_surf_height = cairo_image_surface_get_height (dst); if (!rectangle_intersect (0, 0, src_surf_width, src_surf_height, srcx, srcy, srcwidth, srcheight, &src_clipped_x, &src_clipped_y, &src_clipped_width, &src_clipped_height)) return; /* source rectangle is not in source surface */ if (!rectangle_intersect (0, 0, dst_surf_width, dst_surf_height, dstx, dsty, src_clipped_width, src_clipped_height, &dst_clipped_x, &dst_clipped_y, &dst_clipped_width, &dst_clipped_height)) return; /* dest rectangle is not in dest surface */ srcrowstride = cairo_image_surface_get_stride (src); dstrowstride = cairo_image_surface_get_stride (dst); src_pixels = cairo_image_surface_get_data (src); dst_pixels = cairo_image_surface_get_data (dst); for (y = 0; y < dst_clipped_height; y++) for (x = 0; x < dst_clipped_width; x++) { guint a, c, ad, cd, ar, cr, i; sx = x + src_clipped_x; sy = y + src_clipped_y; dx = x + dst_clipped_x; dy = y + dst_clipped_y; a = src_pixels[4 * sx + sy * srcrowstride + 3]; if (a) { ad = dst_pixels[4 * dx + dy * dstrowstride + 3]; ar = a + ad * (255 - a) / 255; dst_pixels[4 * dx + dy * dstrowstride + 3] = ar; for (i = 0; i < 3; i++) { c = src_pixels[4 * sx + sy * srcrowstride + i]; cd = dst_pixels[4 * dx + dy * dstrowstride + i]; cr = c + cd * (255 - a) / 255; dst_pixels[4 * dx + dy * dstrowstride + i] = cr; } } } cairo_surface_mark_dirty (dst); } static gboolean rsvg_art_affine_image (cairo_surface_t *img, cairo_surface_t *intermediate, cairo_matrix_t *affine, double w, double h) { cairo_matrix_t inv_affine, raw_inv_affine; gint intstride; gint basestride; gint basex, basey; gdouble fbasex, fbasey; gdouble rawx, rawy; guchar *intpix; guchar *basepix; gint i, j, k, basebpp, ii, jj; gboolean has_alpha; gdouble pixsum[4]; gboolean xrunnoff, yrunnoff; gint iwidth, iheight; gint width, height; g_assert (cairo_image_surface_get_format (intermediate) == CAIRO_FORMAT_ARGB32); cairo_surface_flush (img); width = cairo_image_surface_get_width (img); height = cairo_image_surface_get_height (img); iwidth = cairo_image_surface_get_width (intermediate); iheight = cairo_image_surface_get_height (intermediate); has_alpha = cairo_image_surface_get_format (img) == CAIRO_FORMAT_ARGB32; basestride = cairo_image_surface_get_stride (img); intstride = cairo_image_surface_get_stride (intermediate); basepix = cairo_image_surface_get_data (img); intpix = cairo_image_surface_get_data (intermediate); basebpp = has_alpha ? 4 : 3; raw_inv_affine = *affine; if (cairo_matrix_invert (&raw_inv_affine) != CAIRO_STATUS_SUCCESS) return FALSE; cairo_matrix_init_scale (&inv_affine, w, h); cairo_matrix_multiply (&inv_affine, &inv_affine, affine); if (cairo_matrix_invert (&inv_affine) != CAIRO_STATUS_SUCCESS) return FALSE; /*apply the transformation */ for (i = 0; i < iwidth; i++) for (j = 0; j < iheight; j++) { fbasex = (inv_affine.xx * (double) i + inv_affine.xy * (double) j + inv_affine.x0) * (double) width; fbasey = (inv_affine.yx * (double) i + inv_affine.yy * (double) j + inv_affine.y0) * (double) height; basex = floor (fbasex); basey = floor (fbasey); rawx = raw_inv_affine.xx * i + raw_inv_affine.xy * j + raw_inv_affine.x0; rawy = raw_inv_affine.yx * i + raw_inv_affine.yy * j + raw_inv_affine.y0; if (rawx < 0 || rawy < 0 || rawx >= w || rawy >= h || basex < 0 || basey < 0 || basex >= width || basey >= height) { for (k = 0; k < 4; k++) intpix[i * 4 + j * intstride + k] = 0; } else { if (basex < 0 || basex + 1 >= width) xrunnoff = TRUE; else xrunnoff = FALSE; if (basey < 0 || basey + 1 >= height) yrunnoff = TRUE; else yrunnoff = FALSE; for (k = 0; k < basebpp; k++) pixsum[k] = 0; for (ii = 0; ii < 2; ii++) for (jj = 0; jj < 2; jj++) { if (basex + ii < 0 || basey + jj < 0 || basex + ii >= width || basey + jj >= height); else { for (k = 0; k < basebpp; k++) { pixsum[k] += (double) basepix[basebpp * (basex + ii) + (basey + jj) * basestride + k] * (xrunnoff ? 1 : fabs (fbasex - (double) (basex + (1 - ii)))) * (yrunnoff ? 1 : fabs (fbasey - (double) (basey + (1 - jj)))); } } } for (k = 0; k < basebpp; k++) intpix[i * 4 + j * intstride + k] = pixsum[k]; if (!has_alpha) intpix[i * 4 + j * intstride + 3] = 255; } } /* Don't need cairo_surface_mark_dirty(intermediate) here since * the only caller does further work and then calls that himself. */ return TRUE; } static void rsvg_filter_free_pair (gpointer value) { RsvgFilterPrimitiveOutput *output; output = (RsvgFilterPrimitiveOutput *) value; cairo_surface_destroy (output->surface); g_free (output); } static void rsvg_filter_context_free (RsvgFilterContext * ctx) { if (!ctx) return; if (ctx->bg_surface) cairo_surface_destroy (ctx->bg_surface); g_free (ctx); } static gboolean node_is_filter_primitive (RsvgNode *node) { RsvgNodeType type = rsvg_node_get_type (node); return type > RSVG_NODE_TYPE_FILTER_PRIMITIVE_FIRST && type < RSVG_NODE_TYPE_FILTER_PRIMITIVE_LAST; } static gboolean render_child_if_filter_primitive (RsvgNode *node, gpointer data) { RsvgFilterContext *filter_ctx = data; if (node_is_filter_primitive (node)) { RsvgFilterPrimitive *primitive; primitive = rsvg_rust_cnode_get_impl (node); rsvg_filter_primitive_render (node, primitive, filter_ctx); } return TRUE; } /** * rsvg_filter_render: * @node: a pointer to the filter node to use * @source: the a #cairo_surface_t of type %CAIRO_SURFACE_TYPE_IMAGE * @context: the context * * Create a new surface applied the filter. This function will create * a context for itself, set up the coordinate systems execute all its * little primatives and then clean up its own mess. * * Returns: (transfer full): a new #cairo_surface_t **/ cairo_surface_t * rsvg_filter_render (RsvgNode *filter_node, cairo_surface_t *source, RsvgDrawingCtx *context, RsvgBbox *bounds, char *channelmap) { RsvgFilter *filter; RsvgFilterContext *ctx; guint i; cairo_surface_t *output; g_return_val_if_fail (source != NULL, NULL); g_return_val_if_fail (cairo_surface_get_type (source) == CAIRO_SURFACE_TYPE_IMAGE, NULL); g_assert (rsvg_node_get_type (filter_node) == RSVG_NODE_TYPE_FILTER); filter = rsvg_rust_cnode_get_impl (filter_node); ctx = g_new0 (RsvgFilterContext, 1); ctx->filter = filter; ctx->source_surface = source; ctx->bg_surface = NULL; ctx->results = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, rsvg_filter_free_pair); ctx->ctx = context; rsvg_filter_fix_coordinate_system (ctx, rsvg_current_state (context), bounds); ctx->lastresult.surface = cairo_surface_reference (source); ctx->lastresult.bounds = rsvg_filter_primitive_get_bounds (NULL, ctx); for (i = 0; i < 4; i++) ctx->channelmap[i] = channelmap[i] - '0'; rsvg_node_foreach_child (filter_node, render_child_if_filter_primitive, ctx); output = ctx->lastresult.surface; g_hash_table_destroy (ctx->results); rsvg_filter_context_free (ctx); return output; } /** * rsvg_filter_store_result: * @name: The name of the result * @result: The pointer to the result * @ctx: the context that this was called in * * Puts the new result into the hash for easy finding later, also * Stores it as the last result **/ static void rsvg_filter_store_output (GString * name, RsvgFilterPrimitiveOutput result, RsvgFilterContext * ctx) { RsvgFilterPrimitiveOutput *store; cairo_surface_destroy (ctx->lastresult.surface); store = g_new0 (RsvgFilterPrimitiveOutput, 1); *store = result; if (name->str[0] != '\0') { cairo_surface_reference (result.surface); /* increments the references for the table */ g_hash_table_insert (ctx->results, g_strdup (name->str), store); } cairo_surface_reference (result.surface); /* increments the references for the last result */ ctx->lastresult = result; } static void rsvg_filter_store_result (GString * name, cairo_surface_t *surface, RsvgFilterContext * ctx) { RsvgFilterPrimitiveOutput output; output.bounds.x0 = 0; output.bounds.y0 = 0; output.bounds.x1 = ctx->width; output.bounds.y1 = ctx->height; output.surface = surface; rsvg_filter_store_output (name, output, ctx); } static cairo_surface_t * surface_get_alpha (cairo_surface_t *source, RsvgFilterContext * ctx) { guchar *data; guchar *pbdata; gsize i, pbsize; cairo_surface_t *surface; if (source == NULL) return NULL; cairo_surface_flush (source); pbsize = cairo_image_surface_get_width (source) * cairo_image_surface_get_height (source); surface = _rsvg_image_surface_new (cairo_image_surface_get_width (source), cairo_image_surface_get_height (source)); if (surface == NULL) return NULL; data = cairo_image_surface_get_data (surface); pbdata = cairo_image_surface_get_data (source); /* FIXMEchpe: rewrite this into nested width, height loops */ for (i = 0; i < pbsize; i++) data[i * 4 + ctx->channelmap[3]] = pbdata[i * 4 + ctx->channelmap[3]]; cairo_surface_mark_dirty (surface); return surface; } static cairo_surface_t * rsvg_compile_bg (RsvgDrawingCtx * ctx) { RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render); cairo_surface_t *surface; cairo_t *cr; GList *i; surface = _rsvg_image_surface_new (render->width, render->height); if (surface == NULL) return NULL; cr = cairo_create (surface); for (i = g_list_last (render->cr_stack); i != NULL; i = g_list_previous (i)) { cairo_t *draw = i->data; gboolean nest = draw != render->initial_cr; cairo_set_source_surface (cr, cairo_get_target (draw), nest ? 0 : -render->offset_x, nest ? 0 : -render->offset_y); cairo_paint (cr); } cairo_destroy (cr); return surface; } /** * rsvg_filter_get_bg: * * Returns: (transfer none) (nullable): a #cairo_surface_t, or %NULL */ static cairo_surface_t * rsvg_filter_get_bg (RsvgFilterContext * ctx) { if (!ctx->bg_surface) ctx->bg_surface = rsvg_compile_bg (ctx->ctx); return ctx->bg_surface; } /* FIXMEchpe: proper return value and out param! */ /** * rsvg_filter_get_result: * @name: The name of the surface * @ctx: the context that this was called in * * Gets a surface for a primitive * * Returns: (nullable): a pointer to the result that the name refers to, a special * surface if the name is a special keyword or %NULL if nothing was found **/ static RsvgFilterPrimitiveOutput rsvg_filter_get_result (GString * name, RsvgFilterContext * ctx) { RsvgFilterPrimitiveOutput output; RsvgFilterPrimitiveOutput *outputpointer; output.bounds.x0 = output.bounds.x1 = output.bounds.y0 = output.bounds.y1 = 0; if (!strcmp (name->str, "SourceGraphic")) { output.surface = cairo_surface_reference (ctx->source_surface); return output; } else if (!strcmp (name->str, "BackgroundImage")) { output.surface = rsvg_filter_get_bg (ctx); if (output.surface) cairo_surface_reference (output.surface); return output; } else if (!strcmp (name->str, "") || !strcmp (name->str, "none")) { output = ctx->lastresult; cairo_surface_reference (output.surface); return output; } else if (!strcmp (name->str, "SourceAlpha")) { output.surface = surface_get_alpha (ctx->source_surface, ctx); return output; } else if (!strcmp (name->str, "BackgroundAlpha")) { output.surface = surface_get_alpha (rsvg_filter_get_bg (ctx), ctx); return output; } outputpointer = (RsvgFilterPrimitiveOutput *) (g_hash_table_lookup (ctx->results, name->str)); if (outputpointer != NULL) { output = *outputpointer; cairo_surface_reference (output.surface); return output; } /* g_warning (_("%s not found\n"), name->str); */ output = ctx->lastresult; cairo_surface_reference (output.surface); return output; } /** * rsvg_filter_get_in: * @name: * @ctx: * * Returns: (transfer full) (nullable): a new #cairo_surface_t, or %NULL */ static cairo_surface_t * rsvg_filter_get_in (GString * name, RsvgFilterContext * ctx) { return rsvg_filter_get_result (name, ctx).surface; } static void rsvg_filter_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilter *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "filterUnits"))) { if (!strcmp (value, "userSpaceOnUse")) filter->filterunits = userSpaceOnUse; else filter->filterunits = objectBoundingBox; } if ((value = rsvg_property_bag_lookup (atts, "primitiveUnits"))) { if (!strcmp (value, "objectBoundingBox")) filter->primitiveunits = objectBoundingBox; else filter->primitiveunits = userSpaceOnUse; } if ((value = rsvg_property_bag_lookup (atts, "x"))) filter->x = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); if ((value = rsvg_property_bag_lookup (atts, "y"))) filter->y = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); if ((value = rsvg_property_bag_lookup (atts, "width"))) filter->width = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); if ((value = rsvg_property_bag_lookup (atts, "height"))) filter->height = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); } static void rsvg_filter_draw (RsvgNode *node, gpointer impl, RsvgDrawingCtx *ctx, int dominate) { /* nothing; filters are drawn in rsvg-cairo-draw.c */ } static void rsvg_filter_free (gpointer impl) { RsvgFilter *filter = impl; g_free (filter); } /** * rsvg_new_filter: * * Creates a blank filter and assigns default values to everything **/ RsvgNode * rsvg_new_filter (const char *element_name, RsvgNode *parent) { RsvgFilter *filter; filter = g_new0 (RsvgFilter, 1); filter->filterunits = objectBoundingBox; filter->primitiveunits = userSpaceOnUse; filter->x = rsvg_length_parse ("-10%", LENGTH_DIR_HORIZONTAL); filter->y = rsvg_length_parse ("-10%", LENGTH_DIR_VERTICAL); filter->width = rsvg_length_parse ("120%", LENGTH_DIR_HORIZONTAL); filter->height = rsvg_length_parse ("120%", LENGTH_DIR_VERTICAL); return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER, parent, rsvg_state_new (), filter, rsvg_filter_set_atts, rsvg_filter_draw, rsvg_filter_free); } /*************************************************************/ /*************************************************************/ typedef enum { normal, multiply, screen, darken, lighten, softlight, hardlight, colordodge, colorburn, overlay, exclusion, difference } RsvgFilterPrimitiveBlendMode; typedef struct _RsvgFilterPrimitiveBlend RsvgFilterPrimitiveBlend; struct _RsvgFilterPrimitiveBlend { RsvgFilterPrimitive super; RsvgFilterPrimitiveBlendMode mode; GString *in2; }; static void rsvg_filter_blend (RsvgFilterPrimitiveBlendMode mode, cairo_surface_t *in, cairo_surface_t *in2, cairo_surface_t* output, RsvgIRect boundarys, int *channelmap) { guchar i; gint x, y; gint rowstride, rowstride2, rowstrideo, height, width; guchar *in_pixels; guchar *in2_pixels; guchar *output_pixels; cairo_surface_flush (in); cairo_surface_flush (in2); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); rowstride2 = cairo_image_surface_get_stride (in2); rowstrideo = cairo_image_surface_get_stride (output); output_pixels = cairo_image_surface_get_data (output); in_pixels = cairo_image_surface_get_data (in); in2_pixels = cairo_image_surface_get_data (in2); if (boundarys.x0 < 0) boundarys.x0 = 0; if (boundarys.y0 < 0) boundarys.y0 = 0; if (boundarys.x1 >= width) boundarys.x1 = width; if (boundarys.y1 >= height) boundarys.y1 = height; for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { double qr, cr, qa, qb, ca, cb, bca, bcb; int ch; qa = (double) in_pixels[4 * x + y * rowstride + channelmap[3]] / 255.0; qb = (double) in2_pixels[4 * x + y * rowstride2 + channelmap[3]] / 255.0; qr = 1 - (1 - qa) * (1 - qb); cr = 0; for (ch = 0; ch < 3; ch++) { i = channelmap[ch]; ca = (double) in_pixels[4 * x + y * rowstride + i] / 255.0; cb = (double) in2_pixels[4 * x + y * rowstride2 + i] / 255.0; /*these are the ca and cb that are used in the non-standard blend functions */ bcb = (1 - qa) * cb + ca; bca = (1 - qb) * ca + cb; switch (mode) { case normal: cr = (1 - qa) * cb + ca; break; case multiply: cr = (1 - qa) * cb + (1 - qb) * ca + ca * cb; break; case screen: cr = cb + ca - ca * cb; break; case darken: cr = MIN ((1 - qa) * cb + ca, (1 - qb) * ca + cb); break; case lighten: cr = MAX ((1 - qa) * cb + ca, (1 - qb) * ca + cb); break; case softlight: if (bcb < 0.5) cr = 2 * bca * bcb + bca * bca * (1 - 2 * bcb); else cr = sqrt (bca) * (2 * bcb - 1) + (2 * bca) * (1 - bcb); break; case hardlight: if (cb < 0.5) cr = 2 * bca * bcb; else cr = 1 - 2 * (1 - bca) * (1 - bcb); break; case colordodge: if (bcb == 1) cr = 1; else cr = MIN (bca / (1 - bcb), 1); break; case colorburn: if (bcb == 0) cr = 0; else cr = MAX (1 - (1 - bca) / bcb, 0); break; case overlay: if (bca < 0.5) cr = 2 * bca * bcb; else cr = 1 - 2 * (1 - bca) * (1 - bcb); break; case exclusion: cr = bca + bcb - 2 * bca * bcb; break; case difference: cr = abs (bca - bcb); break; } cr *= 255.0; if (cr > 255) cr = 255; if (cr < 0) cr = 0; output_pixels[4 * x + y * rowstrideo + i] = (guchar) cr; } output_pixels[4 * x + y * rowstrideo + channelmap[3]] = qr * 255.0; } cairo_surface_mark_dirty (output); } static void rsvg_filter_primitive_blend_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveBlend *blend = (RsvgFilterPrimitiveBlend *) primitive; RsvgIRect boundarys; cairo_surface_t *output, *in, *in2; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; in2 = rsvg_filter_get_in (blend->in2, ctx); if (in2 == NULL) { cairo_surface_destroy (in); return; } output = _rsvg_image_surface_new (cairo_image_surface_get_width (in), cairo_image_surface_get_height (in)); if (output == NULL) { cairo_surface_destroy (in); cairo_surface_destroy (in2); return; } rsvg_filter_blend (blend->mode, in, in2, output, boundarys, ctx->channelmap); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (in2); cairo_surface_destroy (output); } static void rsvg_filter_primitive_blend_free (gpointer impl) { RsvgFilterPrimitiveBlend *blend = impl; g_string_free (blend->in2, TRUE); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_blend_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveBlend *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "mode"))) { if (!strcmp (value, "multiply")) filter->mode = multiply; else if (!strcmp (value, "screen")) filter->mode = screen; else if (!strcmp (value, "darken")) filter->mode = darken; else if (!strcmp (value, "lighten")) filter->mode = lighten; else filter->mode = normal; } if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "in2"))) g_string_assign (filter->in2, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_blend (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveBlend *filter; filter = g_new0 (RsvgFilterPrimitiveBlend, 1); filter->mode = normal; filter->super.in = g_string_new ("none"); filter->in2 = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->super.render = rsvg_filter_primitive_blend_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_BLEND, parent, rsvg_state_new (), filter, rsvg_filter_primitive_blend_set_atts, rsvg_filter_draw, rsvg_filter_primitive_blend_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveConvolveMatrix RsvgFilterPrimitiveConvolveMatrix; typedef enum { EDGE_MODE_DUPLICATE, EDGE_MODE_WRAP, EDGE_MODE_NONE } EdgeMode; struct _RsvgFilterPrimitiveConvolveMatrix { RsvgFilterPrimitive super; double *KernelMatrix; double divisor; gint orderx, ordery; double dx, dy; double bias; gint targetx, targety; gboolean preservealpha; EdgeMode edgemode; }; static void rsvg_filter_primitive_convolve_matrix_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveConvolveMatrix *convolve = (RsvgFilterPrimitiveConvolveMatrix *) primitive; guchar ch; gint x, y; gint i, j; gint rowstride, height, width; RsvgIRect boundarys; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; gint sx, sy, kx, ky; guchar sval; double kval, sum, dx, dy, targetx, targety; int umch; gint tempresult; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); targetx = convolve->targetx * ctx->paffine.xx; targety = convolve->targety * ctx->paffine.yy; if (convolve->dx != 0 || convolve->dy != 0) { dx = convolve->dx * ctx->paffine.xx; dy = convolve->dy * ctx->paffine.yy; } else dx = dy = 1; rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); for (y = boundarys.y0; y < boundarys.y1; y++) { for (x = boundarys.x0; x < boundarys.x1; x++) { for (umch = 0; umch < 3 + !convolve->preservealpha; umch++) { ch = ctx->channelmap[umch]; sum = 0; for (i = 0; i < convolve->ordery; i++) { for (j = 0; j < convolve->orderx; j++) { int alpha; sx = x - targetx + j * dx; sy = y - targety + i * dy; if (convolve->edgemode == EDGE_MODE_DUPLICATE) { if (sx < boundarys.x0) sx = boundarys.x0; if (sx >= boundarys.x1) sx = boundarys.x1 - 1; if (sy < boundarys.y0) sy = boundarys.y0; if (sy >= boundarys.y1) sy = boundarys.y1 - 1; } else if (convolve->edgemode == EDGE_MODE_WRAP) { if (sx < boundarys.x0 || (sx >= boundarys.x1)) sx = boundarys.x0 + (sx - boundarys.x0) % (boundarys.x1 - boundarys.x0); if (sy < boundarys.y0 || (sy >= boundarys.y1)) sy = boundarys.y0 + (sy - boundarys.y0) % (boundarys.y1 - boundarys.y0); } else if (convolve->edgemode == EDGE_MODE_NONE) { if (sx < boundarys.x0 || (sx >= boundarys.x1) || sy < boundarys.y0 || (sy >= boundarys.y1)) continue; } else { g_assert_not_reached (); } kx = convolve->orderx - j - 1; ky = convolve->ordery - i - 1; alpha = in_pixels[4 * sx + sy * rowstride + 3]; if (ch == 3) sval = alpha; else if (alpha) sval = in_pixels[4 * sx + sy * rowstride + ch] * 255 / alpha; else sval = 0; kval = convolve->KernelMatrix[kx + ky * convolve->orderx]; sum += (double) sval *kval; } } tempresult = sum / convolve->divisor + convolve->bias; if (tempresult > 255) tempresult = 255; if (tempresult < 0) tempresult = 0; output_pixels[4 * x + y * rowstride + ch] = tempresult; } if (convolve->preservealpha) output_pixels[4 * x + y * rowstride + ctx->channelmap[3]] = in_pixels[4 * x + y * rowstride + ctx->channelmap[3]]; for (umch = 0; umch < 3; umch++) { ch = ctx->channelmap[umch]; output_pixels[4 * x + y * rowstride + ch] = output_pixels[4 * x + y * rowstride + ch] * output_pixels[4 * x + y * rowstride + ctx->channelmap[3]] / 255; } } } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_convolve_matrix_free (gpointer impl) { RsvgFilterPrimitiveConvolveMatrix *convolve = impl; g_free (convolve->KernelMatrix); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_convolve_matrix_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveConvolveMatrix *filter = impl; gint i, j; const char *value; gboolean has_target_x, has_target_y; has_target_x = 0; has_target_y = 0; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "targetX"))) { has_target_x = 1; filter->targetx = atoi (value); } if ((value = rsvg_property_bag_lookup (atts, "targetY"))) { has_target_y = 1; filter->targety = atoi (value); } if ((value = rsvg_property_bag_lookup (atts, "bias"))) filter->bias = atof (value); if ((value = rsvg_property_bag_lookup (atts, "preserveAlpha"))) { if (!strcmp (value, "true")) filter->preservealpha = TRUE; else filter->preservealpha = FALSE; } if ((value = rsvg_property_bag_lookup (atts, "divisor"))) filter->divisor = atof (value); if ((value = rsvg_property_bag_lookup (atts, "order"))) { double tempx, tempy; if (rsvg_css_parse_number_optional_number (value, &tempx, &tempy) && tempx >= 1.0 && tempy <= 100.0 && tempy >= 1.0 && tempy <= 100.0) { filter->orderx = (int) tempx; filter->ordery = (int) tempy; g_assert (filter->orderx >= 1); g_assert (filter->ordery >= 1); #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b))) if (SIZE_OVERFLOWS (filter->orderx, filter->ordery)) { rsvg_node_set_attribute_parse_error (node, "order", "number of kernelMatrix elements would be too big"); return; } } else { rsvg_node_set_attribute_parse_error (node, "order", "invalid size for convolve matrix"); return; } } if ((value = rsvg_property_bag_lookup (atts, "kernelUnitLength"))) { if (!rsvg_css_parse_number_optional_number (value, &filter->dx, &filter->dy)) { rsvg_node_set_attribute_parse_error (node, "kernelUnitLength", "expected number-optional-number"); return; } } if ((value = rsvg_property_bag_lookup (atts, "kernelMatrix"))) { gsize num_elems; gsize got_num_elems; num_elems = filter->orderx * filter->ordery; if (!rsvg_css_parse_number_list (value, NUMBER_LIST_LENGTH_EXACT, num_elems, &filter->KernelMatrix, &got_num_elems)) { rsvg_node_set_attribute_parse_error (node, "kernelMatrix", "expected a matrix of numbers"); return; } g_assert (num_elems == got_num_elems); } if ((value = rsvg_property_bag_lookup (atts, "edgeMode"))) { if (!strcmp (value, "duplicate")) { filter->edgemode = EDGE_MODE_DUPLICATE; } else if (!strcmp (value, "wrap")) { filter->edgemode = EDGE_MODE_WRAP; } else if (!strcmp (value, "none")) { filter->edgemode = EDGE_MODE_NONE; } else { rsvg_node_set_attribute_parse_error (node, "edgeMode", "expected 'duplicate' | 'wrap' | 'none'"); return; } } if (filter->divisor == 0) { for (j = 0; j < filter->orderx; j++) for (i = 0; i < filter->ordery; i++) filter->divisor += filter->KernelMatrix[j + i * filter->orderx]; } if (filter->divisor == 0) filter->divisor = 1; if (!has_target_x) { filter->targetx = floor (filter->orderx / 2); } if (!has_target_y) { filter->targety = floor (filter->ordery / 2); } } RsvgNode * rsvg_new_filter_primitive_convolve_matrix (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveConvolveMatrix *filter; filter = g_new0 (RsvgFilterPrimitiveConvolveMatrix, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->KernelMatrix = NULL; filter->divisor = 0; filter->bias = 0; filter->dx = 0; filter->dy = 0; filter->preservealpha = FALSE; filter->edgemode = EDGE_MODE_DUPLICATE; filter->super.render = rsvg_filter_primitive_convolve_matrix_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_CONVOLVE_MATRIX, parent, rsvg_state_new (), filter, rsvg_filter_primitive_convolve_matrix_set_atts, rsvg_filter_draw, rsvg_filter_primitive_convolve_matrix_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveGaussianBlur RsvgFilterPrimitiveGaussianBlur; struct _RsvgFilterPrimitiveGaussianBlur { RsvgFilterPrimitive super; double sdx, sdy; }; static void box_blur_line (gint box_width, gint even_offset, guchar *src, guchar *dest, gint len, gint bpp) { gint i; gint lead; /* This marks the leading edge of the kernel */ gint output; /* This marks the center of the kernel */ gint trail; /* This marks the pixel BEHIND the last 1 in the kernel; it's the pixel to remove from the accumulator. */ gint *ac; /* Accumulator for each channel */ g_assert (box_width > 0); ac = g_new0 (gint, bpp); /* The algorithm differs for even and odd-sized kernels. * With the output at the center, * If odd, the kernel might look like this: 0011100 * If even, the kernel will either be centered on the boundary between * the output and its left neighbor, or on the boundary between the * output and its right neighbor, depending on even_lr. * So it might be 0111100 or 0011110, where output is on the center * of these arrays. */ lead = 0; if (box_width % 2 != 0) { /* Odd-width kernel */ output = lead - (box_width - 1) / 2; trail = lead - box_width; } else { /* Even-width kernel. */ if (even_offset == 1) { /* Right offset */ output = lead + 1 - box_width / 2; trail = lead - box_width; } else if (even_offset == -1) { /* Left offset */ output = lead - box_width / 2; trail = lead - box_width; } else { /* If even_offset isn't 1 or -1, there's some error. */ g_assert_not_reached (); } } /* Initialize accumulator */ for (i = 0; i < bpp; i++) ac[i] = 0; /* As the kernel moves across the image, it has a leading edge and a * trailing edge, and the output is in the middle. */ while (output < len) { /* The number of pixels that are both in the image and * currently covered by the kernel. This is necessary to * handle edge cases. */ guint coverage = (lead < len ? lead : len - 1) - (trail >= 0 ? trail : -1); #ifdef READABLE_BOXBLUR_CODE /* The code here does the same as the code below, but the code below * has been optimized by moving the if statements out of the tight for * loop, and is harder to understand. * Don't use both this code and the code below. */ for (i = 0; i < bpp; i++) { /* If the leading edge of the kernel is still on the image, * add the value there to the accumulator. */ if (lead < len) ac[i] += src[bpp * lead + i]; /* If the trailing edge of the kernel is on the image, * subtract the value there from the accumulator. */ if (trail >= 0) ac[i] -= src[bpp * trail + i]; /* Take the averaged value in the accumulator and store * that value in the output. The number of pixels currently * stored in the accumulator can be less than the nominal * width of the kernel because the kernel can go "over the edge" * of the image. */ if (output >= 0) dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } #endif /* If the leading edge of the kernel is still on the image... */ if (lead < len) { if (trail >= 0) { /* If the trailing edge of the kernel is on the image. (Since * the output is in between the lead and trail, it must be on * the image. */ for (i = 0; i < bpp; i++) { ac[i] += src[bpp * lead + i]; ac[i] -= src[bpp * trail + i]; dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } } else if (output >= 0) { /* If the output is on the image, but the trailing edge isn't yet * on the image. */ for (i = 0; i < bpp; i++) { ac[i] += src[bpp * lead + i]; dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } } else { /* If leading edge is on the image, but the output and trailing * edge aren't yet on the image. */ for (i = 0; i < bpp; i++) ac[i] += src[bpp * lead + i]; } } else if (trail >= 0) { /* If the leading edge has gone off the image, but the output and * trailing edge are on the image. (The big loop exits when the * output goes off the image. */ for (i = 0; i < bpp; i++) { ac[i] -= src[bpp * trail + i]; dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } } else if (output >= 0) { /* Leading has gone off the image and trailing isn't yet in it * (small image) */ for (i = 0; i < bpp; i++) dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } lead++; output++; trail++; } g_free (ac); } static gint compute_box_blur_width (double radius) { double width; width = radius * 3 * sqrt (2 * G_PI) / 4; return (gint) (width + 0.5); } #define SQR(x) ((x) * (x)) static void make_gaussian_convolution_matrix (gdouble radius, gdouble **out_matrix, gint *out_matrix_len) { gdouble *matrix; gdouble std_dev; gdouble sum; gint matrix_len; gint i, j; std_dev = radius + 1.0; radius = std_dev * 2; matrix_len = 2 * ceil (radius - 0.5) + 1; if (matrix_len <= 0) matrix_len = 1; matrix = g_new0 (gdouble, matrix_len); /* Fill the matrix by doing numerical integration approximation * from -2*std_dev to 2*std_dev, sampling 50 points per pixel. * We do the bottom half, mirror it to the top half, then compute the * center point. Otherwise asymmetric quantization errors will occur. * The formula to integrate is e^-(x^2/2s^2). */ for (i = matrix_len / 2 + 1; i < matrix_len; i++) { gdouble base_x = i - (matrix_len / 2) - 0.5; sum = 0; for (j = 1; j <= 50; j++) { gdouble r = base_x + 0.02 * j; if (r <= radius) sum += exp (- SQR (r) / (2 * SQR (std_dev))); } matrix[i] = sum / 50; } /* mirror to the bottom half */ for (i = 0; i <= matrix_len / 2; i++) matrix[i] = matrix[matrix_len - 1 - i]; /* find center val -- calculate an odd number of quanta to make it * symmetric, even if the center point is weighted slightly higher * than others. */ sum = 0; for (j = 0; j <= 50; j++) sum += exp (- SQR (- 0.5 + 0.02 * j) / (2 * SQR (std_dev))); matrix[matrix_len / 2] = sum / 51; /* normalize the distribution by scaling the total sum to one */ sum = 0; for (i = 0; i < matrix_len; i++) sum += matrix[i]; for (i = 0; i < matrix_len; i++) matrix[i] = matrix[i] / sum; *out_matrix = matrix; *out_matrix_len = matrix_len; } static void gaussian_blur_line (gdouble *matrix, gint matrix_len, guchar *src, guchar *dest, gint len, gint bpp) { guchar *src_p; guchar *src_p1; gint matrix_middle; gint row; gint i, j; matrix_middle = matrix_len / 2; /* picture smaller than the matrix? */ if (matrix_len > len) { for (row = 0; row < len; row++) { /* find the scale factor */ gdouble scale = 0; for (j = 0; j < len; j++) { /* if the index is in bounds, add it to the scale counter */ if (j + matrix_middle - row >= 0 && j + matrix_middle - row < matrix_len) scale += matrix[j]; } src_p = src; for (i = 0; i < bpp; i++) { gdouble sum = 0; src_p1 = src_p++; for (j = 0; j < len; j++) { if (j + matrix_middle - row >= 0 && j + matrix_middle - row < matrix_len) sum += *src_p1 * matrix[j]; src_p1 += bpp; } *dest++ = (guchar) (sum / scale + 0.5); } } } else { /* left edge */ for (row = 0; row < matrix_middle; row++) { /* find scale factor */ gdouble scale = 0; for (j = matrix_middle - row; j < matrix_len; j++) scale += matrix[j]; src_p = src; for (i = 0; i < bpp; i++) { gdouble sum = 0; src_p1 = src_p++; for (j = matrix_middle - row; j < matrix_len; j++) { sum += *src_p1 * matrix[j]; src_p1 += bpp; } *dest++ = (guchar) (sum / scale + 0.5); } } /* go through each pixel in each col */ for (; row < len - matrix_middle; row++) { src_p = src + (row - matrix_middle) * bpp; for (i = 0; i < bpp; i++) { gdouble sum = 0; src_p1 = src_p++; for (j = 0; j < matrix_len; j++) { sum += matrix[j] * *src_p1; src_p1 += bpp; } *dest++ = (guchar) (sum + 0.5); } } /* for the edge condition, we only use available info and scale to one */ for (; row < len; row++) { /* find scale factor */ gdouble scale = 0; for (j = 0; j < len - row + matrix_middle; j++) scale += matrix[j]; src_p = src + (row - matrix_middle) * bpp; for (i = 0; i < bpp; i++) { gdouble sum = 0; src_p1 = src_p++; for (j = 0; j < len - row + matrix_middle; j++) { sum += *src_p1 * matrix[j]; src_p1 += bpp; } *dest++ = (guchar) (sum / scale + 0.5); } } } } static void get_column (guchar *column_data, guchar *src_data, gint src_stride, gint bpp, gint height, gint x) { gint y; gint c; for (y = 0; y < height; y++) { guchar *src = src_data + y * src_stride + x * bpp; for (c = 0; c < bpp; c++) column_data[c] = src[c]; column_data += bpp; } } static void put_column (guchar *column_data, guchar *dest_data, gint dest_stride, gint bpp, gint height, gint x) { gint y; gint c; for (y = 0; y < height; y++) { guchar *dst = dest_data + y * dest_stride + x * bpp; for (c = 0; c < bpp; c++) dst[c] = column_data[c]; column_data += bpp; } } static void gaussian_blur_surface (cairo_surface_t *in, cairo_surface_t *out, gdouble sx, gdouble sy) { gint width, height; cairo_format_t in_format, out_format; gint in_stride; gint out_stride; guchar *in_data, *out_data; gint bpp; gboolean out_has_data; cairo_surface_flush (in); width = cairo_image_surface_get_width (in); height = cairo_image_surface_get_height (in); g_assert (width == cairo_image_surface_get_width (out) && height == cairo_image_surface_get_height (out)); in_format = cairo_image_surface_get_format (in); out_format = cairo_image_surface_get_format (out); g_assert (in_format == out_format); g_assert (in_format == CAIRO_FORMAT_ARGB32 || in_format == CAIRO_FORMAT_A8); if (in_format == CAIRO_FORMAT_ARGB32) bpp = 4; else if (in_format == CAIRO_FORMAT_A8) bpp = 1; else { g_assert_not_reached (); return; } in_stride = cairo_image_surface_get_stride (in); out_stride = cairo_image_surface_get_stride (out); in_data = cairo_image_surface_get_data (in); out_data = cairo_image_surface_get_data (out); if (sx < 0.0) sx = 0.0; if (sy < 0.0) sy = 0.0; /* Bail out by just copying? */ if ((sx == 0.0 && sy == 0.0) || sx > 1000 || sy > 1000) { cairo_t *cr; cr = cairo_create (out); cairo_set_source_surface (cr, in, 0, 0); cairo_paint (cr); cairo_destroy (cr); return; } if (sx != 0.0) { gint box_width; gdouble *gaussian_matrix; gint gaussian_matrix_len; int y; guchar *row_buffer = NULL; guchar *row1, *row2; gboolean use_box_blur; /* For small radiuses, use a true gaussian kernel; otherwise use three box blurs with * clever offsets. */ if (sx < 10.0) use_box_blur = FALSE; else use_box_blur = TRUE; if (use_box_blur) { box_width = compute_box_blur_width (sx); /* twice the size so we can have "two" scratch rows */ row_buffer = g_new0 (guchar, width * bpp * 2); row1 = row_buffer; row2 = row_buffer + width * bpp; } else make_gaussian_convolution_matrix (sx, &gaussian_matrix, &gaussian_matrix_len); for (y = 0; y < height; y++) { guchar *in_row, *out_row; in_row = in_data + in_stride * y; out_row = out_data + out_stride * y; if (use_box_blur) { if (box_width % 2 != 0) { /* Odd-width box blur: repeat 3 times, centered on output pixel */ box_blur_line (box_width, 0, in_row, row1, width, bpp); box_blur_line (box_width, 0, row1, row2, width, bpp); box_blur_line (box_width, 0, row2, out_row, width, bpp); } else { /* Even-width box blur: * This method is suggested by the specification for SVG. * One pass with width n, centered between output and right pixel * One pass with width n, centered between output and left pixel * One pass with width n+1, centered on output pixel */ box_blur_line (box_width, -1, in_row, row1, width, bpp); box_blur_line (box_width, 1, row1, row2, width, bpp); box_blur_line (box_width + 1, 0, row2, out_row, width, bpp); } } else gaussian_blur_line (gaussian_matrix, gaussian_matrix_len, in_row, out_row, width, bpp); } if (!use_box_blur) g_free (gaussian_matrix); g_free (row_buffer); out_has_data = TRUE; } else out_has_data = FALSE; if (sy != 0.0) { gint box_height; gdouble *gaussian_matrix = NULL; gint gaussian_matrix_len; guchar *col_buffer; guchar *col1, *col2; int x; gboolean use_box_blur; /* For small radiuses, use a true gaussian kernel; otherwise use three box blurs with * clever offsets. */ if (sy < 10.0) use_box_blur = FALSE; else use_box_blur = TRUE; /* twice the size so we can have the source pixels and the blurred pixels */ col_buffer = g_new0 (guchar, height * bpp * 2); col1 = col_buffer; col2 = col_buffer + height * bpp; if (use_box_blur) { box_height = compute_box_blur_width (sy); } else make_gaussian_convolution_matrix (sy, &gaussian_matrix, &gaussian_matrix_len); for (x = 0; x < width; x++) { if (out_has_data) get_column (col1, out_data, out_stride, bpp, height, x); else get_column (col1, in_data, in_stride, bpp, height, x); if (use_box_blur) { if (box_height % 2 != 0) { /* Odd-width box blur */ box_blur_line (box_height, 0, col1, col2, height, bpp); box_blur_line (box_height, 0, col2, col1, height, bpp); box_blur_line (box_height, 0, col1, col2, height, bpp); } else { /* Even-width box blur */ box_blur_line (box_height, -1, col1, col2, height, bpp); box_blur_line (box_height, 1, col2, col1, height, bpp); box_blur_line (box_height + 1, 0, col1, col2, height, bpp); } } else gaussian_blur_line (gaussian_matrix, gaussian_matrix_len, col1, col2, height, bpp); put_column (col2, out_data, out_stride, bpp, height, x); } g_free (gaussian_matrix); g_free (col_buffer); } cairo_surface_mark_dirty (out); } static void rsvg_filter_primitive_gaussian_blur_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveGaussianBlur *gaussian = (RsvgFilterPrimitiveGaussianBlur *) primitive; int width, height; cairo_surface_t *output, *in; RsvgIRect boundarys; gdouble sdx, sdy; RsvgFilterPrimitiveOutput op; cairo_t *cr; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); op = rsvg_filter_get_result (primitive->in, ctx); in = op.surface; width = cairo_image_surface_get_width (in); height = cairo_image_surface_get_height (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } /* scale the SD values */ sdx = fabs (gaussian->sdx * ctx->paffine.xx); sdy = fabs (gaussian->sdy * ctx->paffine.yy); gaussian_blur_surface (in, output, sdx, sdy); /* Hard-clip to the filter area */ if (!(boundarys.x0 == 0 && boundarys.y0 == 0 && boundarys.x1 == width && boundarys.y1 == height)) { cr = cairo_create (output); cairo_set_operator (cr, CAIRO_OPERATOR_CLEAR); cairo_set_fill_rule (cr, CAIRO_FILL_RULE_EVEN_ODD); cairo_rectangle (cr, 0, 0, width, height); cairo_rectangle (cr, boundarys.x0, boundarys.y0, boundarys.x1 - boundarys.x0, boundarys.y1 - boundarys.y0); cairo_fill (cr); cairo_destroy (cr); } op.surface = output; op.bounds = boundarys; rsvg_filter_store_output (primitive->result, op, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_gaussian_blur_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveGaussianBlur *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "stdDeviation"))) { if (!rsvg_css_parse_number_optional_number (value, &filter->sdx, &filter->sdy)) { rsvg_node_set_attribute_parse_error (node, "stdDeviation", "expected number-optional-number"); return; } } } RsvgNode * rsvg_new_filter_primitive_gaussian_blur (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveGaussianBlur *filter; filter = g_new0 (RsvgFilterPrimitiveGaussianBlur, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->sdx = 0; filter->sdy = 0; filter->super.render = rsvg_filter_primitive_gaussian_blur_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_GAUSSIAN_BLUR, parent, rsvg_state_new (), filter, rsvg_filter_primitive_gaussian_blur_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveOffset RsvgFilterPrimitiveOffset; struct _RsvgFilterPrimitiveOffset { RsvgFilterPrimitive super; RsvgLength dx, dy; }; static void rsvg_filter_primitive_offset_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveOffset *offset = (RsvgFilterPrimitiveOffset *) primitive; guchar ch; gint x, y; gint rowstride, height, width; RsvgIRect boundarys; guchar *in_pixels; guchar *output_pixels; RsvgFilterPrimitiveOutput out; cairo_surface_t *output, *in; double dx, dy; int ox, oy; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); dx = rsvg_length_normalize (&offset->dx, ctx->ctx); dy = rsvg_length_normalize (&offset->dy, ctx->ctx); ox = ctx->paffine.xx * dx + ctx->paffine.xy * dy; oy = ctx->paffine.yx * dx + ctx->paffine.yy * dy; for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { if (x - ox < boundarys.x0 || x - ox >= boundarys.x1) continue; if (y - oy < boundarys.y0 || y - oy >= boundarys.y1) continue; for (ch = 0; ch < 4; ch++) { output_pixels[y * rowstride + x * 4 + ch] = in_pixels[(y - oy) * rowstride + (x - ox) * 4 + ch]; } } cairo_surface_mark_dirty (output); out.surface = output; out.bounds = boundarys; rsvg_filter_store_output (primitive->result, out, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_offset_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag * atts) { RsvgFilterPrimitiveOffset *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "dx"))) filter->dx = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); if ((value = rsvg_property_bag_lookup (atts, "dy"))) filter->dy = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); } RsvgNode * rsvg_new_filter_primitive_offset (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveOffset *filter; filter = g_new0 (RsvgFilterPrimitiveOffset, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->dx = rsvg_length_parse ("0", LENGTH_DIR_HORIZONTAL); filter->dy = rsvg_length_parse ("0", LENGTH_DIR_VERTICAL); filter->super.render = rsvg_filter_primitive_offset_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_OFFSET, parent, rsvg_state_new (), filter, rsvg_filter_primitive_offset_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveMerge RsvgFilterPrimitiveMerge; struct _RsvgFilterPrimitiveMerge { RsvgFilterPrimitive super; }; struct merge_render_closure { cairo_surface_t *output; RsvgIRect boundarys; RsvgFilterContext *ctx; }; static gboolean merge_render_child (RsvgNode *node, gpointer data) { struct merge_render_closure *closure = data; RsvgFilterPrimitive *fp; cairo_surface_t *in; if (rsvg_node_get_type (node) != RSVG_NODE_TYPE_FILTER_PRIMITIVE_MERGE_NODE) return TRUE; fp = rsvg_rust_cnode_get_impl (node); in = rsvg_filter_get_in (fp->in, closure->ctx); if (in == NULL) return TRUE; rsvg_alpha_blt (in, closure->boundarys.x0, closure->boundarys.y0, closure->boundarys.x1 - closure->boundarys.x0, closure->boundarys.y1 - closure->boundarys.y0, closure->output, closure->boundarys.x0, closure->boundarys.y0); cairo_surface_destroy (in); return TRUE; } static void rsvg_filter_primitive_merge_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { struct merge_render_closure closure; closure.boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); closure.output = _rsvg_image_surface_new (ctx->width, ctx->height); if (closure.output == NULL) { return; } closure.ctx = ctx; rsvg_node_foreach_child (node, merge_render_child, &closure); rsvg_filter_store_result (primitive->result, closure.output, ctx); cairo_surface_destroy (closure.output); } static void rsvg_filter_primitive_merge_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveMerge *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_merge (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveMerge *filter; filter = g_new0 (RsvgFilterPrimitiveMerge, 1); filter->super.result = g_string_new ("none"); filter->super.render = rsvg_filter_primitive_merge_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_MERGE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_merge_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } static void rsvg_filter_primitive_merge_node_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitive *primitive = impl; const char *value; /* see bug 145149 - sodipodi generates bad SVG... */ if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (primitive->in, value); } static void rsvg_filter_primitive_merge_node_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { /* todo */ } RsvgNode * rsvg_new_filter_primitive_merge_node (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitive *filter; filter = g_new0 (RsvgFilterPrimitive, 1); filter->in = g_string_new ("none"); filter->render = rsvg_filter_primitive_merge_node_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_MERGE_NODE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_merge_node_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveColorMatrix RsvgFilterPrimitiveColorMatrix; struct _RsvgFilterPrimitiveColorMatrix { RsvgFilterPrimitive super; gint *KernelMatrix; }; static void rsvg_filter_primitive_color_matrix_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveColorMatrix *color_matrix = (RsvgFilterPrimitiveColorMatrix *) primitive; guchar ch; gint x, y; gint i; gint rowstride, height, width; RsvgIRect boundarys; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; int sum; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { int umch; int alpha = in_pixels[4 * x + y * rowstride + ctx->channelmap[3]]; if (!alpha) for (umch = 0; umch < 4; umch++) { sum = color_matrix->KernelMatrix[umch * 5 + 4]; if (sum > 255) sum = 255; if (sum < 0) sum = 0; output_pixels[4 * x + y * rowstride + ctx->channelmap[umch]] = sum; } else for (umch = 0; umch < 4; umch++) { int umi; ch = ctx->channelmap[umch]; sum = 0; for (umi = 0; umi < 4; umi++) { i = ctx->channelmap[umi]; if (umi != 3) sum += color_matrix->KernelMatrix[umch * 5 + umi] * in_pixels[4 * x + y * rowstride + i] / alpha; else sum += color_matrix->KernelMatrix[umch * 5 + umi] * in_pixels[4 * x + y * rowstride + i] / 255; } sum += color_matrix->KernelMatrix[umch * 5 + 4]; if (sum > 255) sum = 255; if (sum < 0) sum = 0; output_pixels[4 * x + y * rowstride + ch] = sum; } for (umch = 0; umch < 3; umch++) { ch = ctx->channelmap[umch]; output_pixels[4 * x + y * rowstride + ch] = output_pixels[4 * x + y * rowstride + ch] * output_pixels[4 * x + y * rowstride + ctx->channelmap[3]] / 255; } } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_color_matrix_free (gpointer impl) { RsvgFilterPrimitiveColorMatrix *matrix = impl; g_free (matrix->KernelMatrix); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_color_matrix_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveColorMatrix *filter = impl; gint type; gsize listlen = 0; const char *value; type = 0; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "values"))) { unsigned int i; double *temp; if (!rsvg_css_parse_number_list (value, NUMBER_LIST_LENGTH_MAXIMUM, 20, &temp, &listlen)) { rsvg_node_set_attribute_parse_error (node, "values", "invalid number list"); return; } filter->KernelMatrix = g_new0 (int, listlen); for (i = 0; i < listlen; i++) filter->KernelMatrix[i] = temp[i] * 255.; g_free (temp); } if ((value = rsvg_property_bag_lookup (atts, "type"))) { if (!strcmp (value, "matrix")) type = 0; else if (!strcmp (value, "saturate")) type = 1; else if (!strcmp (value, "hueRotate")) type = 2; else if (!strcmp (value, "luminanceToAlpha")) type = 3; else type = 0; } if (type == 0) { if (listlen != 20) { if (filter->KernelMatrix != NULL) g_free (filter->KernelMatrix); filter->KernelMatrix = g_new0 (int, 20); } } else if (type == 1) { float s; if (listlen != 0) { s = filter->KernelMatrix[0]; g_free (filter->KernelMatrix); } else s = 255; filter->KernelMatrix = g_new0 (int, 20); filter->KernelMatrix[0] = 0.213 * 255. + 0.787 * s; filter->KernelMatrix[1] = 0.715 * 255. - 0.715 * s; filter->KernelMatrix[2] = 0.072 * 255. - 0.072 * s; filter->KernelMatrix[5] = 0.213 * 255. - 0.213 * s; filter->KernelMatrix[6] = 0.715 * 255. + 0.285 * s; filter->KernelMatrix[7] = 0.072 * 255. - 0.072 * s; filter->KernelMatrix[10] = 0.213 * 255. - 0.213 * s; filter->KernelMatrix[11] = 0.715 * 255. - 0.715 * s; filter->KernelMatrix[12] = 0.072 * 255. + 0.928 * s; filter->KernelMatrix[18] = 255; } else if (type == 2) { double cosval, sinval, arg; if (listlen != 0) { arg = (double) filter->KernelMatrix[0] / 255.; g_free (filter->KernelMatrix); } else arg = 0; cosval = cos (arg); sinval = sin (arg); filter->KernelMatrix = g_new0 (int, 20); filter->KernelMatrix[0] = (0.213 + cosval * 0.787 + sinval * -0.213) * 255.; filter->KernelMatrix[1] = (0.715 + cosval * -0.715 + sinval * -0.715) * 255.; filter->KernelMatrix[2] = (0.072 + cosval * -0.072 + sinval * 0.928) * 255.; filter->KernelMatrix[5] = (0.213 + cosval * -0.213 + sinval * 0.143) * 255.; filter->KernelMatrix[6] = (0.715 + cosval * 0.285 + sinval * 0.140) * 255.; filter->KernelMatrix[7] = (0.072 + cosval * -0.072 + sinval * -0.283) * 255.; filter->KernelMatrix[10] = (0.213 + cosval * -0.213 + sinval * -0.787) * 255.; filter->KernelMatrix[11] = (0.715 + cosval * -0.715 + sinval * 0.715) * 255.; filter->KernelMatrix[12] = (0.072 + cosval * 0.928 + sinval * 0.072) * 255.; filter->KernelMatrix[18] = 255; } else if (type == 3) { if (filter->KernelMatrix != NULL) g_free (filter->KernelMatrix); filter->KernelMatrix = g_new0 (int, 20); filter->KernelMatrix[15] = 0.2125 * 255.; filter->KernelMatrix[16] = 0.7154 * 255.; filter->KernelMatrix[17] = 0.0721 * 255.; } else { g_assert_not_reached (); } } RsvgNode * rsvg_new_filter_primitive_color_matrix (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveColorMatrix *filter; filter = g_new0 (RsvgFilterPrimitiveColorMatrix, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->KernelMatrix = NULL; filter->super.render = rsvg_filter_primitive_color_matrix_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_COLOR_MATRIX, parent, rsvg_state_new (), filter, rsvg_filter_primitive_color_matrix_set_atts, rsvg_filter_draw, rsvg_filter_primitive_color_matrix_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgNodeComponentTransferFunc RsvgNodeComponentTransferFunc; typedef gint (*ComponentTransferFunc) (gint C, RsvgNodeComponentTransferFunc * user_data); typedef struct _RsvgFilterPrimitiveComponentTransfer RsvgFilterPrimitiveComponentTransfer; struct _RsvgNodeComponentTransferFunc { ComponentTransferFunc function; gint *tableValues; gsize nbTableValues; gint slope; gint intercept; gint amplitude; gint offset; gdouble exponent; char channel; }; struct _RsvgFilterPrimitiveComponentTransfer { RsvgFilterPrimitive super; }; static gint identity_component_transfer_func (gint C, RsvgNodeComponentTransferFunc * user_data) { return C; } static gint table_component_transfer_func (gint C, RsvgNodeComponentTransferFunc * user_data) { guint k; gint vk, vk1, distancefromlast; guint num_values; if (!user_data->nbTableValues) return C; num_values = user_data->nbTableValues; k = (C * (num_values - 1)) / 255; vk = user_data->tableValues[MIN (k, num_values - 1)]; vk1 = user_data->tableValues[MIN (k + 1, num_values - 1)]; distancefromlast = (C * (user_data->nbTableValues - 1)) - k * 255; return vk + distancefromlast * (vk1 - vk) / 255; } static gint discrete_component_transfer_func (gint C, RsvgNodeComponentTransferFunc * user_data) { gint k; if (!user_data->nbTableValues) return C; k = (C * user_data->nbTableValues) / 255; return user_data->tableValues[CLAMP (k, 0, user_data->nbTableValues - 1)]; } static gint linear_component_transfer_func (gint C, RsvgNodeComponentTransferFunc * user_data) { return (user_data->slope * C) / 255 + user_data->intercept; } static gint fixpow (gint base, gint exp) { int out = 255; for (; exp > 0; exp--) out = out * base / 255; return out; } static gint gamma_component_transfer_func (gint C, RsvgNodeComponentTransferFunc * user_data) { if (floor (user_data->exponent) == user_data->exponent) return user_data->amplitude * fixpow (C, user_data->exponent) / 255 + user_data->offset; else return (double) user_data->amplitude * pow ((double) C / 255., user_data->exponent) + user_data->offset; } struct component_transfer_closure { int channel_num; char channel; gboolean set_func; RsvgNodeComponentTransferFunc *channels[4]; ComponentTransferFunc functions[4]; RsvgFilterContext *ctx; }; static gboolean component_transfer_render_child (RsvgNode *node, gpointer data) { struct component_transfer_closure *closure = data; RsvgNodeComponentTransferFunc *f; if (rsvg_node_get_type (node) != RSVG_NODE_TYPE_COMPONENT_TRANFER_FUNCTION) return TRUE; f = rsvg_rust_cnode_get_impl (node); if (f->channel == closure->channel) { closure->functions[closure->ctx->channelmap[closure->channel_num]] = f->function; closure->channels[closure->ctx->channelmap[closure->channel_num]] = f; closure->set_func = TRUE; } return TRUE; } static void rsvg_filter_primitive_component_transfer_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { gint x, y, c; gint rowstride, height, width; RsvgIRect boundarys; guchar *inpix, outpix[4]; gint achan = ctx->channelmap[3]; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; struct component_transfer_closure closure; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); closure.ctx = ctx; for (c = 0; c < 4; c++) { closure.channel_num = c; closure.channel = "rgba"[c]; /* see rsvg_new_node_component_transfer_function() for where these chars come from */ closure.set_func = FALSE; rsvg_node_foreach_child (node, component_transfer_render_child, &closure); if (!closure.set_func) closure.functions[ctx->channelmap[c]] = identity_component_transfer_func; } in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { inpix = in_pixels + (y * rowstride + x * 4); for (c = 0; c < 4; c++) { gint temp; int inval; if (c != achan) { if (inpix[achan] == 0) inval = 0; else inval = inpix[c] * 255 / inpix[achan]; } else inval = inpix[c]; temp = closure.functions[c] (inval, closure.channels[c]); if (temp > 255) temp = 255; else if (temp < 0) temp = 0; outpix[c] = temp; } for (c = 0; c < 3; c++) output_pixels[y * rowstride + x * 4 + ctx->channelmap[c]] = outpix[ctx->channelmap[c]] * outpix[achan] / 255; output_pixels[y * rowstride + x * 4 + achan] = outpix[achan]; } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_component_transfer_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveComponentTransfer *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_component_transfer (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveComponentTransfer *filter; filter = g_new0 (RsvgFilterPrimitiveComponentTransfer, 1); filter->super.result = g_string_new ("none"); filter->super.in = g_string_new ("none"); filter->super.render = rsvg_filter_primitive_component_transfer_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_COMPONENT_TRANSFER, parent, rsvg_state_new (), filter, rsvg_filter_primitive_component_transfer_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } static void rsvg_node_component_transfer_function_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgNodeComponentTransferFunc *data = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "type"))) { if (!strcmp (value, "identity")) data->function = identity_component_transfer_func; else if (!strcmp (value, "table")) data->function = table_component_transfer_func; else if (!strcmp (value, "discrete")) data->function = discrete_component_transfer_func; else if (!strcmp (value, "linear")) data->function = linear_component_transfer_func; else if (!strcmp (value, "gamma")) data->function = gamma_component_transfer_func; } if ((value = rsvg_property_bag_lookup (atts, "tableValues"))) { unsigned int i; double *temp; if (!rsvg_css_parse_number_list (value, NUMBER_LIST_LENGTH_MAXIMUM, 256, &temp, &data->nbTableValues)) { rsvg_node_set_attribute_parse_error (node, "tableValues", "invalid number list"); return; } data->tableValues = g_new0 (gint, data->nbTableValues); for (i = 0; i < data->nbTableValues; i++) data->tableValues[i] = temp[i] * 255.; g_free (temp); } if ((value = rsvg_property_bag_lookup (atts, "slope"))) { data->slope = g_ascii_strtod (value, NULL) * 255.; } if ((value = rsvg_property_bag_lookup (atts, "intercept"))) { data->intercept = g_ascii_strtod (value, NULL) * 255.; } if ((value = rsvg_property_bag_lookup (atts, "amplitude"))) { data->amplitude = g_ascii_strtod (value, NULL) * 255.; } if ((value = rsvg_property_bag_lookup (atts, "exponent"))) { data->exponent = g_ascii_strtod (value, NULL); } if ((value = rsvg_property_bag_lookup (atts, "offset"))) { data->offset = g_ascii_strtod (value, NULL) * 255.; } } static void rsvg_node_component_transfer_function_free (gpointer impl) { RsvgNodeComponentTransferFunc *filter = impl; if (filter->nbTableValues) g_free (filter->tableValues); g_free (filter); } RsvgNode * rsvg_new_node_component_transfer_function (const char *element_name, RsvgNode *parent) { RsvgNodeComponentTransferFunc *filter; char channel; if (strcmp (element_name, "feFuncR") == 0) channel = 'r'; else if (strcmp (element_name, "feFuncG") == 0) channel = 'g'; else if (strcmp (element_name, "feFuncB") == 0) channel = 'b'; else if (strcmp (element_name, "feFuncA") == 0) channel = 'a'; else { g_assert_not_reached (); channel = '\0'; } filter = g_new0 (RsvgNodeComponentTransferFunc, 1); filter->function = identity_component_transfer_func; filter->nbTableValues = 0; filter->channel = channel; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_COMPONENT_TRANFER_FUNCTION, parent, rsvg_state_new (), filter, rsvg_node_component_transfer_function_set_atts, rsvg_filter_draw, rsvg_node_component_transfer_function_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveErode RsvgFilterPrimitiveErode; struct _RsvgFilterPrimitiveErode { RsvgFilterPrimitive super; double rx, ry; int mode; }; static void rsvg_filter_primitive_erode_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveErode *erode = (RsvgFilterPrimitiveErode *) primitive; guchar ch, extreme; gint x, y; gint i, j; gint rowstride, height, width; RsvgIRect boundarys; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; gint kx, ky; guchar val; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); /* scale the radius values */ kx = erode->rx * ctx->paffine.xx; ky = erode->ry * ctx->paffine.yy; output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) for (ch = 0; ch < 4; ch++) { if (erode->mode == 0) extreme = 255; else extreme = 0; for (i = -ky; i < ky + 1; i++) for (j = -kx; j < kx + 1; j++) { if (y + i >= height || y + i < 0 || x + j >= width || x + j < 0) continue; val = in_pixels[(y + i) * rowstride + (x + j) * 4 + ch]; if (erode->mode == 0) { if (extreme > val) extreme = val; } else { if (extreme < val) extreme = val; } } output_pixels[y * rowstride + x * 4 + ch] = extreme; } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_erode_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveErode *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "radius"))) { if (!rsvg_css_parse_number_optional_number (value, &filter->rx, &filter->ry)) { rsvg_node_set_attribute_parse_error (node, "radius", "expected number-optional-number"); return; } } if ((value = rsvg_property_bag_lookup (atts, "operator"))) { if (!strcmp (value, "erode")) filter->mode = 0; else if (!strcmp (value, "dilate")) filter->mode = 1; } } RsvgNode * rsvg_new_filter_primitive_erode (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveErode *filter; filter = g_new0 (RsvgFilterPrimitiveErode, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->rx = 0; filter->ry = 0; filter->mode = 0; filter->super.render = rsvg_filter_primitive_erode_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_ERODE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_erode_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef enum { COMPOSITE_MODE_OVER, COMPOSITE_MODE_IN, COMPOSITE_MODE_OUT, COMPOSITE_MODE_ATOP, COMPOSITE_MODE_XOR, COMPOSITE_MODE_ARITHMETIC } RsvgFilterPrimitiveCompositeMode; typedef struct _RsvgFilterPrimitiveComposite RsvgFilterPrimitiveComposite; struct _RsvgFilterPrimitiveComposite { RsvgFilterPrimitive super; RsvgFilterPrimitiveCompositeMode mode; GString *in2; int k1, k2, k3, k4; }; static cairo_operator_t composite_mode_to_cairo_operator (RsvgFilterPrimitiveCompositeMode mode) { switch (mode) { case COMPOSITE_MODE_OVER: return CAIRO_OPERATOR_OVER; case COMPOSITE_MODE_IN: return CAIRO_OPERATOR_IN; case COMPOSITE_MODE_OUT: return CAIRO_OPERATOR_OUT; case COMPOSITE_MODE_ATOP: return CAIRO_OPERATOR_ATOP; case COMPOSITE_MODE_XOR: return CAIRO_OPERATOR_XOR; default: g_assert_not_reached (); return CAIRO_OPERATOR_CLEAR; } } static void rsvg_filter_primitive_composite_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveComposite *composite = (RsvgFilterPrimitiveComposite *) primitive; RsvgIRect boundarys; cairo_surface_t *output, *in, *in2; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; in2 = rsvg_filter_get_in (composite->in2, ctx); if (in2 == NULL) { cairo_surface_destroy (in); return; } if (composite->mode == COMPOSITE_MODE_ARITHMETIC) { guchar i; gint x, y; gint rowstride, height, width; guchar *in_pixels; guchar *in2_pixels; guchar *output_pixels; height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); cairo_surface_destroy (in2); return; } cairo_surface_flush (in); cairo_surface_flush (in2); in_pixels = cairo_image_surface_get_data (in); in2_pixels = cairo_image_surface_get_data (in2); output_pixels = cairo_image_surface_get_data (output); for (y = boundarys.y0; y < boundarys.y1; y++) { for (x = boundarys.x0; x < boundarys.x1; x++) { int qr, qa, qb; qa = in_pixels[4 * x + y * rowstride + 3]; qb = in2_pixels[4 * x + y * rowstride + 3]; qr = (composite->k1 * qa * qb / 255 + composite->k2 * qa + composite->k3 * qb) / 255; if (qr > 255) qr = 255; if (qr < 0) qr = 0; output_pixels[4 * x + y * rowstride + 3] = qr; if (qr) { for (i = 0; i < 3; i++) { int ca, cb, cr; ca = in_pixels[4 * x + y * rowstride + i]; cb = in2_pixels[4 * x + y * rowstride + i]; cr = (ca * cb * composite->k1 / 255 + ca * composite->k2 + cb * composite->k3 + composite->k4 * qr) / 255; if (cr > qr) cr = qr; if (cr < 0) cr = 0; output_pixels[4 * x + y * rowstride + i] = cr; } } } } cairo_surface_mark_dirty (output); } else { cairo_t *cr; cairo_surface_reference (in2); output = in2; cr = cairo_create (output); cairo_set_source_surface (cr, in, 0, 0); cairo_rectangle (cr, boundarys.x0, boundarys.y0, boundarys.x1 - boundarys.x0, boundarys.y1 - boundarys.y0); cairo_clip (cr); cairo_set_operator (cr, composite_mode_to_cairo_operator (composite->mode)); cairo_paint (cr); cairo_destroy (cr); } rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (in2); cairo_surface_destroy (output); } static void rsvg_filter_primitive_composite_free (gpointer impl) { RsvgFilterPrimitiveComposite *composite = impl; g_string_free (composite->in2, TRUE); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_composite_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveComposite *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "operator"))) { if (!strcmp (value, "in")) filter->mode = COMPOSITE_MODE_IN; else if (!strcmp (value, "out")) filter->mode = COMPOSITE_MODE_OUT; else if (!strcmp (value, "atop")) filter->mode = COMPOSITE_MODE_ATOP; else if (!strcmp (value, "xor")) filter->mode = COMPOSITE_MODE_XOR; else if (!strcmp (value, "arithmetic")) filter->mode = COMPOSITE_MODE_ARITHMETIC; else filter->mode = COMPOSITE_MODE_OVER; } if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "in2"))) g_string_assign (filter->in2, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "k1"))) filter->k1 = g_ascii_strtod (value, NULL) * 255.; if ((value = rsvg_property_bag_lookup (atts, "k2"))) filter->k2 = g_ascii_strtod (value, NULL) * 255.; if ((value = rsvg_property_bag_lookup (atts, "k3"))) filter->k3 = g_ascii_strtod (value, NULL) * 255.; if ((value = rsvg_property_bag_lookup (atts, "k4"))) filter->k4 = g_ascii_strtod (value, NULL) * 255.; } RsvgNode * rsvg_new_filter_primitive_composite (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveComposite *filter; filter = g_new0 (RsvgFilterPrimitiveComposite, 1); filter->mode = COMPOSITE_MODE_OVER; filter->super.in = g_string_new ("none"); filter->in2 = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->k1 = 0; filter->k2 = 0; filter->k3 = 0; filter->k4 = 0; filter->super.render = rsvg_filter_primitive_composite_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_COMPOSITE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_composite_set_atts, rsvg_filter_draw, rsvg_filter_primitive_composite_free); } /*************************************************************/ /*************************************************************/ static void rsvg_filter_primitive_flood_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgState *state; guchar i; gint x, y; gint rowstride, height, width; RsvgIRect boundarys; guchar *output_pixels; cairo_surface_t *output; char pixcolor[4]; RsvgFilterPrimitiveOutput out; state = rsvg_node_get_state (node); guint32 color = state->flood_color; guint8 opacity = state->flood_opacity; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); height = ctx->height; width = ctx->width; output = _rsvg_image_surface_new (width, height); if (output == NULL) return; rowstride = cairo_image_surface_get_stride (output); output_pixels = cairo_image_surface_get_data (output); for (i = 0; i < 3; i++) pixcolor[i] = (int) (((unsigned char *) (&color))[2 - i]) * opacity / 255; pixcolor[3] = opacity; for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) for (i = 0; i < 4; i++) output_pixels[4 * x + y * rowstride + ctx->channelmap[i]] = pixcolor[i]; cairo_surface_mark_dirty (output); out.surface = output; out.bounds = boundarys; rsvg_filter_store_output (primitive->result, out, ctx); cairo_surface_destroy (output); } static void rsvg_filter_primitive_flood_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitive *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_flood (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitive *filter; filter = g_new0 (RsvgFilterPrimitive, 1); filter->in = g_string_new ("none"); filter->result = g_string_new ("none"); filter->render = rsvg_filter_primitive_flood_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_FLOOD, parent, rsvg_state_new (), filter, rsvg_filter_primitive_flood_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveDisplacementMap RsvgFilterPrimitiveDisplacementMap; struct _RsvgFilterPrimitiveDisplacementMap { RsvgFilterPrimitive super; gint dx, dy; char xChannelSelector, yChannelSelector; GString *in2; double scale; }; static void rsvg_filter_primitive_displacement_map_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveDisplacementMap *displacement_map = (RsvgFilterPrimitiveDisplacementMap *) primitive; guchar ch, xch, ych; gint x, y; gint rowstride, height, width; RsvgIRect boundarys; guchar *in_pixels; guchar *in2_pixels; guchar *output_pixels; cairo_surface_t *output, *in, *in2; double ox, oy; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in2 = rsvg_filter_get_in (displacement_map->in2, ctx); if (in2 == NULL) { cairo_surface_destroy (in); return; } cairo_surface_flush (in2); in_pixels = cairo_image_surface_get_data (in); in2_pixels = cairo_image_surface_get_data (in2); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); cairo_surface_destroy (in2); return; } output_pixels = cairo_image_surface_get_data (output); switch (displacement_map->xChannelSelector) { case 'R': xch = 0; break; case 'G': xch = 1; break; case 'B': xch = 2; break; case 'A': xch = 3; break; default: xch = 0; break; } switch (displacement_map->yChannelSelector) { case 'R': ych = 0; break; case 'G': ych = 1; break; case 'B': ych = 2; break; case 'A': ych = 3; break; default: ych = 1; break; } xch = ctx->channelmap[xch]; ych = ctx->channelmap[ych]; for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { if (xch != 4) ox = x + displacement_map->scale * ctx->paffine.xx * ((double) in2_pixels[y * rowstride + x * 4 + xch] / 255.0 - 0.5); else ox = x; if (ych != 4) oy = y + displacement_map->scale * ctx->paffine.yy * ((double) in2_pixels[y * rowstride + x * 4 + ych] / 255.0 - 0.5); else oy = y; for (ch = 0; ch < 4; ch++) { output_pixels[y * rowstride + x * 4 + ch] = get_interp_pixel (in_pixels, ox, oy, ch, boundarys, rowstride); } } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (in2); cairo_surface_destroy (output); } static void rsvg_filter_primitive_displacement_map_free (gpointer impl) { RsvgFilterPrimitiveDisplacementMap *dmap = impl; g_string_free (dmap->in2, TRUE); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_displacement_map_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveDisplacementMap *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "in2"))) g_string_assign (filter->in2, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "xChannelSelector"))) filter->xChannelSelector = (value)[0]; if ((value = rsvg_property_bag_lookup (atts, "yChannelSelector"))) filter->yChannelSelector = (value)[0]; if ((value = rsvg_property_bag_lookup (atts, "scale"))) filter->scale = g_ascii_strtod (value, NULL); } RsvgNode * rsvg_new_filter_primitive_displacement_map (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveDisplacementMap *filter; filter = g_new0 (RsvgFilterPrimitiveDisplacementMap, 1); filter->super.in = g_string_new ("none"); filter->in2 = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->xChannelSelector = ' '; filter->yChannelSelector = ' '; filter->scale = 0; filter->super.render = rsvg_filter_primitive_displacement_map_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_DISPLACEMENT_MAP, parent, rsvg_state_new (), filter, rsvg_filter_primitive_displacement_map_set_atts, rsvg_filter_draw, rsvg_filter_primitive_displacement_map_free); } /*************************************************************/ /*************************************************************/ /* Produces results in the range [1, 2**31 - 2]. Algorithm is: r = (a * r) mod m where a = 16807 and m = 2**31 - 1 = 2147483647 See [Park & Miller], CACM vol. 31 no. 10 p. 1195, Oct. 1988 To test: the algorithm should produce the result 1043618065 as the 10,000th generated number if the original seed is 1. */ #define feTurbulence_RAND_m 2147483647 /* 2**31 - 1 */ #define feTurbulence_RAND_a 16807 /* 7**5; primitive root of m */ #define feTurbulence_RAND_q 127773 /* m / a */ #define feTurbulence_RAND_r 2836 /* m % a */ #define feTurbulence_BSize 0x100 #define feTurbulence_BM 0xff #define feTurbulence_PerlinN 0x1000 #define feTurbulence_NP 12 /* 2^PerlinN */ #define feTurbulence_NM 0xfff typedef struct _RsvgFilterPrimitiveTurbulence RsvgFilterPrimitiveTurbulence; struct _RsvgFilterPrimitiveTurbulence { RsvgFilterPrimitive super; int uLatticeSelector[feTurbulence_BSize + feTurbulence_BSize + 2]; double fGradient[4][feTurbulence_BSize + feTurbulence_BSize + 2][2]; int seed; double fBaseFreqX; double fBaseFreqY; int nNumOctaves; gboolean bFractalSum; gboolean bDoStitching; }; struct feTurbulence_StitchInfo { int nWidth; /* How much to subtract to wrap for stitching. */ int nHeight; int nWrapX; /* Minimum value to wrap. */ int nWrapY; }; static long feTurbulence_setup_seed (int lSeed) { if (lSeed <= 0) lSeed = -(lSeed % (feTurbulence_RAND_m - 1)) + 1; if (lSeed > feTurbulence_RAND_m - 1) lSeed = feTurbulence_RAND_m - 1; return lSeed; } static long feTurbulence_random (int lSeed) { long result; result = feTurbulence_RAND_a * (lSeed % feTurbulence_RAND_q) - feTurbulence_RAND_r * (lSeed / feTurbulence_RAND_q); if (result <= 0) result += feTurbulence_RAND_m; return result; } static void feTurbulence_init (RsvgFilterPrimitiveTurbulence * filter) { double s; int i, j, k, lSeed; lSeed = feTurbulence_setup_seed (filter->seed); for (k = 0; k < 4; k++) { for (i = 0; i < feTurbulence_BSize; i++) { filter->uLatticeSelector[i] = i; for (j = 0; j < 2; j++) filter->fGradient[k][i][j] = (double) (((lSeed = feTurbulence_random (lSeed)) % (feTurbulence_BSize + feTurbulence_BSize)) - feTurbulence_BSize) / feTurbulence_BSize; s = (double) (sqrt (filter->fGradient[k][i][0] * filter->fGradient[k][i][0] + filter->fGradient[k][i][1] * filter->fGradient[k][i][1])); filter->fGradient[k][i][0] /= s; filter->fGradient[k][i][1] /= s; } } while (--i) { k = filter->uLatticeSelector[i]; filter->uLatticeSelector[i] = filter->uLatticeSelector[j = (lSeed = feTurbulence_random (lSeed)) % feTurbulence_BSize]; filter->uLatticeSelector[j] = k; } for (i = 0; i < feTurbulence_BSize + 2; i++) { filter->uLatticeSelector[feTurbulence_BSize + i] = filter->uLatticeSelector[i]; for (k = 0; k < 4; k++) for (j = 0; j < 2; j++) filter->fGradient[k][feTurbulence_BSize + i][j] = filter->fGradient[k][i][j]; } } #define feTurbulence_s_curve(t) ( t * t * (3. - 2. * t) ) #define feTurbulence_lerp(t, a, b) ( a + t * (b - a) ) static double feTurbulence_noise2 (RsvgFilterPrimitiveTurbulence * filter, int nColorChannel, double vec[2], struct feTurbulence_StitchInfo *pStitchInfo) { int bx0, bx1, by0, by1, b00, b10, b01, b11; double rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v; register int i, j; t = vec[0] + feTurbulence_PerlinN; bx0 = (int) t; bx1 = bx0 + 1; rx0 = t - (int) t; rx1 = rx0 - 1.0f; t = vec[1] + feTurbulence_PerlinN; by0 = (int) t; by1 = by0 + 1; ry0 = t - (int) t; ry1 = ry0 - 1.0f; /* If stitching, adjust lattice points accordingly. */ if (pStitchInfo != NULL) { if (bx0 >= pStitchInfo->nWrapX) bx0 -= pStitchInfo->nWidth; if (bx1 >= pStitchInfo->nWrapX) bx1 -= pStitchInfo->nWidth; if (by0 >= pStitchInfo->nWrapY) by0 -= pStitchInfo->nHeight; if (by1 >= pStitchInfo->nWrapY) by1 -= pStitchInfo->nHeight; } bx0 &= feTurbulence_BM; bx1 &= feTurbulence_BM; by0 &= feTurbulence_BM; by1 &= feTurbulence_BM; i = filter->uLatticeSelector[bx0]; j = filter->uLatticeSelector[bx1]; b00 = filter->uLatticeSelector[i + by0]; b10 = filter->uLatticeSelector[j + by0]; b01 = filter->uLatticeSelector[i + by1]; b11 = filter->uLatticeSelector[j + by1]; sx = (double) (feTurbulence_s_curve (rx0)); sy = (double) (feTurbulence_s_curve (ry0)); q = filter->fGradient[nColorChannel][b00]; u = rx0 * q[0] + ry0 * q[1]; q = filter->fGradient[nColorChannel][b10]; v = rx1 * q[0] + ry0 * q[1]; a = feTurbulence_lerp (sx, u, v); q = filter->fGradient[nColorChannel][b01]; u = rx0 * q[0] + ry1 * q[1]; q = filter->fGradient[nColorChannel][b11]; v = rx1 * q[0] + ry1 * q[1]; b = feTurbulence_lerp (sx, u, v); return feTurbulence_lerp (sy, a, b); } static double feTurbulence_turbulence (RsvgFilterPrimitiveTurbulence * filter, int nColorChannel, double *point, double fTileX, double fTileY, double fTileWidth, double fTileHeight) { struct feTurbulence_StitchInfo stitch; struct feTurbulence_StitchInfo *pStitchInfo = NULL; /* Not stitching when NULL. */ double fSum = 0.0f, vec[2], ratio = 1.; int nOctave; /* Adjust the base frequencies if necessary for stitching. */ if (filter->bDoStitching) { /* When stitching tiled turbulence, the frequencies must be adjusted so that the tile borders will be continuous. */ if (filter->fBaseFreqX != 0.0) { double fLoFreq = (double) (floor (fTileWidth * filter->fBaseFreqX)) / fTileWidth; double fHiFreq = (double) (ceil (fTileWidth * filter->fBaseFreqX)) / fTileWidth; if (filter->fBaseFreqX / fLoFreq < fHiFreq / filter->fBaseFreqX) filter->fBaseFreqX = fLoFreq; else filter->fBaseFreqX = fHiFreq; } if (filter->fBaseFreqY != 0.0) { double fLoFreq = (double) (floor (fTileHeight * filter->fBaseFreqY)) / fTileHeight; double fHiFreq = (double) (ceil (fTileHeight * filter->fBaseFreqY)) / fTileHeight; if (filter->fBaseFreqY / fLoFreq < fHiFreq / filter->fBaseFreqY) filter->fBaseFreqY = fLoFreq; else filter->fBaseFreqY = fHiFreq; } /* Set up initial stitch values. */ pStitchInfo = &stitch; stitch.nWidth = (int) (fTileWidth * filter->fBaseFreqX + 0.5f); stitch.nWrapX = fTileX * filter->fBaseFreqX + feTurbulence_PerlinN + stitch.nWidth; stitch.nHeight = (int) (fTileHeight * filter->fBaseFreqY + 0.5f); stitch.nWrapY = fTileY * filter->fBaseFreqY + feTurbulence_PerlinN + stitch.nHeight; } vec[0] = point[0] * filter->fBaseFreqX; vec[1] = point[1] * filter->fBaseFreqY; for (nOctave = 0; nOctave < filter->nNumOctaves; nOctave++) { if (filter->bFractalSum) fSum += (double) (feTurbulence_noise2 (filter, nColorChannel, vec, pStitchInfo) / ratio); else fSum += (double) (fabs (feTurbulence_noise2 (filter, nColorChannel, vec, pStitchInfo)) / ratio); vec[0] *= 2; vec[1] *= 2; ratio *= 2; if (pStitchInfo != NULL) { /* Update stitch values. Subtracting PerlinN before the multiplication and adding it afterward simplifies to subtracting it once. */ stitch.nWidth *= 2; stitch.nWrapX = 2 * stitch.nWrapX - feTurbulence_PerlinN; stitch.nHeight *= 2; stitch.nWrapY = 2 * stitch.nWrapY - feTurbulence_PerlinN; } } return fSum; } static void rsvg_filter_primitive_turbulence_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveTurbulence *turbulence = (RsvgFilterPrimitiveTurbulence *) primitive; gint x, y, tileWidth, tileHeight, rowstride, width, height; RsvgIRect boundarys; guchar *output_pixels; cairo_surface_t *output, *in; cairo_matrix_t affine; affine = ctx->paffine; if (cairo_matrix_invert (&affine) != CAIRO_STATUS_SUCCESS) return; in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); tileWidth = (boundarys.x1 - boundarys.x0); tileHeight = (boundarys.y1 - boundarys.y0); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); for (y = 0; y < tileHeight; y++) { for (x = 0; x < tileWidth; x++) { gint i; double point[2]; guchar *pixel; point[0] = affine.xx * (x + boundarys.x0) + affine.xy * (y + boundarys.y0) + affine.x0; point[1] = affine.yx * (x + boundarys.x0) + affine.yy * (y + boundarys.y0) + affine.y0; pixel = output_pixels + 4 * (x + boundarys.x0) + (y + boundarys.y0) * rowstride; for (i = 0; i < 4; i++) { double cr; cr = feTurbulence_turbulence (turbulence, i, point, (double) x, (double) y, (double) tileWidth, (double) tileHeight); if (turbulence->bFractalSum) cr = ((cr * 255.) + 255.) / 2.; else cr = (cr * 255.); cr = CLAMP (cr, 0., 255.); pixel[ctx->channelmap[i]] = (guchar) cr; } for (i = 0; i < 3; i++) pixel[ctx->channelmap[i]] = pixel[ctx->channelmap[i]] * pixel[ctx->channelmap[3]] / 255; } } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_turbulence_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveTurbulence *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "baseFrequency"))) { if (!rsvg_css_parse_number_optional_number (value, &filter->fBaseFreqX, &filter->fBaseFreqY)) { rsvg_node_set_attribute_parse_error (node, "baseFrequency", "expected number-optional-number"); return; } } if ((value = rsvg_property_bag_lookup (atts, "numOctaves"))) filter->nNumOctaves = atoi (value); if ((value = rsvg_property_bag_lookup (atts, "seed"))) filter->seed = atoi (value); if ((value = rsvg_property_bag_lookup (atts, "stitchTiles"))) filter->bDoStitching = (!strcmp (value, "stitch")); if ((value = rsvg_property_bag_lookup (atts, "type"))) filter->bFractalSum = (!strcmp (value, "fractalNoise")); } RsvgNode * rsvg_new_filter_primitive_turbulence (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveTurbulence *filter; filter = g_new0 (RsvgFilterPrimitiveTurbulence, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->fBaseFreqX = 0; filter->fBaseFreqY = 0; filter->nNumOctaves = 1; filter->seed = 0; filter->bDoStitching = 0; filter->bFractalSum = 0; feTurbulence_init (filter); filter->super.render = rsvg_filter_primitive_turbulence_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_TURBULENCE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_turbulence_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveImage RsvgFilterPrimitiveImage; struct _RsvgFilterPrimitiveImage { RsvgFilterPrimitive super; RsvgHandle *ctx; GString *href; }; static cairo_surface_t * rsvg_filter_primitive_image_render_in (RsvgFilterPrimitiveImage *image, RsvgFilterContext * context) { RsvgDrawingCtx *ctx; RsvgNode *drawable; cairo_surface_t *result; ctx = context->ctx; if (!image->href) return NULL; drawable = rsvg_drawing_ctx_acquire_node (ctx, image->href->str); if (!drawable) return NULL; rsvg_current_state (ctx)->affine = context->paffine; result = rsvg_get_surface_of_node (ctx, drawable, context->width, context->height); rsvg_drawing_ctx_release_node (ctx, drawable); return result; } static cairo_surface_t * rsvg_filter_primitive_image_render_ext (RsvgFilterPrimitive *self, RsvgFilterContext * ctx) { RsvgFilterPrimitiveImage *image = (RsvgFilterPrimitiveImage *) self; RsvgIRect boundarys; cairo_surface_t *img, *intermediate; int i; unsigned char *pixels; int channelmap[4]; int length; int width, height; if (!image->href) return NULL; boundarys = rsvg_filter_primitive_get_bounds (self, ctx); width = boundarys.x1 - boundarys.x0; height = boundarys.y1 - boundarys.y0; if (width == 0 || height == 0) return NULL; img = rsvg_cairo_surface_new_from_href (image->ctx, image->href->str, NULL); if (!img) return NULL; intermediate = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); if (cairo_surface_status (intermediate) != CAIRO_STATUS_SUCCESS || !rsvg_art_affine_image (img, intermediate, &ctx->paffine, (gdouble) width / ctx->paffine.xx, (gdouble) height / ctx->paffine.yy)) { cairo_surface_destroy (intermediate); cairo_surface_destroy (img); return NULL; } cairo_surface_destroy (img); length = cairo_image_surface_get_height (intermediate) * cairo_image_surface_get_stride (intermediate); for (i = 0; i < 4; i++) channelmap[i] = ctx->channelmap[i]; pixels = cairo_image_surface_get_data (intermediate); for (i = 0; i < length; i += 4) { unsigned char alpha; unsigned char pixel[4]; int ch; alpha = pixels[i + 3]; pixel[channelmap[3]] = alpha; if (alpha) for (ch = 0; ch < 3; ch++) pixel[channelmap[ch]] = pixels[i + ch] * alpha / 255; else for (ch = 0; ch < 3; ch++) pixel[channelmap[ch]] = 0; for (ch = 0; ch < 4; ch++) pixels[i + ch] = pixel[ch]; } cairo_surface_mark_dirty (intermediate); return intermediate; } static void rsvg_filter_primitive_image_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveImage *image = (RsvgFilterPrimitiveImage *) primitive; RsvgIRect boundarys; RsvgFilterPrimitiveOutput op; cairo_surface_t *output, *img; if (!image->href) return; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); output = _rsvg_image_surface_new (ctx->width, ctx->height); if (output == NULL) return; img = rsvg_filter_primitive_image_render_in (image, ctx); if (img == NULL) { img = rsvg_filter_primitive_image_render_ext (primitive, ctx); } if (img) { cairo_t *cr; cr = cairo_create (output); cairo_set_source_surface (cr, img, 0, 0); cairo_rectangle (cr, boundarys.x0, boundarys.y0, boundarys.x1 - boundarys.x0, boundarys.y1 - boundarys.y0); cairo_clip (cr); cairo_paint (cr); cairo_destroy (cr); cairo_surface_destroy (img); } op.surface = output; op.bounds = boundarys; rsvg_filter_store_output (primitive->result, op, ctx); cairo_surface_destroy (output); } static void rsvg_filter_primitive_image_free (gpointer impl) { RsvgFilterPrimitiveImage *image = impl; if (image->href) g_string_free (image->href, TRUE); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_image_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveImage *filter = impl; const char *value; filter->ctx = handle; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); if ((value = rsvg_property_bag_lookup (atts, "xlink:href"))) { filter->href = g_string_new (NULL); g_string_assign (filter->href, value); } filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_image (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveImage *filter; filter = g_new0 (RsvgFilterPrimitiveImage, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->super.render = rsvg_filter_primitive_image_render; filter->href = NULL; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_IMAGE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_image_set_atts, rsvg_filter_draw, rsvg_filter_primitive_image_free); } /*************************************************************/ /*************************************************************/ typedef struct _FactorAndMatrix FactorAndMatrix; struct _FactorAndMatrix { gint matrix[9]; gdouble factor; }; typedef struct _vector3 vector3; struct _vector3 { gdouble x; gdouble y; gdouble z; }; static gdouble norm (vector3 A) { return sqrt (A.x * A.x + A.y * A.y + A.z * A.z); } static gdouble dotproduct (vector3 A, vector3 B) { return A.x * B.x + A.y * B.y + A.z * B.z; } static vector3 normalise (vector3 A) { double divisor; divisor = norm (A); A.x /= divisor; A.y /= divisor; A.z /= divisor; return A; } static FactorAndMatrix get_light_normal_matrix_x (gint n) { static const FactorAndMatrix matrix_list[] = { { {0, 0, 0, 0, -2, 2, 0, -1, 1}, 2.0 / 3.0}, { {0, 0, 0, -2, 0, 2, -1, 0, 1}, 1.0 / 3.0}, { {0, 0, 0, -2, 2, 0, -1, 1, 0}, 2.0 / 3.0}, { {0, -1, 1, 0, -2, 2, 0, -1, 1}, 1.0 / 2.0}, { {-1, 0, 1, -2, 0, 2, -1, 0, 1}, 1.0 / 4.0}, { {-1, 1, 0, -2, 2, 0, -1, 1, 0}, 1.0 / 2.0}, { {0, -1, 1, 0, -2, 2, 0, 0, 0}, 2.0 / 3.0}, { {-1, 0, 1, -2, 0, 2, 0, 0, 0}, 1.0 / 3.0}, { {-1, 1, 0, -2, 2, 0, 0, 0, 0}, 2.0 / 3.0} }; return matrix_list[n]; } static FactorAndMatrix get_light_normal_matrix_y (gint n) { static const FactorAndMatrix matrix_list[] = { { {0, 0, 0, 0, -2, -1, 0, 2, 1}, 2.0 / 3.0}, { {0, 0, 0, -1, -2, -1, 1, 2, 1}, 1.0 / 3.0}, { {0, 0, 0, -1, -2, 0, 1, 2, 0}, 2.0 / 3.0}, { {0, -2, -1, 0, 0, 0, 0, 2, 1}, 1.0 / 2.0}, { {-1, -2, -1, 0, 0, 0, 1, 2, 1}, 1.0 / 4.0}, { {-1, -2, 0, 0, 0, 0, 1, 2, 0}, 1.0 / 2.0}, { {0, -2, -1, 0, 2, 1, 0, 0, 0}, 2.0 / 3.0}, { {0, -2, -1, 1, 2, 1, 0, 0, 0}, 1.0 / 3.0}, { {-1, -2, 0, 1, 2, 0, 0, 0, 0}, 2.0 / 3.0} }; return matrix_list[n]; } static vector3 get_surface_normal (guchar * I, RsvgIRect boundarys, gint x, gint y, gdouble dx, gdouble dy, gdouble rawdx, gdouble rawdy, gdouble surfaceScale, gint rowstride, int chan) { gint mrow, mcol; FactorAndMatrix fnmx, fnmy; gint *Kx, *Ky; gdouble factorx, factory; gdouble Nx, Ny; vector3 output; if (x + dx >= boundarys.x1 - 1) mcol = 2; else if (x - dx < boundarys.x0 + 1) mcol = 0; else mcol = 1; if (y + dy >= boundarys.y1 - 1) mrow = 2; else if (y - dy < boundarys.y0 + 1) mrow = 0; else mrow = 1; fnmx = get_light_normal_matrix_x (mrow * 3 + mcol); factorx = fnmx.factor / rawdx; Kx = fnmx.matrix; fnmy = get_light_normal_matrix_y (mrow * 3 + mcol); factory = fnmy.factor / rawdy; Ky = fnmy.matrix; Nx = -surfaceScale * factorx * ((gdouble) (Kx[0] * get_interp_pixel (I, x - dx, y - dy, chan, boundarys, rowstride) + Kx[1] * get_interp_pixel (I, x, y - dy, chan, boundarys, rowstride) + Kx[2] * get_interp_pixel (I, x + dx, y - dy, chan, boundarys, rowstride) + Kx[3] * get_interp_pixel (I, x - dx, y, chan, boundarys, rowstride) + Kx[4] * get_interp_pixel (I, x, y, chan, boundarys, rowstride) + Kx[5] * get_interp_pixel (I, x + dx, y, chan, boundarys, rowstride) + Kx[6] * get_interp_pixel (I, x - dx, y + dy, chan, boundarys, rowstride) + Kx[7] * get_interp_pixel (I, x, y + dy, chan, boundarys, rowstride) + Kx[8] * get_interp_pixel (I, x + dx, y + dy, chan, boundarys, rowstride))) / 255.0; Ny = -surfaceScale * factory * ((gdouble) (Ky[0] * get_interp_pixel (I, x - dx, y - dy, chan, boundarys, rowstride) + Ky[1] * get_interp_pixel (I, x, y - dy, chan, boundarys, rowstride) + Ky[2] * get_interp_pixel (I, x + dx, y - dy, chan, boundarys, rowstride) + Ky[3] * get_interp_pixel (I, x - dx, y, chan, boundarys, rowstride) + Ky[4] * get_interp_pixel (I, x, y, chan, boundarys, rowstride) + Ky[5] * get_interp_pixel (I, x + dx, y, chan, boundarys, rowstride) + Ky[6] * get_interp_pixel (I, x - dx, y + dy, chan, boundarys, rowstride) + Ky[7] * get_interp_pixel (I, x, y + dy, chan, boundarys, rowstride) + Ky[8] * get_interp_pixel (I, x + dx, y + dy, chan, boundarys, rowstride))) / 255.0; output.x = Nx; output.y = Ny; output.z = 1; output = normalise (output); return output; } typedef enum { DISTANTLIGHT, POINTLIGHT, SPOTLIGHT } lightType; typedef struct _RsvgNodeLightSource RsvgNodeLightSource; struct _RsvgNodeLightSource { lightType type; gdouble azimuth; gdouble elevation; RsvgLength x, y, z, pointsAtX, pointsAtY, pointsAtZ; gdouble specularExponent; gdouble limitingconeAngle; }; static vector3 get_light_direction (RsvgNodeLightSource * source, gdouble x1, gdouble y1, gdouble z, cairo_matrix_t *affine, RsvgDrawingCtx * ctx) { vector3 output; switch (source->type) { case DISTANTLIGHT: output.x = cos (source->azimuth) * cos (source->elevation); output.y = sin (source->azimuth) * cos (source->elevation); output.z = sin (source->elevation); break; default: { double x, y; x = affine->xx * x1 + affine->xy * y1 + affine->x0; y = affine->yx * x1 + affine->yy * y1 + affine->y0; output.x = rsvg_length_normalize (&source->x, ctx) - x; output.y = rsvg_length_normalize (&source->y, ctx) - y; output.z = rsvg_length_normalize (&source->z, ctx) - z; output = normalise (output); } break; } return output; } static vector3 get_light_color (RsvgNodeLightSource * source, vector3 color, gdouble x1, gdouble y1, gdouble z, cairo_matrix_t *affine, RsvgDrawingCtx * ctx) { double base, angle, x, y; vector3 s; vector3 L; vector3 output; double sx, sy, sz, spx, spy, spz; if (source->type != SPOTLIGHT) return color; sx = rsvg_length_normalize (&source->x, ctx); sy = rsvg_length_normalize (&source->y, ctx); sz = rsvg_length_normalize (&source->z, ctx); spx = rsvg_length_normalize (&source->pointsAtX, ctx); spy = rsvg_length_normalize (&source->pointsAtY, ctx); spz = rsvg_length_normalize (&source->pointsAtZ, ctx); x = affine->xx * x1 + affine->xy * y1 + affine->x0; y = affine->yx * x1 + affine->yy * y1 + affine->y0; L.x = sx - x; L.y = sy - y; L.z = sz - z; L = normalise (L); s.x = spx - sx; s.y = spy - sy; s.z = spz - sz; s = normalise (s); base = -dotproduct (L, s); angle = acos (base); if (base < 0 || angle > source->limitingconeAngle) { output.x = 0; output.y = 0; output.z = 0; return output; } output.x = color.x * pow (base, source->specularExponent); output.y = color.y * pow (base, source->specularExponent); output.z = color.z * pow (base, source->specularExponent); return output; } static void rsvg_node_light_source_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgNodeLightSource *data = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "azimuth"))) data->azimuth = g_ascii_strtod (value, NULL) / 180.0 * M_PI; if ((value = rsvg_property_bag_lookup (atts, "elevation"))) data->elevation = g_ascii_strtod (value, NULL) / 180.0 * M_PI; if ((value = rsvg_property_bag_lookup (atts, "limitingConeAngle"))) data->limitingconeAngle = g_ascii_strtod (value, NULL) / 180.0 * M_PI; if ((value = rsvg_property_bag_lookup (atts, "x"))) data->x = data->pointsAtX = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); if ((value = rsvg_property_bag_lookup (atts, "y"))) data->y = data->pointsAtX = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); if ((value = rsvg_property_bag_lookup (atts, "z"))) data->z = data->pointsAtX = rsvg_length_parse (value, LENGTH_DIR_BOTH); if ((value = rsvg_property_bag_lookup (atts, "pointsAtX"))) data->pointsAtX = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); if ((value = rsvg_property_bag_lookup (atts, "pointsAtY"))) data->pointsAtY = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); if ((value = rsvg_property_bag_lookup (atts, "pointsAtZ"))) data->pointsAtZ = rsvg_length_parse (value, LENGTH_DIR_BOTH); if ((value = rsvg_property_bag_lookup (atts, "specularExponent"))) data->specularExponent = g_ascii_strtod (value, NULL); } RsvgNode * rsvg_new_node_light_source (const char *element_name, RsvgNode *parent) { RsvgNodeLightSource *data; data = g_new0 (RsvgNodeLightSource, 1); data->specularExponent = 1; if (strcmp (element_name, "feDistantLight") == 0) data->type = SPOTLIGHT; else if (strcmp (element_name, "feSpotLight") == 0) data->type = DISTANTLIGHT; else if (strcmp (element_name, "fePointLight") == 0) data->type = POINTLIGHT; else g_assert_not_reached (); data->limitingconeAngle = 180; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_LIGHT_SOURCE, parent, rsvg_state_new (), data, rsvg_node_light_source_set_atts, rsvg_filter_draw, g_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveDiffuseLighting RsvgFilterPrimitiveDiffuseLighting; struct _RsvgFilterPrimitiveDiffuseLighting { RsvgFilterPrimitive super; gdouble dx, dy; double diffuseConstant; double surfaceScale; guint32 lightingcolor; }; struct find_light_source_closure { RsvgNode *found_node; }; static gboolean is_light_source (RsvgNode *node, gpointer data) { struct find_light_source_closure *closure = data; if (rsvg_node_get_type (node) == RSVG_NODE_TYPE_LIGHT_SOURCE) { closure->found_node = rsvg_node_ref (node); } return TRUE; } static RsvgNodeLightSource * find_light_source_in_children (RsvgNode *node) { struct find_light_source_closure closure; RsvgNodeLightSource *source; closure.found_node = NULL; rsvg_node_foreach_child (node, is_light_source, &closure); if (closure.found_node == NULL) return NULL; g_assert (rsvg_node_get_type (closure.found_node) == RSVG_NODE_TYPE_LIGHT_SOURCE); source = rsvg_rust_cnode_get_impl (closure.found_node); closure.found_node = rsvg_node_unref (closure.found_node); return source; } static void rsvg_filter_primitive_diffuse_lighting_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveDiffuseLighting *diffuse_lighting = (RsvgFilterPrimitiveDiffuseLighting *) primitive; gint x, y; float dy, dx, rawdy, rawdx; gdouble z; gint rowstride, height, width; gdouble factor, surfaceScale; vector3 lightcolor, L, N; vector3 color; cairo_matrix_t iaffine; RsvgNodeLightSource *source = NULL; RsvgIRect boundarys; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; source = find_light_source_in_children (node); if (source == NULL) return; iaffine = ctx->paffine; if (cairo_matrix_invert (&iaffine) != CAIRO_STATUS_SUCCESS) return; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); color.x = ((guchar *) (&diffuse_lighting->lightingcolor))[2] / 255.0; color.y = ((guchar *) (&diffuse_lighting->lightingcolor))[1] / 255.0; color.z = ((guchar *) (&diffuse_lighting->lightingcolor))[0] / 255.0; surfaceScale = diffuse_lighting->surfaceScale / 255.0; if (diffuse_lighting->dy < 0 || diffuse_lighting->dx < 0) { dx = 1; dy = 1; rawdx = 1; rawdy = 1; } else { dx = diffuse_lighting->dx * ctx->paffine.xx; dy = diffuse_lighting->dy * ctx->paffine.yy; rawdx = diffuse_lighting->dx; rawdy = diffuse_lighting->dy; } for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { z = surfaceScale * (double) in_pixels[y * rowstride + x * 4 + ctx->channelmap[3]]; L = get_light_direction (source, x, y, z, &iaffine, ctx->ctx); N = get_surface_normal (in_pixels, boundarys, x, y, dx, dy, rawdx, rawdy, diffuse_lighting->surfaceScale, rowstride, ctx->channelmap[3]); lightcolor = get_light_color (source, color, x, y, z, &iaffine, ctx->ctx); factor = dotproduct (N, L); output_pixels[y * rowstride + x * 4 + ctx->channelmap[0]] = MAX (0, MIN (255, diffuse_lighting->diffuseConstant * factor * lightcolor.x * 255.0)); output_pixels[y * rowstride + x * 4 + ctx->channelmap[1]] = MAX (0, MIN (255, diffuse_lighting->diffuseConstant * factor * lightcolor.y * 255.0)); output_pixels[y * rowstride + x * 4 + ctx->channelmap[2]] = MAX (0, MIN (255, diffuse_lighting->diffuseConstant * factor * lightcolor.z * 255.0)); output_pixels[y * rowstride + x * 4 + ctx->channelmap[3]] = 255; } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_diffuse_lighting_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveDiffuseLighting *filter = impl; const char *value; RsvgState *state; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "kernelUnitLength"))) rsvg_css_parse_number_optional_number (value, &filter->dx, &filter->dy); if ((value = rsvg_property_bag_lookup (atts, "lighting-color"))) { RsvgCssColorSpec spec; spec = rsvg_css_parse_color (value, ALLOW_INHERIT_YES, ALLOW_CURRENT_COLOR_YES); switch (spec.kind) { case RSVG_CSS_COLOR_SPEC_INHERIT: /* FIXME: we should inherit; see how stop-color is handled in rsvg-styles.c */ break; case RSVG_CSS_COLOR_SPEC_CURRENT_COLOR: state = rsvg_state_new (); rsvg_state_reconstruct (state, node); filter->lightingcolor = state->current_color; break; case RSVG_CSS_COLOR_SPEC_ARGB: filter->lightingcolor = spec.argb; break; case RSVG_CSS_COLOR_PARSE_ERROR: rsvg_node_set_attribute_parse_error (node, "lighting-color", "Invalid color"); break; default: g_assert_not_reached (); } } if ((value = rsvg_property_bag_lookup (atts, "diffuseConstant"))) filter->diffuseConstant = g_ascii_strtod (value, NULL); if ((value = rsvg_property_bag_lookup (atts, "surfaceScale"))) filter->surfaceScale = g_ascii_strtod (value, NULL); } RsvgNode * rsvg_new_filter_primitive_diffuse_lighting (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveDiffuseLighting *filter; filter = g_new0 (RsvgFilterPrimitiveDiffuseLighting, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->surfaceScale = 1; filter->diffuseConstant = 1; filter->dx = 1; filter->dy = 1; filter->lightingcolor = 0xFFFFFFFF; filter->super.render = rsvg_filter_primitive_diffuse_lighting_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_DIFFUSE_LIGHTING, parent, rsvg_state_new (), filter, rsvg_filter_primitive_diffuse_lighting_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveSpecularLighting RsvgFilterPrimitiveSpecularLighting; struct _RsvgFilterPrimitiveSpecularLighting { RsvgFilterPrimitive super; double specularConstant; double specularExponent; double surfaceScale; guint32 lightingcolor; }; static void rsvg_filter_primitive_specular_lighting_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveSpecularLighting *specular_lighting = (RsvgFilterPrimitiveSpecularLighting *) primitive; gint x, y; gdouble z, surfaceScale; gint rowstride, height, width; gdouble factor, max, base; vector3 lightcolor, color; vector3 L; cairo_matrix_t iaffine; RsvgIRect boundarys; RsvgNodeLightSource *source = NULL; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; source = find_light_source_in_children (node); if (source == NULL) return; iaffine = ctx->paffine; if (cairo_matrix_invert (&iaffine) != CAIRO_STATUS_SUCCESS) return; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); color.x = ((guchar *) (&specular_lighting->lightingcolor))[2] / 255.0; color.y = ((guchar *) (&specular_lighting->lightingcolor))[1] / 255.0; color.z = ((guchar *) (&specular_lighting->lightingcolor))[0] / 255.0; surfaceScale = specular_lighting->surfaceScale / 255.0; for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { z = in_pixels[y * rowstride + x * 4 + 3] * surfaceScale; L = get_light_direction (source, x, y, z, &iaffine, ctx->ctx); L.z += 1; L = normalise (L); lightcolor = get_light_color (source, color, x, y, z, &iaffine, ctx->ctx); base = dotproduct (get_surface_normal (in_pixels, boundarys, x, y, 1, 1, 1.0 / ctx->paffine.xx, 1.0 / ctx->paffine.yy, specular_lighting->surfaceScale, rowstride, ctx->channelmap[3]), L); factor = specular_lighting->specularConstant * pow (base, specular_lighting->specularExponent) * 255; max = 0; if (max < lightcolor.x) max = lightcolor.x; if (max < lightcolor.y) max = lightcolor.y; if (max < lightcolor.z) max = lightcolor.z; max *= factor; if (max > 255) max = 255; if (max < 0) max = 0; output_pixels[y * rowstride + x * 4 + ctx->channelmap[0]] = lightcolor.x * max; output_pixels[y * rowstride + x * 4 + ctx->channelmap[1]] = lightcolor.y * max; output_pixels[y * rowstride + x * 4 + ctx->channelmap[2]] = lightcolor.z * max; output_pixels[y * rowstride + x * 4 + ctx->channelmap[3]] = max; } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_specular_lighting_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveSpecularLighting *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "lighting-color"))) { RsvgCssColorSpec spec; RsvgState *state; spec = rsvg_css_parse_color (value, ALLOW_INHERIT_YES, ALLOW_CURRENT_COLOR_YES); switch (spec.kind) { case RSVG_CSS_COLOR_SPEC_INHERIT: /* FIXME: we should inherit; see how stop-color is handled in rsvg-styles.c */ break; case RSVG_CSS_COLOR_SPEC_CURRENT_COLOR: state = rsvg_state_new (); rsvg_state_reconstruct (state, node); filter->lightingcolor = state->current_color; break; case RSVG_CSS_COLOR_SPEC_ARGB: filter->lightingcolor = spec.argb; break; case RSVG_CSS_COLOR_PARSE_ERROR: rsvg_node_set_attribute_parse_error (node, "lighting-color", "Invalid color"); break; default: g_assert_not_reached (); } } if ((value = rsvg_property_bag_lookup (atts, "specularConstant"))) filter->specularConstant = g_ascii_strtod (value, NULL); if ((value = rsvg_property_bag_lookup (atts, "specularExponent"))) filter->specularExponent = g_ascii_strtod (value, NULL); if ((value = rsvg_property_bag_lookup (atts, "surfaceScale"))) filter->surfaceScale = g_ascii_strtod (value, NULL); } RsvgNode * rsvg_new_filter_primitive_specular_lighting (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveSpecularLighting *filter; filter = g_new0 (RsvgFilterPrimitiveSpecularLighting, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->surfaceScale = 1; filter->specularConstant = 1; filter->specularExponent = 1; filter->lightingcolor = 0xFFFFFFFF; filter->super.render = rsvg_filter_primitive_specular_lighting_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_SPECULAR_LIGHTING, parent, rsvg_state_new (), filter, rsvg_filter_primitive_specular_lighting_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveTile RsvgFilterPrimitiveTile; struct _RsvgFilterPrimitiveTile { RsvgFilterPrimitive super; }; static int mod (int a, int b) { while (a < 0) a += b; return a % b; } static void rsvg_filter_primitive_tile_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { guchar i; gint x, y, rowstride; RsvgIRect boundarys, oboundarys; RsvgFilterPrimitiveOutput input; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; oboundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); input = rsvg_filter_get_result (primitive->in, ctx); in = input.surface; boundarys = input.bounds; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); output = _rsvg_image_surface_new (ctx->width, ctx->height); if (output == NULL) { cairo_surface_destroy (in); return; } rowstride = cairo_image_surface_get_stride (output); output_pixels = cairo_image_surface_get_data (output); for (y = oboundarys.y0; y < oboundarys.y1; y++) for (x = oboundarys.x0; x < oboundarys.x1; x++) for (i = 0; i < 4; i++) { output_pixels[4 * x + y * rowstride + i] = in_pixels[(mod ((x - boundarys.x0), (boundarys.x1 - boundarys.x0)) + boundarys.x0) * 4 + (mod ((y - boundarys.y0), (boundarys.y1 - boundarys.y0)) + boundarys.y0) * rowstride + i]; } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_tile_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveTile *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_tile (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveTile *filter; filter = g_new0 (RsvgFilterPrimitiveTile, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->super.render = rsvg_filter_primitive_tile_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_TILE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_tile_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); }
./CrossVul/dataset_final_sorted/CWE-369/c/good_2580_0
crossvul-cpp_data_good_3367_0
// imagew-api.c // Part of ImageWorsener, Copyright (c) 2011 by Jason Summers. // For more information, see the readme.txt file. // Most of the functions declared in imagew.h are defined here. #include "imagew-config.h" #include <stdlib.h> #include <string.h> #include <stdarg.h> #include "imagew-internals.h" // Translate a string, using the given flags. IW_IMPL(void) iw_translate(struct iw_context *ctx, unsigned int flags, char *dst, size_t dstlen, const char *src) { int ret; dst[0]='\0'; if(ctx && ctx->translate_fn) { ret = (*ctx->translate_fn)(ctx,flags,dst,dstlen,src); } else { ret = 0; } if(!ret) { // Not translated. Just copy the string. iw_strlcpy(dst,src,dstlen); } } // Formats and translates, and returns the resulting string in buf. // 'ctx' can be NULL, in which case no tranlation will happen. IW_IMPL(void) iw_translatev(struct iw_context *ctx, unsigned int flags, char *dst, size_t dstlen, const char *fmt, va_list ap) { char buf1[IW_MSG_MAX]; char buf2[IW_MSG_MAX]; // If not translating, just format the string directly. if(!ctx || !ctx->translate_fn) { iw_vsnprintf(dst,dstlen,fmt,ap); return; } // String is now in fmt. iw_translate(ctx,IW_TRANSLATEFLAG_FORMAT|flags,buf1,sizeof(buf1),fmt); // String is now in buf1. iw_vsnprintf(buf2,sizeof(buf2),buf1,ap); // String is now in buf2. iw_translate(ctx,IW_TRANSLATEFLAG_POSTFORMAT|flags,dst,dstlen,buf2); // String is now in dst. } // Formats and translates, and returns the resulting string in buf IW_IMPL(void) iw_translatef(struct iw_context *ctx, unsigned int flags, char *dst, size_t dstlen, const char *fmt, ...) { va_list ap; va_start(ap, fmt); iw_translatev(ctx,flags,dst,dstlen,fmt,ap); va_end(ap); } static void iw_warning_internal(struct iw_context *ctx, const char *s) { if(!ctx->warning_fn) return; (*ctx->warning_fn)(ctx,s); } IW_IMPL(void) iw_warning(struct iw_context *ctx, const char *s) { char buf[IW_MSG_MAX]; if(!ctx->warning_fn) return; iw_translate(ctx,IW_TRANSLATEFLAG_WARNINGMSG,buf,sizeof(buf),s); iw_warning_internal(ctx,buf); } IW_IMPL(void) iw_warningv(struct iw_context *ctx, const char *fmt, va_list ap) { char buf[IW_MSG_MAX]; if(!ctx->warning_fn) return; iw_translatev(ctx,IW_TRANSLATEFLAG_WARNINGMSG,buf,sizeof(buf),fmt,ap); iw_warning_internal(ctx,buf); } // Call the caller's warning function, if defined. IW_IMPL(void) iw_warningf(struct iw_context *ctx, const char *fmt, ...) { va_list ap; if(!ctx->warning_fn) return; va_start(ap, fmt); iw_warningv(ctx,fmt,ap); va_end(ap); } static void iw_set_error_internal(struct iw_context *ctx, const char *s) { if(ctx->error_flag) return; // Only record the first error. ctx->error_flag = 1; if(!ctx->error_msg) { ctx->error_msg=iw_malloc_ex(ctx,IW_MALLOCFLAG_NOERRORS,IW_MSG_MAX*sizeof(char)); if(!ctx->error_msg) { return; } } iw_strlcpy(ctx->error_msg,s,IW_MSG_MAX); } IW_IMPL(void) iw_set_error(struct iw_context *ctx, const char *s) { char buf[IW_MSG_MAX]; if(ctx->error_flag) return; // Only record the first error. iw_translate(ctx,IW_TRANSLATEFLAG_ERRORMSG,buf,sizeof(buf),s); iw_set_error_internal(ctx,buf); } IW_IMPL(void) iw_set_errorv(struct iw_context *ctx, const char *fmt, va_list ap) { char buf[IW_MSG_MAX]; if(ctx->error_flag) return; // Only record the first error. iw_translatev(ctx,IW_TRANSLATEFLAG_ERRORMSG,buf,sizeof(buf),fmt,ap); iw_set_error_internal(ctx,buf); } IW_IMPL(void) iw_set_errorf(struct iw_context *ctx, const char *fmt, ...) { va_list ap; va_start(ap, fmt); iw_set_errorv(ctx,fmt,ap); va_end(ap); } IW_IMPL(const char*) iw_get_errormsg(struct iw_context *ctx, char *buf, int buflen) { if(ctx->error_msg) { iw_strlcpy(buf,ctx->error_msg,buflen); } else { iw_translate(ctx,IW_TRANSLATEFLAG_ERRORMSG,buf,buflen,"Error message not available"); } return buf; } IW_IMPL(int) iw_get_errorflag(struct iw_context *ctx) { return ctx->error_flag; } // Given a color type, returns the number of channels. IW_IMPL(int) iw_imgtype_num_channels(int t) { switch(t) { case IW_IMGTYPE_RGBA: return 4; case IW_IMGTYPE_RGB: return 3; case IW_IMGTYPE_GRAYA: return 2; } return 1; } IW_IMPL(size_t) iw_calc_bytesperrow(int num_pixels, int bits_per_pixel) { return (size_t)(((num_pixels*bits_per_pixel)+7)/8); } IW_IMPL(int) iw_check_image_dimensions(struct iw_context *ctx, int w, int h) { if(w>ctx->max_width || h>ctx->max_height) { iw_set_errorf(ctx,"Image dimensions too large (%d\xc3\x97%d)",w,h); return 0; } if(w<1 || h<1) { iw_set_errorf(ctx,"Invalid image dimensions (%d\xc3\x97%d)",w,h); return 0; } return 1; } IW_IMPL(int) iw_is_valid_density(double density_x, double density_y, int density_code) { if(density_x<0.0001 || density_y<0.0001) return 0; if(density_x>10000000.0 || density_y>10000000.0) return 0; if(density_x/10.0>density_y) return 0; if(density_y/10.0>density_x) return 0; if(density_code!=IW_DENSITY_UNITS_UNKNOWN && density_code!=IW_DENSITY_UNITS_PER_METER) return 0; return 1; } static void default_resize_settings(struct iw_resize_settings *rs) { int i; rs->family = IW_RESIZETYPE_AUTO; rs->edge_policy = IW_EDGE_POLICY_STANDARD; rs->blur_factor = 1.0; rs->translate = 0.0; for(i=0;i<3;i++) { rs->channel_offset[i] = 0.0; } } IW_IMPL(struct iw_context*) iw_create_context(struct iw_init_params *params) { struct iw_context *ctx; if(params && params->mallocfn) { ctx = (*params->mallocfn)(params->userdata,IW_MALLOCFLAG_ZEROMEM,sizeof(struct iw_context)); } else { ctx = iwpvt_default_malloc(NULL,IW_MALLOCFLAG_ZEROMEM,sizeof(struct iw_context)); } if(!ctx) return NULL; if(params) { ctx->userdata = params->userdata; ctx->caller_api_version = params->api_version; } if(params && params->mallocfn) { ctx->mallocfn = params->mallocfn; ctx->freefn = params->freefn; } else { ctx->mallocfn = iwpvt_default_malloc; ctx->freefn = iwpvt_default_free; } ctx->max_malloc = IW_DEFAULT_MAX_MALLOC; ctx->max_width = ctx->max_height = IW_DEFAULT_MAX_DIMENSION; default_resize_settings(&ctx->resize_settings[IW_DIMENSION_H]); default_resize_settings(&ctx->resize_settings[IW_DIMENSION_V]); ctx->input_w = -1; ctx->input_h = -1; iw_make_srgb_csdescr_2(&ctx->img1cs); iw_make_srgb_csdescr_2(&ctx->img2cs); ctx->to_grayscale=0; ctx->grayscale_formula = IW_GSF_STANDARD; ctx->req.include_screen = 1; ctx->opt_grayscale = 1; ctx->opt_palette = 1; ctx->opt_16_to_8 = 1; ctx->opt_strip_alpha = 1; ctx->opt_binary_trns = 1; return ctx; } IW_IMPL(void) iw_destroy_context(struct iw_context *ctx) { int i; if(!ctx) return; if(ctx->req.options) { for(i=0; i<=ctx->req.options_count; i++) { iw_free(ctx, ctx->req.options[i].name); iw_free(ctx, ctx->req.options[i].val); } iw_free(ctx, ctx->req.options); } if(ctx->img1.pixels) iw_free(ctx,ctx->img1.pixels); if(ctx->img2.pixels) iw_free(ctx,ctx->img2.pixels); if(ctx->error_msg) iw_free(ctx,ctx->error_msg); if(ctx->optctx.tmp_pixels) iw_free(ctx,ctx->optctx.tmp_pixels); if(ctx->optctx.palette) iw_free(ctx,ctx->optctx.palette); if(ctx->input_color_corr_table) iw_free(ctx,ctx->input_color_corr_table); if(ctx->output_rev_color_corr_table) iw_free(ctx,ctx->output_rev_color_corr_table); if(ctx->nearest_color_table) iw_free(ctx,ctx->nearest_color_table); if(ctx->prng) iwpvt_prng_destroy(ctx,ctx->prng); iw_free(ctx,ctx); } IW_IMPL(void) iw_get_output_image(struct iw_context *ctx, struct iw_image *img) { int k; iw_zeromem(img,sizeof(struct iw_image)); img->width = ctx->optctx.width; img->height = ctx->optctx.height; img->imgtype = ctx->optctx.imgtype; img->sampletype = ctx->img2.sampletype; img->bit_depth = ctx->optctx.bit_depth; img->pixels = (iw_byte*)ctx->optctx.pixelsptr; img->bpr = ctx->optctx.bpr; img->density_code = ctx->img2.density_code; img->density_x = ctx->img2.density_x; img->density_y = ctx->img2.density_y; img->rendering_intent = ctx->img2.rendering_intent; img->has_bkgdlabel = ctx->optctx.has_bkgdlabel; for(k=0;k<4;k++) { if(ctx->optctx.bit_depth==8) { img->bkgdlabel.c[k] = ((double)ctx->optctx.bkgdlabel[k])/255.0; } else { img->bkgdlabel.c[k] = ((double)ctx->optctx.bkgdlabel[k])/65535.0; } } img->has_colorkey_trns = ctx->optctx.has_colorkey_trns; img->colorkey[0] = ctx->optctx.colorkey[0]; img->colorkey[1] = ctx->optctx.colorkey[1]; img->colorkey[2] = ctx->optctx.colorkey[2]; if(ctx->reduced_output_maxcolor_flag) { img->reduced_maxcolors = 1; if(IW_IMGTYPE_IS_GRAY(img->imgtype)) { img->maxcolorcode[IW_CHANNELTYPE_GRAY] = ctx->img2_ci[0].maxcolorcode_int; if(IW_IMGTYPE_HAS_ALPHA(img->imgtype)) { img->maxcolorcode[IW_CHANNELTYPE_ALPHA] = ctx->img2_ci[1].maxcolorcode_int; } } else { img->maxcolorcode[IW_CHANNELTYPE_RED] = ctx->img2_ci[0].maxcolorcode_int; img->maxcolorcode[IW_CHANNELTYPE_GREEN] = ctx->img2_ci[1].maxcolorcode_int; img->maxcolorcode[IW_CHANNELTYPE_BLUE] = ctx->img2_ci[2].maxcolorcode_int; if(IW_IMGTYPE_HAS_ALPHA(img->imgtype)) { img->maxcolorcode[IW_CHANNELTYPE_ALPHA] = ctx->img2_ci[3].maxcolorcode_int; } } } } IW_IMPL(void) iw_get_output_colorspace(struct iw_context *ctx, struct iw_csdescr *csdescr) { *csdescr = ctx->img2cs; // struct copy } IW_IMPL(const struct iw_palette*) iw_get_output_palette(struct iw_context *ctx) { return ctx->optctx.palette; } IW_IMPL(void) iw_set_output_canvas_size(struct iw_context *ctx, int w, int h) { ctx->canvas_width = w; ctx->canvas_height = h; } IW_IMPL(void) iw_set_output_image_size(struct iw_context *ctx, double w, double h) { ctx->req.out_true_width = w; if(ctx->req.out_true_width<0.01) ctx->req.out_true_width=0.01; ctx->req.out_true_height = h; if(ctx->req.out_true_height<0.01) ctx->req.out_true_height=0.01; ctx->req.out_true_valid = 1; } IW_IMPL(void) iw_set_input_crop(struct iw_context *ctx, int x, int y, int w, int h) { ctx->input_start_x = x; ctx->input_start_y = y; ctx->input_w = w; ctx->input_h = h; } IW_IMPL(void) iw_set_output_profile(struct iw_context *ctx, unsigned int n) { ctx->output_profile = n; } IW_IMPL(void) iw_set_output_depth(struct iw_context *ctx, int bps) { ctx->req.output_depth = bps; } IW_IMPL(void) iw_set_output_max_color_code(struct iw_context *ctx, int channeltype, int n) { if(channeltype>=0 && channeltype<IW_NUM_CHANNELTYPES) { ctx->req.output_maxcolorcode[channeltype] = n; } } IW_IMPL(void) iw_set_dither_type(struct iw_context *ctx, int channeltype, int f, int s) { if(channeltype>=0 && channeltype<IW_NUM_CHANNELTYPES) { ctx->ditherfamily_by_channeltype[channeltype] = f; ctx->dithersubtype_by_channeltype[channeltype] = s; } switch(channeltype) { case IW_CHANNELTYPE_ALL: ctx->ditherfamily_by_channeltype[IW_CHANNELTYPE_ALPHA] = f; ctx->dithersubtype_by_channeltype[IW_CHANNELTYPE_ALPHA] = s; // fall thru case IW_CHANNELTYPE_NONALPHA: ctx->ditherfamily_by_channeltype[IW_CHANNELTYPE_RED] = f; ctx->dithersubtype_by_channeltype[IW_CHANNELTYPE_RED] = s; ctx->ditherfamily_by_channeltype[IW_CHANNELTYPE_GREEN] = f; ctx->dithersubtype_by_channeltype[IW_CHANNELTYPE_GREEN] = s; ctx->ditherfamily_by_channeltype[IW_CHANNELTYPE_BLUE] = f; ctx->dithersubtype_by_channeltype[IW_CHANNELTYPE_BLUE] = s; ctx->ditherfamily_by_channeltype[IW_CHANNELTYPE_GRAY] = f; ctx->dithersubtype_by_channeltype[IW_CHANNELTYPE_GRAY] = s; break; } } IW_IMPL(void) iw_set_color_count(struct iw_context *ctx, int channeltype, int c) { if(channeltype>=0 && channeltype<IW_NUM_CHANNELTYPES) { ctx->req.color_count[channeltype] = c; } switch(channeltype) { case IW_CHANNELTYPE_ALL: ctx->req.color_count[IW_CHANNELTYPE_ALPHA] = c; // fall thru case IW_CHANNELTYPE_NONALPHA: ctx->req.color_count[IW_CHANNELTYPE_RED] = c; ctx->req.color_count[IW_CHANNELTYPE_GREEN] = c; ctx->req.color_count[IW_CHANNELTYPE_BLUE] = c; ctx->req.color_count[IW_CHANNELTYPE_GRAY] = c; break; } } IW_IMPL(void) iw_set_channel_offset(struct iw_context *ctx, int channeltype, int dimension, double offs) { if(channeltype<0 || channeltype>2) return; if(dimension<0 || dimension>1) dimension=0; ctx->resize_settings[dimension].channel_offset[channeltype] = offs; } IW_IMPL(void) iw_set_input_max_color_code(struct iw_context *ctx, int input_channel, int c) { if(input_channel>=0 && input_channel<IW_CI_COUNT) { ctx->img1_ci[input_channel].maxcolorcode_int = c; } } IW_IMPL(void) iw_set_input_bkgd_label_2(struct iw_context *ctx, const struct iw_color *clr) { ctx->img1_bkgd_label_set = 1; ctx->img1_bkgd_label_inputcs = *clr; } IW_IMPL(void) iw_set_input_bkgd_label(struct iw_context *ctx, double r, double g, double b) { struct iw_color clr; clr.c[0] = r; clr.c[1] = g; clr.c[2] = b; clr.c[3] = 1.0; iw_set_input_bkgd_label_2(ctx, &clr); } IW_IMPL(void) iw_set_output_bkgd_label_2(struct iw_context *ctx, const struct iw_color *clr) { ctx->req.output_bkgd_label_valid = 1; ctx->req.output_bkgd_label = *clr; } IW_IMPL(void) iw_set_output_bkgd_label(struct iw_context *ctx, double r, double g, double b) { struct iw_color clr; clr.c[0] = r; clr.c[1] = g; clr.c[2] = b; clr.c[3] = 1.0; iw_set_output_bkgd_label_2(ctx, &clr); } IW_IMPL(int) iw_get_input_density(struct iw_context *ctx, double *px, double *py, int *pcode) { *px = 1.0; *py = 1.0; *pcode = IW_DENSITY_UNKNOWN; if(ctx->img1.density_code==IW_DENSITY_UNKNOWN) { return 0; } if(!iw_is_valid_density(ctx->img1.density_x, ctx->img1.density_y, ctx->img1.density_code)) { return 0; } *px = ctx->img1.density_x; *py = ctx->img1.density_y; *pcode = ctx->img1.density_code; return 1; } IW_IMPL(void) iw_set_output_density(struct iw_context *ctx, double x, double y, int code) { ctx->img2.density_code = code; ctx->img2.density_x = x; ctx->img2.density_y = y; } // Detect a "gamma" colorspace that is actually linear. static void optimize_csdescr(struct iw_csdescr *cs) { if(cs->cstype!=IW_CSTYPE_GAMMA) return; if(cs->gamma>=0.999995 && cs->gamma<=1.000005) { cs->cstype = IW_CSTYPE_LINEAR; } } IW_IMPL(void) iw_make_linear_csdescr(struct iw_csdescr *cs) { cs->cstype = IW_CSTYPE_LINEAR; cs->gamma = 0.0; cs->srgb_intent = 0; } // This function is deprecated, and should not be used. IW_IMPL(void) iw_make_srgb_csdescr(struct iw_csdescr *cs, int srgb_intent) { cs->cstype = IW_CSTYPE_SRGB; cs->gamma = 0.0; cs->srgb_intent = srgb_intent; } IW_IMPL(void) iw_make_srgb_csdescr_2(struct iw_csdescr *cs) { cs->cstype = IW_CSTYPE_SRGB; cs->gamma = 0.0; } IW_IMPL(void) iw_make_rec709_csdescr(struct iw_csdescr *cs) { cs->cstype = IW_CSTYPE_REC709; cs->gamma = 0.0; } IW_IMPL(void) iw_make_gamma_csdescr(struct iw_csdescr *cs, double gamma) { cs->cstype = IW_CSTYPE_GAMMA; cs->gamma = gamma; if(cs->gamma<0.1) cs->gamma=0.1; if(cs->gamma>10.0) cs->gamma=10.0; cs->srgb_intent = 0; optimize_csdescr(cs); } IW_IMPL(void) iw_set_output_colorspace(struct iw_context *ctx, const struct iw_csdescr *csdescr) { ctx->req.output_cs = *csdescr; // struct copy optimize_csdescr(&ctx->req.output_cs); ctx->req.output_cs_valid = 1; } IW_IMPL(void) iw_set_input_colorspace(struct iw_context *ctx, const struct iw_csdescr *csdescr) { ctx->img1cs = *csdescr; // struct copy optimize_csdescr(&ctx->img1cs); } IW_IMPL(void) iw_set_apply_bkgd_2(struct iw_context *ctx, const struct iw_color *clr) { ctx->req.bkgd_valid=1; ctx->req.bkgd = *clr; } IW_IMPL(void) iw_set_apply_bkgd(struct iw_context *ctx, double r, double g, double b) { struct iw_color clr; clr.c[IW_CHANNELTYPE_RED]=r; clr.c[IW_CHANNELTYPE_GREEN]=g; clr.c[IW_CHANNELTYPE_BLUE]=b; clr.c[IW_CHANNELTYPE_ALPHA]=1.0; iw_set_apply_bkgd_2(ctx, &clr); } IW_IMPL(void) iw_set_bkgd_checkerboard_2(struct iw_context *ctx, int checkersize, const struct iw_color *clr) { ctx->req.bkgd_checkerboard=1; ctx->bkgd_check_size=checkersize; ctx->req.bkgd2 = *clr; } IW_IMPL(void) iw_set_bkgd_checkerboard(struct iw_context *ctx, int checkersize, double r2, double g2, double b2) { struct iw_color clr; clr.c[IW_CHANNELTYPE_RED]=r2; clr.c[IW_CHANNELTYPE_GREEN]=g2; clr.c[IW_CHANNELTYPE_BLUE]=b2; clr.c[IW_CHANNELTYPE_ALPHA]=1.0; iw_set_bkgd_checkerboard_2(ctx, checkersize, &clr); } IW_IMPL(void) iw_set_bkgd_checkerboard_origin(struct iw_context *ctx, int x, int y) { ctx->bkgd_check_origin[IW_DIMENSION_H] = x; ctx->bkgd_check_origin[IW_DIMENSION_V] = y; } IW_IMPL(void) iw_set_max_malloc(struct iw_context *ctx, size_t n) { ctx->max_malloc = n; } IW_IMPL(void) iw_set_random_seed(struct iw_context *ctx, int randomize, int rand_seed) { ctx->randomize = randomize; ctx->random_seed = rand_seed; } IW_IMPL(void) iw_set_userdata(struct iw_context *ctx, void *userdata) { ctx->userdata = userdata; } IW_IMPL(void*) iw_get_userdata(struct iw_context *ctx) { return ctx->userdata; } IW_IMPL(void) iw_set_translate_fn(struct iw_context *ctx, iw_translatefn_type xlatefn) { ctx->translate_fn = xlatefn; } IW_IMPL(void) iw_set_warning_fn(struct iw_context *ctx, iw_warningfn_type warnfn) { ctx->warning_fn = warnfn; } IW_IMPL(void) iw_set_input_image(struct iw_context *ctx, const struct iw_image *img) { ctx->img1 = *img; // struct copy } IW_IMPL(void) iw_set_resize_alg(struct iw_context *ctx, int dimension, int family, double blur, double param1, double param2) { struct iw_resize_settings *rs; if(dimension<0 || dimension>1) dimension=0; rs=&ctx->resize_settings[dimension]; rs->family = family; rs->blur_factor = blur; rs->param1 = param1; rs->param2 = param2; } IW_IMPL(void) iw_reorient_image(struct iw_context *ctx, unsigned int x) { static const unsigned int transpose_tbl[8] = { 4,6,5,7,0,2,1,3 }; int tmpi; double tmpd; x = x & 0x07; // If needed, perform a 'transpose' of the current transform. if(x&0x04) { ctx->img1.orient_transform = transpose_tbl[ctx->img1.orient_transform]; // We swapped the width and height, so we need to fix up some things. tmpi = ctx->img1.width; ctx->img1.width = ctx->img1.height; ctx->img1.height = tmpi; tmpd = ctx->img1.density_x; ctx->img1.density_x = ctx->img1.density_y; ctx->img1.density_y = tmpd; } // Do horizontal and vertical mirroring. ctx->img1.orient_transform ^= (x&0x03); } IW_IMPL(int) iw_get_sample_size(void) { return (int)sizeof(iw_float32); } IW_IMPL(int) iw_get_version_int(void) { return IW_VERSION_INT; } IW_IMPL(char*) iw_get_version_string(struct iw_context *ctx, char *s, int s_len) { int ver; ver = iw_get_version_int(); iw_snprintf(s,s_len,"%d.%d.%d", (ver&0xff0000)>>16, (ver&0xff00)>>8, (ver&0xff) ); return s; } IW_IMPL(char*) iw_get_copyright_string(struct iw_context *ctx, char *dst, int dstlen) { iw_translatef(ctx,0,dst,dstlen,"Copyright \xc2\xa9 %s %s",IW_COPYRIGHT_YEAR,"Jason Summers"); return dst; } IW_IMPL(void) iw_set_zlib_module(struct iw_context *ctx, struct iw_zlib_module *z) { ctx->zlib_module = z; } IW_IMPL(struct iw_zlib_module*) iw_get_zlib_module(struct iw_context *ctx) { return ctx->zlib_module; } IW_IMPL(void) iw_set_allow_opt(struct iw_context *ctx, int opt, int n) { iw_byte v; v = n?1:0; switch(opt) { case IW_OPT_GRAYSCALE: ctx->opt_grayscale = v; break; case IW_OPT_PALETTE: ctx->opt_palette = v; break; case IW_OPT_16_TO_8: ctx->opt_16_to_8 = v; break; case IW_OPT_STRIP_ALPHA: ctx->opt_strip_alpha = v; break; case IW_OPT_BINARY_TRNS: ctx->opt_binary_trns = v; break; } } IW_IMPL(void) iw_set_grayscale_weights(struct iw_context *ctx, double r, double g, double b) { double tot; //ctx->grayscale_formula = IW_GSF_WEIGHTED; // Normalize, so the weights add up to 1. tot = r+g+b; if(tot==0.0) tot=1.0; ctx->grayscale_weight[0] = r/tot; ctx->grayscale_weight[1] = g/tot; ctx->grayscale_weight[2] = b/tot; } IW_IMPL(unsigned int) iw_color_get_int_sample(struct iw_color *clr, int channel, unsigned int maxcolorcode) { int n; n = (int)(0.5+(clr->c[channel] * (double)maxcolorcode)); if(n<0) n=0; else if(n>(int)maxcolorcode) n=(int)maxcolorcode; return (unsigned int)n; } IW_IMPL(void) iw_set_value(struct iw_context *ctx, int code, int n) { switch(code) { case IW_VAL_API_VERSION: ctx->caller_api_version = n; break; case IW_VAL_CVT_TO_GRAYSCALE: ctx->to_grayscale = n; break; case IW_VAL_DISABLE_GAMMA: ctx->no_gamma = n; break; case IW_VAL_NO_CSLABEL: ctx->req.suppress_output_cslabel = n; break; case IW_VAL_INT_CLAMP: ctx->intclamp = n; break; case IW_VAL_EDGE_POLICY_X: ctx->resize_settings[IW_DIMENSION_H].edge_policy = n; break; case IW_VAL_EDGE_POLICY_Y: ctx->resize_settings[IW_DIMENSION_V].edge_policy = n; break; case IW_VAL_PREF_UNITS: ctx->pref_units = n; break; case IW_VAL_GRAYSCALE_FORMULA: ctx->grayscale_formula = n; break; case IW_VAL_INPUT_NATIVE_GRAYSCALE: ctx->img1.native_grayscale = n; break; case IW_VAL_COMPRESSION: ctx->req.compression = n; break; case IW_VAL_PAGE_TO_READ: ctx->req.page_to_read = n; break; case IW_VAL_INCLUDE_SCREEN: ctx->req.include_screen = n; break; case IW_VAL_JPEG_QUALITY: // For backward compatibility only. iw_set_option(ctx, "jpeg:quality", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_JPEG_SAMP_FACTOR_H: // For backward compatibility only. iw_set_option(ctx, "jpeg:sampling-x", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_JPEG_SAMP_FACTOR_V: // For backward compatibility only. iw_set_option(ctx, "jpeg:sampling-y", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_JPEG_ARITH_CODING: // For backward compatibility only. iw_set_option(ctx, "jpeg:arith", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_DEFLATE_CMPR_LEVEL: // For backward compatibility only. iw_set_option(ctx, "deflate:cmprlevel", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_OUTPUT_INTERLACED: ctx->req.interlaced = n; break; case IW_VAL_USE_BKGD_LABEL: ctx->req.use_bkgd_label_from_file = n; break; case IW_VAL_BMP_NO_FILEHEADER: ctx->req.bmp_no_fileheader = n; break; case IW_VAL_BMP_VERSION: // For backward compatibility only. iw_set_option(ctx, "bmp:version", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_MAX_WIDTH: ctx->max_width = n; break; case IW_VAL_MAX_HEIGHT: ctx->max_height = n; break; case IW_VAL_NO_BKGD_LABEL: ctx->req.suppress_output_bkgd_label = n; break; case IW_VAL_INTENT: ctx->req.output_rendering_intent = n; break; case IW_VAL_OUTPUT_SAMPLE_TYPE: ctx->req.output_sample_type = n; break; case IW_VAL_OUTPUT_COLOR_TYPE: // For backward compatibility only. if(n==IW_COLORTYPE_RGB) { iw_set_option(ctx, "deflate:colortype", "rgb"); } break; case IW_VAL_OUTPUT_FORMAT: ctx->req.output_format = n; break; case IW_VAL_NEGATE_TARGET: ctx->req.negate_target = n; break; } } IW_IMPL(int) iw_get_value(struct iw_context *ctx, int code) { int ret=0; switch(code) { case IW_VAL_API_VERSION: ret = ctx->caller_api_version; break; case IW_VAL_CVT_TO_GRAYSCALE: ret = ctx->to_grayscale; break; case IW_VAL_DISABLE_GAMMA: ret = ctx->no_gamma; break; case IW_VAL_NO_CSLABEL: ret = ctx->req.suppress_output_cslabel; break; case IW_VAL_INT_CLAMP: ret = ctx->intclamp; break; case IW_VAL_EDGE_POLICY_X: ret = ctx->resize_settings[IW_DIMENSION_H].edge_policy; break; case IW_VAL_EDGE_POLICY_Y: ret = ctx->resize_settings[IW_DIMENSION_V].edge_policy; break; case IW_VAL_PREF_UNITS: ret = ctx->pref_units; break; case IW_VAL_GRAYSCALE_FORMULA: ret = ctx->grayscale_formula; break; case IW_VAL_INPUT_NATIVE_GRAYSCALE: ret = ctx->img1.native_grayscale; break; case IW_VAL_INPUT_WIDTH: if(ctx->img1.width<1) ret=1; else ret = ctx->img1.width; break; case IW_VAL_INPUT_HEIGHT: if(ctx->img1.height<1) ret=1; else ret = ctx->img1.height; break; case IW_VAL_INPUT_IMAGE_TYPE: ret = ctx->img1.imgtype; break; case IW_VAL_INPUT_DEPTH: ret = ctx->img1.bit_depth; break; case IW_VAL_COMPRESSION: ret = ctx->req.compression; break; case IW_VAL_PAGE_TO_READ: ret = ctx->req.page_to_read; break; case IW_VAL_INCLUDE_SCREEN: ret = ctx->req.include_screen; break; case IW_VAL_OUTPUT_PALETTE_GRAYSCALE: ret = ctx->optctx.palette_is_grayscale; break; case IW_VAL_OUTPUT_INTERLACED: ret = ctx->req.interlaced; break; case IW_VAL_USE_BKGD_LABEL: ret = ctx->req.use_bkgd_label_from_file; break; case IW_VAL_BMP_NO_FILEHEADER: ret = ctx->req.bmp_no_fileheader; break; case IW_VAL_MAX_WIDTH: ret = ctx->max_width; break; case IW_VAL_MAX_HEIGHT: ret = ctx->max_height; break; case IW_VAL_PRECISION: ret = 32; break; case IW_VAL_NO_BKGD_LABEL: ret = ctx->req.suppress_output_bkgd_label; break; case IW_VAL_INTENT: ret = ctx->req.output_rendering_intent; break; case IW_VAL_OUTPUT_SAMPLE_TYPE: ret = ctx->req.output_sample_type; break; case IW_VAL_OUTPUT_FORMAT: ret = ctx->req.output_format; break; case IW_VAL_NEGATE_TARGET: ret = ctx->req.negate_target; break; } return ret; } IW_IMPL(void) iw_set_value_dbl(struct iw_context *ctx, int code, double n) { switch(code) { case IW_VAL_WEBP_QUALITY: // For backward compatibility only. iw_set_option(ctx, "webp:quality", iwpvt_strdup_dbl(ctx, n)); break; case IW_VAL_TRANSLATE_X: ctx->resize_settings[IW_DIMENSION_H].translate = n; break; case IW_VAL_TRANSLATE_Y: ctx->resize_settings[IW_DIMENSION_V].translate = n; break; } } IW_IMPL(double) iw_get_value_dbl(struct iw_context *ctx, int code) { double ret = 0.0; switch(code) { case IW_VAL_TRANSLATE_X: ret = ctx->resize_settings[IW_DIMENSION_H].translate; break; case IW_VAL_TRANSLATE_Y: ret = ctx->resize_settings[IW_DIMENSION_V].translate; break; } return ret; } IW_IMPL(void) iw_set_option(struct iw_context *ctx, const char *name, const char *val) { #define IW_MAX_OPTIONS 32 int i; if(val==NULL || val[0]=='\0') { // An empty value can be used to mean "turn on this option". // To make that easier, set such values to "1". val = "1"; } // Allocate req.options if that hasn't been done yet. if(!ctx->req.options) { ctx->req.options = iw_mallocz(ctx, IW_MAX_OPTIONS*sizeof(struct iw_option_struct)); if(!ctx->req.options) return; ctx->req.options_numalloc = IW_MAX_OPTIONS; ctx->req.options_count = 0; } // If option already exists, replace it. for(i=0; i<ctx->req.options_count; i++) { if(ctx->req.options[i].name && !strcmp(ctx->req.options[i].name, name)) { iw_free(ctx, ctx->req.options[i].val); ctx->req.options[i].val = iw_strdup(ctx, val); return; } } // Add the new option. if(ctx->req.options_count>=IW_MAX_OPTIONS) return; ctx->req.options[ctx->req.options_count].name = iw_strdup(ctx, name); ctx->req.options[ctx->req.options_count].val = iw_strdup(ctx, val); ctx->req.options_count++; } // Return the value of the first option with the given name. // Return NULL if not found. IW_IMPL(const char*) iw_get_option(struct iw_context *ctx, const char *name) { int i; for(i=0; i<ctx->req.options_count; i++) { if(ctx->req.options[i].name && !strcmp(ctx->req.options[i].name, name)) { return ctx->req.options[i].val; } } return NULL; }
./CrossVul/dataset_final_sorted/CWE-369/c/good_3367_0
crossvul-cpp_data_bad_225_0
/* pngrutil.c - utilities to read a PNG file * * Last changed in libpng 1.6.35 [(PENDING RELEASE)] * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * This file contains routines that are only called from within * libpng itself during the course of reading an image. */ #include "pngpriv.h" #ifdef PNG_READ_SUPPORTED png_uint_32 PNGAPI png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf) { png_uint_32 uval = png_get_uint_32(buf); if (uval > PNG_UINT_31_MAX) png_error(png_ptr, "PNG unsigned integer out of range"); return (uval); } #if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_READ_cHRM_SUPPORTED) /* The following is a variation on the above for use with the fixed * point values used for gAMA and cHRM. Instead of png_error it * issues a warning and returns (-1) - an invalid value because both * gAMA and cHRM use *unsigned* integers for fixed point values. */ #define PNG_FIXED_ERROR (-1) static png_fixed_point /* PRIVATE */ png_get_fixed_point(png_structrp png_ptr, png_const_bytep buf) { png_uint_32 uval = png_get_uint_32(buf); if (uval <= PNG_UINT_31_MAX) return (png_fixed_point)uval; /* known to be in range */ /* The caller can turn off the warning by passing NULL. */ if (png_ptr != NULL) png_warning(png_ptr, "PNG fixed point integer out of range"); return PNG_FIXED_ERROR; } #endif #ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED /* NOTE: the read macros will obscure these definitions, so that if * PNG_USE_READ_MACROS is set the library will not use them internally, * but the APIs will still be available externally. * * The parentheses around "PNGAPI function_name" in the following three * functions are necessary because they allow the macros to co-exist with * these (unused but exported) functions. */ /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */ png_uint_32 (PNGAPI png_get_uint_32)(png_const_bytep buf) { png_uint_32 uval = ((png_uint_32)(*(buf )) << 24) + ((png_uint_32)(*(buf + 1)) << 16) + ((png_uint_32)(*(buf + 2)) << 8) + ((png_uint_32)(*(buf + 3)) ) ; return uval; } /* Grab a signed 32-bit integer from a buffer in big-endian format. The * data is stored in the PNG file in two's complement format and there * is no guarantee that a 'png_int_32' is exactly 32 bits, therefore * the following code does a two's complement to native conversion. */ png_int_32 (PNGAPI png_get_int_32)(png_const_bytep buf) { png_uint_32 uval = png_get_uint_32(buf); if ((uval & 0x80000000) == 0) /* non-negative */ return (png_int_32)uval; uval = (uval ^ 0xffffffff) + 1; /* 2's complement: -x = ~x+1 */ if ((uval & 0x80000000) == 0) /* no overflow */ return -(png_int_32)uval; /* The following has to be safe; this function only gets called on PNG data * and if we get here that data is invalid. 0 is the most safe value and * if not then an attacker would surely just generate a PNG with 0 instead. */ return 0; } /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */ png_uint_16 (PNGAPI png_get_uint_16)(png_const_bytep buf) { /* ANSI-C requires an int value to accommodate at least 16 bits so this * works and allows the compiler not to worry about possible narrowing * on 32-bit systems. (Pre-ANSI systems did not make integers smaller * than 16 bits either.) */ unsigned int val = ((unsigned int)(*buf) << 8) + ((unsigned int)(*(buf + 1))); return (png_uint_16)val; } #endif /* READ_INT_FUNCTIONS */ /* Read and check the PNG file signature */ void /* PRIVATE */ png_read_sig(png_structrp png_ptr, png_inforp info_ptr) { size_t num_checked, num_to_check; /* Exit if the user application does not expect a signature. */ if (png_ptr->sig_bytes >= 8) return; num_checked = png_ptr->sig_bytes; num_to_check = 8 - num_checked; #ifdef PNG_IO_STATE_SUPPORTED png_ptr->io_state = PNG_IO_READING | PNG_IO_SIGNATURE; #endif /* The signature must be serialized in a single I/O call. */ png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check); png_ptr->sig_bytes = 8; if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check) != 0) { if (num_checked < 4 && png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4)) png_error(png_ptr, "Not a PNG file"); else png_error(png_ptr, "PNG file corrupted by ASCII conversion"); } if (num_checked < 3) png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE; } /* Read the chunk header (length + type name). * Put the type name into png_ptr->chunk_name, and return the length. */ png_uint_32 /* PRIVATE */ png_read_chunk_header(png_structrp png_ptr) { png_byte buf[8]; png_uint_32 length; #ifdef PNG_IO_STATE_SUPPORTED png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_HDR; #endif /* Read the length and the chunk name. * This must be performed in a single I/O call. */ png_read_data(png_ptr, buf, 8); length = png_get_uint_31(png_ptr, buf); /* Put the chunk name into png_ptr->chunk_name. */ png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(buf+4); png_debug2(0, "Reading %lx chunk, length = %lu", (unsigned long)png_ptr->chunk_name, (unsigned long)length); /* Reset the crc and run it over the chunk name. */ png_reset_crc(png_ptr); png_calculate_crc(png_ptr, buf + 4, 4); /* Check to see if chunk name is valid. */ png_check_chunk_name(png_ptr, png_ptr->chunk_name); /* Check for too-large chunk length */ png_check_chunk_length(png_ptr, length); #ifdef PNG_IO_STATE_SUPPORTED png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA; #endif return length; } /* Read data, and (optionally) run it through the CRC. */ void /* PRIVATE */ png_crc_read(png_structrp png_ptr, png_bytep buf, png_uint_32 length) { if (png_ptr == NULL) return; png_read_data(png_ptr, buf, length); png_calculate_crc(png_ptr, buf, length); } /* Optionally skip data and then check the CRC. Depending on whether we * are reading an ancillary or critical chunk, and how the program has set * things up, we may calculate the CRC on the data and print a message. * Returns '1' if there was a CRC error, '0' otherwise. */ int /* PRIVATE */ png_crc_finish(png_structrp png_ptr, png_uint_32 skip) { /* The size of the local buffer for inflate is a good guess as to a * reasonable size to use for buffering reads from the application. */ while (skip > 0) { png_uint_32 len; png_byte tmpbuf[PNG_INFLATE_BUF_SIZE]; len = (sizeof tmpbuf); if (len > skip) len = skip; skip -= len; png_crc_read(png_ptr, tmpbuf, len); } if (png_crc_error(png_ptr) != 0) { if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0 ? (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0 : (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE) != 0) { png_chunk_warning(png_ptr, "CRC error"); } else png_chunk_error(png_ptr, "CRC error"); return (1); } return (0); } /* Compare the CRC stored in the PNG file with that calculated by libpng from * the data it has read thus far. */ int /* PRIVATE */ png_crc_error(png_structrp png_ptr) { png_byte crc_bytes[4]; png_uint_32 crc; int need_crc = 1; if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0) { if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) == (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN)) need_crc = 0; } else /* critical */ { if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0) need_crc = 0; } #ifdef PNG_IO_STATE_SUPPORTED png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_CRC; #endif /* The chunk CRC must be serialized in a single I/O call. */ png_read_data(png_ptr, crc_bytes, 4); if (need_crc != 0) { crc = png_get_uint_32(crc_bytes); return ((int)(crc != png_ptr->crc)); } else return (0); } #if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\ defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\ defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\ defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_SEQUENTIAL_READ_SUPPORTED) /* Manage the read buffer; this simply reallocates the buffer if it is not small * enough (or if it is not allocated). The routine returns a pointer to the * buffer; if an error occurs and 'warn' is set the routine returns NULL, else * it will call png_error (via png_malloc) on failure. (warn == 2 means * 'silent'). */ static png_bytep png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn) { png_bytep buffer = png_ptr->read_buffer; if (buffer != NULL && new_size > png_ptr->read_buffer_size) { png_ptr->read_buffer = NULL; png_ptr->read_buffer = NULL; png_ptr->read_buffer_size = 0; png_free(png_ptr, buffer); buffer = NULL; } if (buffer == NULL) { buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size)); if (buffer != NULL) { memset(buffer, 0, new_size); /* just in case */ png_ptr->read_buffer = buffer; png_ptr->read_buffer_size = new_size; } else if (warn < 2) /* else silent */ { if (warn != 0) png_chunk_warning(png_ptr, "insufficient memory to read chunk"); else png_chunk_error(png_ptr, "insufficient memory to read chunk"); } } return buffer; } #endif /* READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|SEQUENTIAL_READ */ /* png_inflate_claim: claim the zstream for some nefarious purpose that involves * decompression. Returns Z_OK on success, else a zlib error code. It checks * the owner but, in final release builds, just issues a warning if some other * chunk apparently owns the stream. Prior to release it does a png_error. */ static int png_inflate_claim(png_structrp png_ptr, png_uint_32 owner) { if (png_ptr->zowner != 0) { char msg[64]; PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner); /* So the message that results is "<chunk> using zstream"; this is an * internal error, but is very useful for debugging. i18n requirements * are minimal. */ (void)png_safecat(msg, (sizeof msg), 4, " using zstream"); #if PNG_RELEASE_BUILD png_chunk_warning(png_ptr, msg); png_ptr->zowner = 0; #else png_chunk_error(png_ptr, msg); #endif } /* Implementation note: unlike 'png_deflate_claim' this internal function * does not take the size of the data as an argument. Some efficiency could * be gained by using this when it is known *if* the zlib stream itself does * not record the number; however, this is an illusion: the original writer * of the PNG may have selected a lower window size, and we really must * follow that because, for systems with with limited capabilities, we * would otherwise reject the application's attempts to use a smaller window * size (zlib doesn't have an interface to say "this or lower"!). * * inflateReset2 was added to zlib 1.2.4; before this the window could not be * reset, therefore it is necessary to always allocate the maximum window * size with earlier zlibs just in case later compressed chunks need it. */ { int ret; /* zlib return code */ #if ZLIB_VERNUM >= 0x1240 int window_bits = 0; # if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW) if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) == PNG_OPTION_ON) { window_bits = 15; png_ptr->zstream_start = 0; /* fixed window size */ } else { png_ptr->zstream_start = 1; } # endif #endif /* ZLIB_VERNUM >= 0x1240 */ /* Set this for safety, just in case the previous owner left pointers to * memory allocations. */ png_ptr->zstream.next_in = NULL; png_ptr->zstream.avail_in = 0; png_ptr->zstream.next_out = NULL; png_ptr->zstream.avail_out = 0; if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0) { #if ZLIB_VERNUM >= 0x1240 ret = inflateReset2(&png_ptr->zstream, window_bits); #else ret = inflateReset(&png_ptr->zstream); #endif } else { #if ZLIB_VERNUM >= 0x1240 ret = inflateInit2(&png_ptr->zstream, window_bits); #else ret = inflateInit(&png_ptr->zstream); #endif if (ret == Z_OK) png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED; } #if ZLIB_VERNUM >= 0x1290 && \ defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_IGNORE_ADLER32) if (((png_ptr->options >> PNG_IGNORE_ADLER32) & 3) == PNG_OPTION_ON) /* Turn off validation of the ADLER32 checksum in IDAT chunks */ ret = inflateValidate(&png_ptr->zstream, 0); #endif if (ret == Z_OK) png_ptr->zowner = owner; else png_zstream_error(png_ptr, ret); return ret; } #ifdef window_bits # undef window_bits #endif } #if ZLIB_VERNUM >= 0x1240 /* Handle the start of the inflate stream if we called inflateInit2(strm,0); * in this case some zlib versions skip validation of the CINFO field and, in * certain circumstances, libpng may end up displaying an invalid image, in * contrast to implementations that call zlib in the normal way (e.g. libpng * 1.5). */ int /* PRIVATE */ png_zlib_inflate(png_structrp png_ptr, int flush) { if (png_ptr->zstream_start && png_ptr->zstream.avail_in > 0) { if ((*png_ptr->zstream.next_in >> 4) > 7) { png_ptr->zstream.msg = "invalid window size (libpng)"; return Z_DATA_ERROR; } png_ptr->zstream_start = 0; } return inflate(&png_ptr->zstream, flush); } #endif /* Zlib >= 1.2.4 */ #ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED #if defined(PNG_READ_zTXt_SUPPORTED) || defined (PNG_READ_iTXt_SUPPORTED) /* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to * allow the caller to do multiple calls if required. If the 'finish' flag is * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and * Z_OK or Z_STREAM_END will be returned on success. * * The input and output sizes are updated to the actual amounts of data consumed * or written, not the amount available (as in a z_stream). The data pointers * are not changed, so the next input is (data+input_size) and the next * available output is (output+output_size). */ static int png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish, /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr, /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr) { if (png_ptr->zowner == owner) /* Else not claimed */ { int ret; png_alloc_size_t avail_out = *output_size_ptr; png_uint_32 avail_in = *input_size_ptr; /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it * can't even necessarily handle 65536 bytes) because the type uInt is * "16 bits or more". Consequently it is necessary to chunk the input to * zlib. This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the * maximum value that can be stored in a uInt.) It is possible to set * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have * a performance advantage, because it reduces the amount of data accessed * at each step and that may give the OS more time to page it in. */ png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input); /* avail_in and avail_out are set below from 'size' */ png_ptr->zstream.avail_in = 0; png_ptr->zstream.avail_out = 0; /* Read directly into the output if it is available (this is set to * a local buffer below if output is NULL). */ if (output != NULL) png_ptr->zstream.next_out = output; do { uInt avail; Byte local_buffer[PNG_INFLATE_BUF_SIZE]; /* zlib INPUT BUFFER */ /* The setting of 'avail_in' used to be outside the loop; by setting it * inside it is possible to chunk the input to zlib and simply rely on * zlib to advance the 'next_in' pointer. This allows arbitrary * amounts of data to be passed through zlib at the unavoidable cost of * requiring a window save (memcpy of up to 32768 output bytes) * every ZLIB_IO_MAX input bytes. */ avail_in += png_ptr->zstream.avail_in; /* not consumed last time */ avail = ZLIB_IO_MAX; if (avail_in < avail) avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */ avail_in -= avail; png_ptr->zstream.avail_in = avail; /* zlib OUTPUT BUFFER */ avail_out += png_ptr->zstream.avail_out; /* not written last time */ avail = ZLIB_IO_MAX; /* maximum zlib can process */ if (output == NULL) { /* Reset the output buffer each time round if output is NULL and * make available the full buffer, up to 'remaining_space' */ png_ptr->zstream.next_out = local_buffer; if ((sizeof local_buffer) < avail) avail = (sizeof local_buffer); } if (avail_out < avail) avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */ png_ptr->zstream.avail_out = avail; avail_out -= avail; /* zlib inflate call */ /* In fact 'avail_out' may be 0 at this point, that happens at the end * of the read when the final LZ end code was not passed at the end of * the previous chunk of input data. Tell zlib if we have reached the * end of the output buffer. */ ret = PNG_INFLATE(png_ptr, avail_out > 0 ? Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH)); } while (ret == Z_OK); /* For safety kill the local buffer pointer now */ if (output == NULL) png_ptr->zstream.next_out = NULL; /* Claw back the 'size' and 'remaining_space' byte counts. */ avail_in += png_ptr->zstream.avail_in; avail_out += png_ptr->zstream.avail_out; /* Update the input and output sizes; the updated values are the amount * consumed or written, effectively the inverse of what zlib uses. */ if (avail_out > 0) *output_size_ptr -= avail_out; if (avail_in > 0) *input_size_ptr -= avail_in; /* Ensure png_ptr->zstream.msg is set (even in the success case!) */ png_zstream_error(png_ptr, ret); return ret; } else { /* This is a bad internal error. The recovery assigns to the zstream msg * pointer, which is not owned by the caller, but this is safe; it's only * used on errors! */ png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed"); return Z_STREAM_ERROR; } } /* * Decompress trailing data in a chunk. The assumption is that read_buffer * points at an allocated area holding the contents of a chunk with a * trailing compressed part. What we get back is an allocated area * holding the original prefix part and an uncompressed version of the * trailing part (the malloc area passed in is freed). */ static int png_decompress_chunk(png_structrp png_ptr, png_uint_32 chunklength, png_uint_32 prefix_size, png_alloc_size_t *newlength /* must be initialized to the maximum! */, int terminate /*add a '\0' to the end of the uncompressed data*/) { /* TODO: implement different limits for different types of chunk. * * The caller supplies *newlength set to the maximum length of the * uncompressed data, but this routine allocates space for the prefix and * maybe a '\0' terminator too. We have to assume that 'prefix_size' is * limited only by the maximum chunk size. */ png_alloc_size_t limit = PNG_SIZE_MAX; # ifdef PNG_SET_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_malloc_max > 0 && png_ptr->user_chunk_malloc_max < limit) limit = png_ptr->user_chunk_malloc_max; # elif PNG_USER_CHUNK_MALLOC_MAX > 0 if (PNG_USER_CHUNK_MALLOC_MAX < limit) limit = PNG_USER_CHUNK_MALLOC_MAX; # endif if (limit >= prefix_size + (terminate != 0)) { int ret; limit -= prefix_size + (terminate != 0); if (limit < *newlength) *newlength = limit; /* Now try to claim the stream. */ ret = png_inflate_claim(png_ptr, png_ptr->chunk_name); if (ret == Z_OK) { png_uint_32 lzsize = chunklength - prefix_size; ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/, /* input: */ png_ptr->read_buffer + prefix_size, &lzsize, /* output: */ NULL, newlength); if (ret == Z_STREAM_END) { /* Use 'inflateReset' here, not 'inflateReset2' because this * preserves the previously decided window size (otherwise it would * be necessary to store the previous window size.) In practice * this doesn't matter anyway, because png_inflate will call inflate * with Z_FINISH in almost all cases, so the window will not be * maintained. */ if (inflateReset(&png_ptr->zstream) == Z_OK) { /* Because of the limit checks above we know that the new, * expanded, size will fit in a size_t (let alone an * png_alloc_size_t). Use png_malloc_base here to avoid an * extra OOM message. */ png_alloc_size_t new_size = *newlength; png_alloc_size_t buffer_size = prefix_size + new_size + (terminate != 0); png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr, buffer_size)); if (text != NULL) { memset(text, 0, buffer_size); ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/, png_ptr->read_buffer + prefix_size, &lzsize, text + prefix_size, newlength); if (ret == Z_STREAM_END) { if (new_size == *newlength) { if (terminate != 0) text[prefix_size + *newlength] = 0; if (prefix_size > 0) memcpy(text, png_ptr->read_buffer, prefix_size); { png_bytep old_ptr = png_ptr->read_buffer; png_ptr->read_buffer = text; png_ptr->read_buffer_size = buffer_size; text = old_ptr; /* freed below */ } } else { /* The size changed on the second read, there can be no * guarantee that anything is correct at this point. * The 'msg' pointer has been set to "unexpected end of * LZ stream", which is fine, but return an error code * that the caller won't accept. */ ret = PNG_UNEXPECTED_ZLIB_RETURN; } } else if (ret == Z_OK) ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */ /* Free the text pointer (this is the old read_buffer on * success) */ png_free(png_ptr, text); /* This really is very benign, but it's still an error because * the extra space may otherwise be used as a Trojan Horse. */ if (ret == Z_STREAM_END && chunklength - prefix_size != lzsize) png_chunk_benign_error(png_ptr, "extra compressed data"); } else { /* Out of memory allocating the buffer */ ret = Z_MEM_ERROR; png_zstream_error(png_ptr, Z_MEM_ERROR); } } else { /* inflateReset failed, store the error message */ png_zstream_error(png_ptr, ret); ret = PNG_UNEXPECTED_ZLIB_RETURN; } } else if (ret == Z_OK) ret = PNG_UNEXPECTED_ZLIB_RETURN; /* Release the claimed stream */ png_ptr->zowner = 0; } else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */ ret = PNG_UNEXPECTED_ZLIB_RETURN; return ret; } else { /* Application/configuration limits exceeded */ png_zstream_error(png_ptr, Z_MEM_ERROR); return Z_MEM_ERROR; } } #endif /* READ_zTXt || READ_iTXt */ #endif /* READ_COMPRESSED_TEXT */ #ifdef PNG_READ_iCCP_SUPPORTED /* Perform a partial read and decompress, producing 'avail_out' bytes and * reading from the current chunk as required. */ static int png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size, png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size, int finish) { if (png_ptr->zowner == png_ptr->chunk_name) { int ret; /* next_in and avail_in must have been initialized by the caller. */ png_ptr->zstream.next_out = next_out; png_ptr->zstream.avail_out = 0; /* set in the loop */ do { if (png_ptr->zstream.avail_in == 0) { if (read_size > *chunk_bytes) read_size = (uInt)*chunk_bytes; *chunk_bytes -= read_size; if (read_size > 0) png_crc_read(png_ptr, read_buffer, read_size); png_ptr->zstream.next_in = read_buffer; png_ptr->zstream.avail_in = read_size; } if (png_ptr->zstream.avail_out == 0) { uInt avail = ZLIB_IO_MAX; if (avail > *out_size) avail = (uInt)*out_size; *out_size -= avail; png_ptr->zstream.avail_out = avail; } /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all * the available output is produced; this allows reading of truncated * streams. */ ret = PNG_INFLATE(png_ptr, *chunk_bytes > 0 ? Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH)); } while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0)); *out_size += png_ptr->zstream.avail_out; png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */ /* Ensure the error message pointer is always set: */ png_zstream_error(png_ptr, ret); return ret; } else { png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed"); return Z_STREAM_ERROR; } } #endif /* READ_iCCP */ /* Read and check the IDHR chunk */ void /* PRIVATE */ png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[13]; png_uint_32 width, height; int bit_depth, color_type, compression_type, filter_type; int interlace_type; png_debug(1, "in png_handle_IHDR"); if ((png_ptr->mode & PNG_HAVE_IHDR) != 0) png_chunk_error(png_ptr, "out of place"); /* Check the length */ if (length != 13) png_chunk_error(png_ptr, "invalid"); png_ptr->mode |= PNG_HAVE_IHDR; png_crc_read(png_ptr, buf, 13); png_crc_finish(png_ptr, 0); width = png_get_uint_31(png_ptr, buf); height = png_get_uint_31(png_ptr, buf + 4); bit_depth = buf[8]; color_type = buf[9]; compression_type = buf[10]; filter_type = buf[11]; interlace_type = buf[12]; /* Set internal variables */ png_ptr->width = width; png_ptr->height = height; png_ptr->bit_depth = (png_byte)bit_depth; png_ptr->interlaced = (png_byte)interlace_type; png_ptr->color_type = (png_byte)color_type; #ifdef PNG_MNG_FEATURES_SUPPORTED png_ptr->filter_type = (png_byte)filter_type; #endif png_ptr->compression_type = (png_byte)compression_type; /* Find number of channels */ switch (png_ptr->color_type) { default: /* invalid, png_set_IHDR calls png_error */ case PNG_COLOR_TYPE_GRAY: case PNG_COLOR_TYPE_PALETTE: png_ptr->channels = 1; break; case PNG_COLOR_TYPE_RGB: png_ptr->channels = 3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: png_ptr->channels = 2; break; case PNG_COLOR_TYPE_RGB_ALPHA: png_ptr->channels = 4; break; } /* Set up other useful info */ png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * png_ptr->channels); png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width); png_debug1(3, "bit_depth = %d", png_ptr->bit_depth); png_debug1(3, "channels = %d", png_ptr->channels); png_debug1(3, "rowbytes = %lu", (unsigned long)png_ptr->rowbytes); png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type, interlace_type, compression_type, filter_type); } /* Read and check the palette */ void /* PRIVATE */ png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_color palette[PNG_MAX_PALETTE_LENGTH]; int max_palette_length, num, i; #ifdef PNG_POINTER_INDEXING_SUPPORTED png_colorp pal_ptr; #endif png_debug(1, "in png_handle_PLTE"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); /* Moved to before the 'after IDAT' check below because otherwise duplicate * PLTE chunks are potentially ignored (the spec says there shall not be more * than one PLTE, the error is not treated as benign, so this check trumps * the requirement that PLTE appears before IDAT.) */ else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0) png_chunk_error(png_ptr, "duplicate"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { /* This is benign because the non-benign error happened before, when an * IDAT was encountered in a color-mapped image with no PLTE. */ png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } png_ptr->mode |= PNG_HAVE_PLTE; if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "ignored in grayscale PNG"); return; } #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) { png_crc_finish(png_ptr, length); return; } #endif if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3) { png_crc_finish(png_ptr, length); if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) png_chunk_benign_error(png_ptr, "invalid"); else png_chunk_error(png_ptr, "invalid"); return; } /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */ num = (int)length / 3; /* If the palette has 256 or fewer entries but is too large for the bit * depth, we don't issue an error, to preserve the behavior of previous * libpng versions. We silently truncate the unused extra palette entries * here. */ if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) max_palette_length = (1 << png_ptr->bit_depth); else max_palette_length = PNG_MAX_PALETTE_LENGTH; if (num > max_palette_length) num = max_palette_length; #ifdef PNG_POINTER_INDEXING_SUPPORTED for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); pal_ptr->red = buf[0]; pal_ptr->green = buf[1]; pal_ptr->blue = buf[2]; } #else for (i = 0; i < num; i++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); /* Don't depend upon png_color being any order */ palette[i].red = buf[0]; palette[i].green = buf[1]; palette[i].blue = buf[2]; } #endif /* If we actually need the PLTE chunk (ie for a paletted image), we do * whatever the normal CRC configuration tells us. However, if we * have an RGB image, the PLTE can be considered ancillary, so * we will act as though it is. */ #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) #endif { png_crc_finish(png_ptr, (png_uint_32) (length - (unsigned int)num * 3)); } #ifndef PNG_READ_OPT_PLTE_SUPPORTED else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */ { /* If we don't want to use the data from an ancillary chunk, * we have two options: an error abort, or a warning and we * ignore the data in this chunk (which should be OK, since * it's considered ancillary for a RGB or RGBA image). * * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the * chunk type to determine whether to check the ancillary or the critical * flags. */ if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0) { if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0) return; else png_chunk_error(png_ptr, "CRC error"); } /* Otherwise, we (optionally) emit a warning and use the chunk. */ else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0) png_chunk_warning(png_ptr, "CRC error"); } #endif /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its * own copy of the palette. This has the side effect that when png_start_row * is called (this happens after any call to png_read_update_info) the * info_ptr palette gets changed. This is extremely unexpected and * confusing. * * Fix this by not sharing the palette in this way. */ png_set_PLTE(png_ptr, info_ptr, palette, num); /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before * IDAT. Prior to 1.6.0 this was not checked; instead the code merely * checked the apparent validity of a tRNS chunk inserted before PLTE on a * palette PNG. 1.6.0 attempts to rigorously follow the standard and * therefore does a benign error if the erroneous condition is detected *and* * cancels the tRNS if the benign error returns. The alternative is to * amend the standard since it would be rather hypocritical of the standards * maintainers to ignore it. */ #ifdef PNG_READ_tRNS_SUPPORTED if (png_ptr->num_trans > 0 || (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)) { /* Cancel this because otherwise it would be used if the transforms * require it. Don't cancel the 'valid' flag because this would prevent * detection of duplicate chunks. */ png_ptr->num_trans = 0; if (info_ptr != NULL) info_ptr->num_trans = 0; png_chunk_benign_error(png_ptr, "tRNS must be after"); } #endif #ifdef PNG_READ_hIST_SUPPORTED if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0) png_chunk_benign_error(png_ptr, "hIST must be after"); #endif #ifdef PNG_READ_bKGD_SUPPORTED if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0) png_chunk_benign_error(png_ptr, "bKGD must be after"); #endif } void /* PRIVATE */ png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_debug(1, "in png_handle_IEND"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0 || (png_ptr->mode & PNG_HAVE_IDAT) == 0) png_chunk_error(png_ptr, "out of place"); png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND); png_crc_finish(png_ptr, length); if (length != 0) png_chunk_benign_error(png_ptr, "invalid"); PNG_UNUSED(info_ptr) } #ifdef PNG_READ_gAMA_SUPPORTED void /* PRIVATE */ png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_fixed_point igamma; png_byte buf[4]; png_debug(1, "in png_handle_gAMA"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } if (length != 4) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 4); if (png_crc_finish(png_ptr, 0) != 0) return; igamma = png_get_fixed_point(NULL, buf); png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma); png_colorspace_sync(png_ptr, info_ptr); } #endif #ifdef PNG_READ_sBIT_SUPPORTED void /* PRIVATE */ png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { unsigned int truelen, i; png_byte sample_depth; png_byte buf[4]; png_debug(1, "in png_handle_sBIT"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { truelen = 3; sample_depth = 8; } else { truelen = png_ptr->channels; sample_depth = png_ptr->bit_depth; } if (length != truelen || length > 4) { png_chunk_benign_error(png_ptr, "invalid"); png_crc_finish(png_ptr, length); return; } buf[0] = buf[1] = buf[2] = buf[3] = sample_depth; png_crc_read(png_ptr, buf, truelen); if (png_crc_finish(png_ptr, 0) != 0) return; for (i=0; i<truelen; ++i) { if (buf[i] == 0 || buf[i] > sample_depth) { png_chunk_benign_error(png_ptr, "invalid"); return; } } if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0) { png_ptr->sig_bit.red = buf[0]; png_ptr->sig_bit.green = buf[1]; png_ptr->sig_bit.blue = buf[2]; png_ptr->sig_bit.alpha = buf[3]; } else { png_ptr->sig_bit.gray = buf[0]; png_ptr->sig_bit.red = buf[0]; png_ptr->sig_bit.green = buf[0]; png_ptr->sig_bit.blue = buf[0]; png_ptr->sig_bit.alpha = buf[1]; } png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit)); } #endif #ifdef PNG_READ_cHRM_SUPPORTED void /* PRIVATE */ png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[32]; png_xy xy; png_debug(1, "in png_handle_cHRM"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } if (length != 32) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 32); if (png_crc_finish(png_ptr, 0) != 0) return; xy.whitex = png_get_fixed_point(NULL, buf); xy.whitey = png_get_fixed_point(NULL, buf + 4); xy.redx = png_get_fixed_point(NULL, buf + 8); xy.redy = png_get_fixed_point(NULL, buf + 12); xy.greenx = png_get_fixed_point(NULL, buf + 16); xy.greeny = png_get_fixed_point(NULL, buf + 20); xy.bluex = png_get_fixed_point(NULL, buf + 24); xy.bluey = png_get_fixed_point(NULL, buf + 28); if (xy.whitex == PNG_FIXED_ERROR || xy.whitey == PNG_FIXED_ERROR || xy.redx == PNG_FIXED_ERROR || xy.redy == PNG_FIXED_ERROR || xy.greenx == PNG_FIXED_ERROR || xy.greeny == PNG_FIXED_ERROR || xy.bluex == PNG_FIXED_ERROR || xy.bluey == PNG_FIXED_ERROR) { png_chunk_benign_error(png_ptr, "invalid values"); return; } /* If a colorspace error has already been output skip this chunk */ if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0) return; if ((png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0) { png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID; png_colorspace_sync(png_ptr, info_ptr); png_chunk_benign_error(png_ptr, "duplicate"); return; } png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM; (void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy, 1/*prefer cHRM values*/); png_colorspace_sync(png_ptr, info_ptr); } #endif #ifdef PNG_READ_sRGB_SUPPORTED void /* PRIVATE */ png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte intent; png_debug(1, "in png_handle_sRGB"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } if (length != 1) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, &intent, 1); if (png_crc_finish(png_ptr, 0) != 0) return; /* If a colorspace error has already been output skip this chunk */ if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0) return; /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect * this. */ if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) != 0) { png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID; png_colorspace_sync(png_ptr, info_ptr); png_chunk_benign_error(png_ptr, "too many profiles"); return; } (void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent); png_colorspace_sync(png_ptr, info_ptr); } #endif /* READ_sRGB */ #ifdef PNG_READ_iCCP_SUPPORTED void /* PRIVATE */ png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) /* Note: this does not properly handle profiles that are > 64K under DOS */ { png_const_charp errmsg = NULL; /* error message output, or no error */ int finished = 0; /* crc checked */ png_debug(1, "in png_handle_iCCP"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } /* Consistent with all the above colorspace handling an obviously *invalid* * chunk is just ignored, so does not invalidate the color space. An * alternative is to set the 'invalid' flags at the start of this routine * and only clear them in they were not set before and all the tests pass. */ /* The keyword must be at least one character and there is a * terminator (0) byte and the compression method byte, and the * 'zlib' datastream is at least 11 bytes. */ if (length < 14) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "too short"); return; } /* If a colorspace error has already been output skip this chunk */ if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0) { png_crc_finish(png_ptr, length); return; } /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect * this. */ if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0) { uInt read_length, keyword_length; char keyword[81]; /* Find the keyword; the keyword plus separator and compression method * bytes can be at most 81 characters long. */ read_length = 81; /* maximum */ if (read_length > length) read_length = (uInt)length; png_crc_read(png_ptr, (png_bytep)keyword, read_length); length -= read_length; /* The minimum 'zlib' stream is assumed to be just the 2 byte header, * 5 bytes minimum 'deflate' stream, and the 4 byte checksum. */ if (length < 11) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "too short"); return; } keyword_length = 0; while (keyword_length < 80 && keyword_length < read_length && keyword[keyword_length] != 0) ++keyword_length; /* TODO: make the keyword checking common */ if (keyword_length >= 1 && keyword_length <= 79) { /* We only understand '0' compression - deflate - so if we get a * different value we can't safely decode the chunk. */ if (keyword_length+1 < read_length && keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE) { read_length -= keyword_length+2; if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK) { Byte profile_header[132]={0}; Byte local_buffer[PNG_INFLATE_BUF_SIZE]; png_alloc_size_t size = (sizeof profile_header); png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2); png_ptr->zstream.avail_in = read_length; (void)png_inflate_read(png_ptr, local_buffer, (sizeof local_buffer), &length, profile_header, &size, 0/*finish: don't, because the output is too small*/); if (size == 0) { /* We have the ICC profile header; do the basic header checks. */ const png_uint_32 profile_length = png_get_uint_32(profile_header); if (png_icc_check_length(png_ptr, &png_ptr->colorspace, keyword, profile_length) != 0) { /* The length is apparently ok, so we can check the 132 * byte header. */ if (png_icc_check_header(png_ptr, &png_ptr->colorspace, keyword, profile_length, profile_header, png_ptr->color_type) != 0) { /* Now read the tag table; a variable size buffer is * needed at this point, allocate one for the whole * profile. The header check has already validated * that none of this stuff will overflow. */ const png_uint_32 tag_count = png_get_uint_32( profile_header+128); png_bytep profile = png_read_buffer(png_ptr, profile_length, 2/*silent*/); if (profile != NULL) { memcpy(profile, profile_header, (sizeof profile_header)); size = 12 * tag_count; (void)png_inflate_read(png_ptr, local_buffer, (sizeof local_buffer), &length, profile + (sizeof profile_header), &size, 0); /* Still expect a buffer error because we expect * there to be some tag data! */ if (size == 0) { if (png_icc_check_tag_table(png_ptr, &png_ptr->colorspace, keyword, profile_length, profile) != 0) { /* The profile has been validated for basic * security issues, so read the whole thing in. */ size = profile_length - (sizeof profile_header) - 12 * tag_count; (void)png_inflate_read(png_ptr, local_buffer, (sizeof local_buffer), &length, profile + (sizeof profile_header) + 12 * tag_count, &size, 1/*finish*/); if (length > 0 && !(png_ptr->flags & PNG_FLAG_BENIGN_ERRORS_WARN)) errmsg = "extra compressed data"; /* But otherwise allow extra data: */ else if (size == 0) { if (length > 0) { /* This can be handled completely, so * keep going. */ png_chunk_warning(png_ptr, "extra compressed data"); } png_crc_finish(png_ptr, length); finished = 1; # if defined(PNG_sRGB_SUPPORTED) && PNG_sRGB_PROFILE_CHECKS >= 0 /* Check for a match against sRGB */ png_icc_set_sRGB(png_ptr, &png_ptr->colorspace, profile, png_ptr->zstream.adler); # endif /* Steal the profile for info_ptr. */ if (info_ptr != NULL) { png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0); info_ptr->iccp_name = png_voidcast(char*, png_malloc_base(png_ptr, keyword_length+1)); if (info_ptr->iccp_name != NULL) { memcpy(info_ptr->iccp_name, keyword, keyword_length+1); info_ptr->iccp_proflen = profile_length; info_ptr->iccp_profile = profile; png_ptr->read_buffer = NULL; /*steal*/ info_ptr->free_me |= PNG_FREE_ICCP; info_ptr->valid |= PNG_INFO_iCCP; } else { png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID; errmsg = "out of memory"; } } /* else the profile remains in the read * buffer which gets reused for subsequent * chunks. */ if (info_ptr != NULL) png_colorspace_sync(png_ptr, info_ptr); if (errmsg == NULL) { png_ptr->zowner = 0; return; } } if (errmsg == NULL) errmsg = png_ptr->zstream.msg; } /* else png_icc_check_tag_table output an error */ } else /* profile truncated */ errmsg = png_ptr->zstream.msg; } else errmsg = "out of memory"; } /* else png_icc_check_header output an error */ } /* else png_icc_check_length output an error */ } else /* profile truncated */ errmsg = png_ptr->zstream.msg; /* Release the stream */ png_ptr->zowner = 0; } else /* png_inflate_claim failed */ errmsg = png_ptr->zstream.msg; } else errmsg = "bad compression method"; /* or missing */ } else errmsg = "bad keyword"; } else errmsg = "too many profiles"; /* Failure: the reason is in 'errmsg' */ if (finished == 0) png_crc_finish(png_ptr, length); png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID; png_colorspace_sync(png_ptr, info_ptr); if (errmsg != NULL) /* else already output */ png_chunk_benign_error(png_ptr, errmsg); } #endif /* READ_iCCP */ #ifdef PNG_READ_sPLT_SUPPORTED void /* PRIVATE */ png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) /* Note: this does not properly handle chunks that are > 64K under DOS */ { png_bytep entry_start, buffer; png_sPLT_t new_palette; png_sPLT_entryp pp; png_uint_32 data_length; int entry_size, i; png_uint_32 skip = 0; png_uint_32 dl; size_t max_dl; png_debug(1, "in png_handle_sPLT"); #ifdef PNG_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_cache_max != 0) { if (png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); return; } if (--png_ptr->user_chunk_cache_max == 1) { png_warning(png_ptr, "No space in chunk cache for sPLT"); png_crc_finish(png_ptr, length); return; } } #endif if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } #ifdef PNG_MAX_MALLOC_64K if (length > 65535U) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "too large to fit in memory"); return; } #endif buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/); if (buffer == NULL) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of memory"); return; } /* WARNING: this may break if size_t is less than 32 bits; it is assumed * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a * potential breakage point if the types in pngconf.h aren't exactly right. */ png_crc_read(png_ptr, buffer, length); if (png_crc_finish(png_ptr, skip) != 0) return; buffer[length] = 0; for (entry_start = buffer; *entry_start; entry_start++) /* Empty loop to find end of name */ ; ++entry_start; /* A sample depth should follow the separator, and we should be on it */ if (length < 2U || entry_start > buffer + (length - 2U)) { png_warning(png_ptr, "malformed sPLT chunk"); return; } new_palette.depth = *entry_start++; entry_size = (new_palette.depth == 8 ? 6 : 10); /* This must fit in a png_uint_32 because it is derived from the original * chunk data length. */ data_length = length - (png_uint_32)(entry_start - buffer); /* Integrity-check the data length */ if ((data_length % (unsigned int)entry_size) != 0) { png_warning(png_ptr, "sPLT chunk has bad length"); return; } dl = (png_uint_32)(data_length / (unsigned int)entry_size); max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry)); if (dl > max_dl) { png_warning(png_ptr, "sPLT chunk too long"); return; } new_palette.nentries = (png_int_32)(data_length / (unsigned int)entry_size); new_palette.entries = (png_sPLT_entryp)png_malloc_warn(png_ptr, (png_alloc_size_t) new_palette.nentries * (sizeof (png_sPLT_entry))); if (new_palette.entries == NULL) { png_warning(png_ptr, "sPLT chunk requires too much memory"); return; } #ifdef PNG_POINTER_INDEXING_SUPPORTED for (i = 0; i < new_palette.nentries; i++) { pp = new_palette.entries + i; if (new_palette.depth == 8) { pp->red = *entry_start++; pp->green = *entry_start++; pp->blue = *entry_start++; pp->alpha = *entry_start++; } else { pp->red = png_get_uint_16(entry_start); entry_start += 2; pp->green = png_get_uint_16(entry_start); entry_start += 2; pp->blue = png_get_uint_16(entry_start); entry_start += 2; pp->alpha = png_get_uint_16(entry_start); entry_start += 2; } pp->frequency = png_get_uint_16(entry_start); entry_start += 2; } #else pp = new_palette.entries; for (i = 0; i < new_palette.nentries; i++) { if (new_palette.depth == 8) { pp[i].red = *entry_start++; pp[i].green = *entry_start++; pp[i].blue = *entry_start++; pp[i].alpha = *entry_start++; } else { pp[i].red = png_get_uint_16(entry_start); entry_start += 2; pp[i].green = png_get_uint_16(entry_start); entry_start += 2; pp[i].blue = png_get_uint_16(entry_start); entry_start += 2; pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2; } pp[i].frequency = png_get_uint_16(entry_start); entry_start += 2; } #endif /* Discard all chunk data except the name and stash that */ new_palette.name = (png_charp)buffer; png_set_sPLT(png_ptr, info_ptr, &new_palette, 1); png_free(png_ptr, new_palette.entries); } #endif /* READ_sPLT */ #ifdef PNG_READ_tRNS_SUPPORTED void /* PRIVATE */ png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte readbuf[PNG_MAX_PALETTE_LENGTH]; png_debug(1, "in png_handle_tRNS"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) { png_byte buf[2]; if (length != 2) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 2); png_ptr->num_trans = 1; png_ptr->trans_color.gray = png_get_uint_16(buf); } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) { png_byte buf[6]; if (length != 6) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, length); png_ptr->num_trans = 1; png_ptr->trans_color.red = png_get_uint_16(buf); png_ptr->trans_color.green = png_get_uint_16(buf + 2); png_ptr->trans_color.blue = png_get_uint_16(buf + 4); } else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if ((png_ptr->mode & PNG_HAVE_PLTE) == 0) { /* TODO: is this actually an error in the ISO spec? */ png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } if (length > (unsigned int) png_ptr->num_palette || length > (unsigned int) PNG_MAX_PALETTE_LENGTH || length == 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, readbuf, length); png_ptr->num_trans = (png_uint_16)length; } else { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid with alpha channel"); return; } if (png_crc_finish(png_ptr, 0) != 0) { png_ptr->num_trans = 0; return; } /* TODO: this is a horrible side effect in the palette case because the * png_struct ends up with a pointer to the tRNS buffer owned by the * png_info. Fix this. */ png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans, &(png_ptr->trans_color)); } #endif #ifdef PNG_READ_bKGD_SUPPORTED void /* PRIVATE */ png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { unsigned int truelen; png_byte buf[6]; png_color_16 background; png_debug(1, "in png_handle_bKGD"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 || (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && (png_ptr->mode & PNG_HAVE_PLTE) == 0)) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) truelen = 1; else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0) truelen = 6; else truelen = 2; if (length != truelen) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, truelen); if (png_crc_finish(png_ptr, 0) != 0) return; /* We convert the index value into RGB components so that we can allow * arbitrary RGB values for background when we have transparency, and * so it is easy to determine the RGB values of the background color * from the info_ptr struct. */ if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { background.index = buf[0]; if (info_ptr != NULL && info_ptr->num_palette != 0) { if (buf[0] >= info_ptr->num_palette) { png_chunk_benign_error(png_ptr, "invalid index"); return; } background.red = (png_uint_16)png_ptr->palette[buf[0]].red; background.green = (png_uint_16)png_ptr->palette[buf[0]].green; background.blue = (png_uint_16)png_ptr->palette[buf[0]].blue; } else background.red = background.green = background.blue = 0; background.gray = 0; } else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */ { if (png_ptr->bit_depth <= 8) { if (buf[0] != 0 || buf[1] >= (unsigned int)(1 << png_ptr->bit_depth)) { png_chunk_benign_error(png_ptr, "invalid gray level"); return; } } background.index = 0; background.red = background.green = background.blue = background.gray = png_get_uint_16(buf); } else { if (png_ptr->bit_depth <= 8) { if (buf[0] != 0 || buf[2] != 0 || buf[4] != 0) { png_chunk_benign_error(png_ptr, "invalid color"); return; } } background.index = 0; background.red = png_get_uint_16(buf); background.green = png_get_uint_16(buf + 2); background.blue = png_get_uint_16(buf + 4); background.gray = 0; } png_set_bKGD(png_ptr, info_ptr, &background); } #endif #ifdef PNG_READ_eXIf_SUPPORTED void /* PRIVATE */ png_handle_eXIf(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { unsigned int i; png_debug(1, "in png_handle_eXIf"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); if (length < 2) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "too short"); return; } else if (info_ptr == NULL || (info_ptr->valid & PNG_INFO_eXIf) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } info_ptr->free_me |= PNG_FREE_EXIF; info_ptr->eXIf_buf = png_voidcast(png_bytep, png_malloc_warn(png_ptr, length)); if (info_ptr->eXIf_buf == NULL) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of memory"); return; } for (i = 0; i < length; i++) { png_byte buf[1]; png_crc_read(png_ptr, buf, 1); info_ptr->eXIf_buf[i] = buf[0]; if (i == 1 && buf[0] != 'M' && buf[0] != 'I' && info_ptr->eXIf_buf[0] != buf[0]) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "incorrect byte-order specifier"); png_free(png_ptr, info_ptr->eXIf_buf); info_ptr->eXIf_buf = NULL; return; } } if (png_crc_finish(png_ptr, 0) != 0) return; png_set_eXIf_1(png_ptr, info_ptr, length, info_ptr->eXIf_buf); png_free(png_ptr, info_ptr->eXIf_buf); info_ptr->eXIf_buf = NULL; } #endif #ifdef PNG_READ_hIST_SUPPORTED void /* PRIVATE */ png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { unsigned int num, i; png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH]; png_debug(1, "in png_handle_hIST"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 || (png_ptr->mode & PNG_HAVE_PLTE) == 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } num = length / 2 ; if (num != (unsigned int) png_ptr->num_palette || num > (unsigned int) PNG_MAX_PALETTE_LENGTH) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } for (i = 0; i < num; i++) { png_byte buf[2]; png_crc_read(png_ptr, buf, 2); readbuf[i] = png_get_uint_16(buf); } if (png_crc_finish(png_ptr, 0) != 0) return; png_set_hIST(png_ptr, info_ptr, readbuf); } #endif #ifdef PNG_READ_pHYs_SUPPORTED void /* PRIVATE */ png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[9]; png_uint_32 res_x, res_y; int unit_type; png_debug(1, "in png_handle_pHYs"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if (length != 9) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 9); if (png_crc_finish(png_ptr, 0) != 0) return; res_x = png_get_uint_32(buf); res_y = png_get_uint_32(buf + 4); unit_type = buf[8]; png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type); } #endif #ifdef PNG_READ_oFFs_SUPPORTED void /* PRIVATE */ png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[9]; png_int_32 offset_x, offset_y; int unit_type; png_debug(1, "in png_handle_oFFs"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if (length != 9) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 9); if (png_crc_finish(png_ptr, 0) != 0) return; offset_x = png_get_int_32(buf); offset_y = png_get_int_32(buf + 4); unit_type = buf[8]; png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type); } #endif #ifdef PNG_READ_pCAL_SUPPORTED /* Read the pCAL chunk (described in the PNG Extensions document) */ void /* PRIVATE */ png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_int_32 X0, X1; png_byte type, nparams; png_bytep buffer, buf, units, endptr; png_charpp params; int i; png_debug(1, "in png_handle_pCAL"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)", length + 1); buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/); if (buffer == NULL) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of memory"); return; } png_crc_read(png_ptr, buffer, length); if (png_crc_finish(png_ptr, 0) != 0) return; buffer[length] = 0; /* Null terminate the last string */ png_debug(3, "Finding end of pCAL purpose string"); for (buf = buffer; *buf; buf++) /* Empty loop */ ; endptr = buffer + length; /* We need to have at least 12 bytes after the purpose string * in order to get the parameter information. */ if (endptr - buf <= 12) { png_chunk_benign_error(png_ptr, "invalid"); return; } png_debug(3, "Reading pCAL X0, X1, type, nparams, and units"); X0 = png_get_int_32((png_bytep)buf+1); X1 = png_get_int_32((png_bytep)buf+5); type = buf[9]; nparams = buf[10]; units = buf + 11; png_debug(3, "Checking pCAL equation type and number of parameters"); /* Check that we have the right number of parameters for known * equation types. */ if ((type == PNG_EQUATION_LINEAR && nparams != 2) || (type == PNG_EQUATION_BASE_E && nparams != 3) || (type == PNG_EQUATION_ARBITRARY && nparams != 3) || (type == PNG_EQUATION_HYPERBOLIC && nparams != 4)) { png_chunk_benign_error(png_ptr, "invalid parameter count"); return; } else if (type >= PNG_EQUATION_LAST) { png_chunk_benign_error(png_ptr, "unrecognized equation type"); } for (buf = units; *buf; buf++) /* Empty loop to move past the units string. */ ; png_debug(3, "Allocating pCAL parameters array"); params = png_voidcast(png_charpp, png_malloc_warn(png_ptr, nparams * (sizeof (png_charp)))); if (params == NULL) { png_chunk_benign_error(png_ptr, "out of memory"); return; } /* Get pointers to the start of each parameter string. */ for (i = 0; i < nparams; i++) { buf++; /* Skip the null string terminator from previous parameter. */ png_debug1(3, "Reading pCAL parameter %d", i); for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++) /* Empty loop to move past each parameter string */ ; /* Make sure we haven't run out of data yet */ if (buf > endptr) { png_free(png_ptr, params); png_chunk_benign_error(png_ptr, "invalid data"); return; } } png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams, (png_charp)units, params); png_free(png_ptr, params); } #endif #ifdef PNG_READ_sCAL_SUPPORTED /* Read the sCAL chunk */ void /* PRIVATE */ png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_bytep buffer; size_t i; int state; png_debug(1, "in png_handle_sCAL"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } /* Need unit type, width, \0, height: minimum 4 bytes */ else if (length < 4) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)", length + 1); buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/); if (buffer == NULL) { png_chunk_benign_error(png_ptr, "out of memory"); png_crc_finish(png_ptr, length); return; } png_crc_read(png_ptr, buffer, length); buffer[length] = 0; /* Null terminate the last string */ if (png_crc_finish(png_ptr, 0) != 0) return; /* Validate the unit. */ if (buffer[0] != 1 && buffer[0] != 2) { png_chunk_benign_error(png_ptr, "invalid unit"); return; } /* Validate the ASCII numbers, need two ASCII numbers separated by * a '\0' and they need to fit exactly in the chunk data. */ i = 1; state = 0; if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 || i >= length || buffer[i++] != 0) png_chunk_benign_error(png_ptr, "bad width format"); else if (PNG_FP_IS_POSITIVE(state) == 0) png_chunk_benign_error(png_ptr, "non-positive width"); else { size_t heighti = i; state = 0; if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 || i != length) png_chunk_benign_error(png_ptr, "bad height format"); else if (PNG_FP_IS_POSITIVE(state) == 0) png_chunk_benign_error(png_ptr, "non-positive height"); else /* This is the (only) success case. */ png_set_sCAL_s(png_ptr, info_ptr, buffer[0], (png_charp)buffer+1, (png_charp)buffer+heighti); } } #endif #ifdef PNG_READ_tIME_SUPPORTED void /* PRIVATE */ png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[7]; png_time mod_time; png_debug(1, "in png_handle_tIME"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; if (length != 7) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 7); if (png_crc_finish(png_ptr, 0) != 0) return; mod_time.second = buf[6]; mod_time.minute = buf[5]; mod_time.hour = buf[4]; mod_time.day = buf[3]; mod_time.month = buf[2]; mod_time.year = png_get_uint_16(buf); png_set_tIME(png_ptr, info_ptr, &mod_time); } #endif #ifdef PNG_READ_tEXt_SUPPORTED /* Note: this does not properly handle chunks that are > 64K under DOS */ void /* PRIVATE */ png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_text text_info; png_bytep buffer; png_charp key; png_charp text; png_uint_32 skip = 0; png_debug(1, "in png_handle_tEXt"); #ifdef PNG_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_cache_max != 0) { if (png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); return; } if (--png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "no space in chunk cache"); return; } } #endif if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; #ifdef PNG_MAX_MALLOC_64K if (length > 65535U) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "too large to fit in memory"); return; } #endif buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/); if (buffer == NULL) { png_chunk_benign_error(png_ptr, "out of memory"); return; } png_crc_read(png_ptr, buffer, length); if (png_crc_finish(png_ptr, skip) != 0) return; key = (png_charp)buffer; key[length] = 0; for (text = key; *text; text++) /* Empty loop to find end of key */ ; if (text != key + length) text++; text_info.compression = PNG_TEXT_COMPRESSION_NONE; text_info.key = key; text_info.lang = NULL; text_info.lang_key = NULL; text_info.itxt_length = 0; text_info.text = text; text_info.text_length = strlen(text); if (png_set_text_2(png_ptr, info_ptr, &text_info, 1) != 0) png_warning(png_ptr, "Insufficient memory to process text chunk"); } #endif #ifdef PNG_READ_zTXt_SUPPORTED /* Note: this does not correctly handle chunks that are > 64K under DOS */ void /* PRIVATE */ png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_const_charp errmsg = NULL; png_bytep buffer; png_uint_32 keyword_length; png_debug(1, "in png_handle_zTXt"); #ifdef PNG_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_cache_max != 0) { if (png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); return; } if (--png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "no space in chunk cache"); return; } } #endif if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; /* Note, "length" is sufficient here; we won't be adding * a null terminator later. */ buffer = png_read_buffer(png_ptr, length, 2/*silent*/); if (buffer == NULL) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of memory"); return; } png_crc_read(png_ptr, buffer, length); if (png_crc_finish(png_ptr, 0) != 0) return; /* TODO: also check that the keyword contents match the spec! */ for (keyword_length = 0; keyword_length < length && buffer[keyword_length] != 0; ++keyword_length) /* Empty loop to find end of name */ ; if (keyword_length > 79 || keyword_length < 1) errmsg = "bad keyword"; /* zTXt must have some LZ data after the keyword, although it may expand to * zero bytes; we need a '\0' at the end of the keyword, the compression type * then the LZ data: */ else if (keyword_length + 3 > length) errmsg = "truncated"; else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE) errmsg = "unknown compression type"; else { png_alloc_size_t uncompressed_length = PNG_SIZE_MAX; /* TODO: at present png_decompress_chunk imposes a single application * level memory limit, this should be split to different values for iCCP * and text chunks. */ if (png_decompress_chunk(png_ptr, length, keyword_length+2, &uncompressed_length, 1/*terminate*/) == Z_STREAM_END) { png_text text; if (png_ptr->read_buffer == NULL) errmsg="Read failure in png_handle_zTXt"; else { /* It worked; png_ptr->read_buffer now looks like a tEXt chunk * except for the extra compression type byte and the fact that * it isn't necessarily '\0' terminated. */ buffer = png_ptr->read_buffer; buffer[uncompressed_length+(keyword_length+2)] = 0; text.compression = PNG_TEXT_COMPRESSION_zTXt; text.key = (png_charp)buffer; text.text = (png_charp)(buffer + keyword_length+2); text.text_length = uncompressed_length; text.itxt_length = 0; text.lang = NULL; text.lang_key = NULL; if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0) errmsg = "insufficient memory"; } } else errmsg = png_ptr->zstream.msg; } if (errmsg != NULL) png_chunk_benign_error(png_ptr, errmsg); } #endif #ifdef PNG_READ_iTXt_SUPPORTED /* Note: this does not correctly handle chunks that are > 64K under DOS */ void /* PRIVATE */ png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_const_charp errmsg = NULL; png_bytep buffer; png_uint_32 prefix_length; png_debug(1, "in png_handle_iTXt"); #ifdef PNG_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_cache_max != 0) { if (png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); return; } if (--png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "no space in chunk cache"); return; } } #endif if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/); if (buffer == NULL) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of memory"); return; } png_crc_read(png_ptr, buffer, length); if (png_crc_finish(png_ptr, 0) != 0) return; /* First the keyword. */ for (prefix_length=0; prefix_length < length && buffer[prefix_length] != 0; ++prefix_length) /* Empty loop */ ; /* Perform a basic check on the keyword length here. */ if (prefix_length > 79 || prefix_length < 1) errmsg = "bad keyword"; /* Expect keyword, compression flag, compression type, language, translated * keyword (both may be empty but are 0 terminated) then the text, which may * be empty. */ else if (prefix_length + 5 > length) errmsg = "truncated"; else if (buffer[prefix_length+1] == 0 || (buffer[prefix_length+1] == 1 && buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE)) { int compressed = buffer[prefix_length+1] != 0; png_uint_32 language_offset, translated_keyword_offset; png_alloc_size_t uncompressed_length = 0; /* Now the language tag */ prefix_length += 3; language_offset = prefix_length; for (; prefix_length < length && buffer[prefix_length] != 0; ++prefix_length) /* Empty loop */ ; /* WARNING: the length may be invalid here, this is checked below. */ translated_keyword_offset = ++prefix_length; for (; prefix_length < length && buffer[prefix_length] != 0; ++prefix_length) /* Empty loop */ ; /* prefix_length should now be at the trailing '\0' of the translated * keyword, but it may already be over the end. None of this arithmetic * can overflow because chunks are at most 2^31 bytes long, but on 16-bit * systems the available allocation may overflow. */ ++prefix_length; if (compressed == 0 && prefix_length <= length) uncompressed_length = length - prefix_length; else if (compressed != 0 && prefix_length < length) { uncompressed_length = PNG_SIZE_MAX; /* TODO: at present png_decompress_chunk imposes a single application * level memory limit, this should be split to different values for * iCCP and text chunks. */ if (png_decompress_chunk(png_ptr, length, prefix_length, &uncompressed_length, 1/*terminate*/) == Z_STREAM_END) buffer = png_ptr->read_buffer; else errmsg = png_ptr->zstream.msg; } else errmsg = "truncated"; if (errmsg == NULL) { png_text text; buffer[uncompressed_length+prefix_length] = 0; if (compressed == 0) text.compression = PNG_ITXT_COMPRESSION_NONE; else text.compression = PNG_ITXT_COMPRESSION_zTXt; text.key = (png_charp)buffer; text.lang = (png_charp)buffer + language_offset; text.lang_key = (png_charp)buffer + translated_keyword_offset; text.text = (png_charp)buffer + prefix_length; text.text_length = 0; text.itxt_length = uncompressed_length; if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0) errmsg = "insufficient memory"; } } else errmsg = "bad compression info"; if (errmsg != NULL) png_chunk_benign_error(png_ptr, errmsg); } #endif #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED /* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */ static int png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length) { png_alloc_size_t limit = PNG_SIZE_MAX; if (png_ptr->unknown_chunk.data != NULL) { png_free(png_ptr, png_ptr->unknown_chunk.data); png_ptr->unknown_chunk.data = NULL; } # ifdef PNG_SET_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_malloc_max > 0 && png_ptr->user_chunk_malloc_max < limit) limit = png_ptr->user_chunk_malloc_max; # elif PNG_USER_CHUNK_MALLOC_MAX > 0 if (PNG_USER_CHUNK_MALLOC_MAX < limit) limit = PNG_USER_CHUNK_MALLOC_MAX; # endif if (length <= limit) { PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name); /* The following is safe because of the PNG_SIZE_MAX init above */ png_ptr->unknown_chunk.size = (size_t)length/*SAFE*/; /* 'mode' is a flag array, only the bottom four bits matter here */ png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/; if (length == 0) png_ptr->unknown_chunk.data = NULL; else { /* Do a 'warn' here - it is handled below. */ png_ptr->unknown_chunk.data = png_voidcast(png_bytep, png_malloc_warn(png_ptr, length)); } } if (png_ptr->unknown_chunk.data == NULL && length > 0) { /* This is benign because we clean up correctly */ png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits"); return 0; } else { if (length > 0) png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length); png_crc_finish(png_ptr, 0); return 1; } } #endif /* READ_UNKNOWN_CHUNKS */ /* Handle an unknown, or known but disabled, chunk */ void /* PRIVATE */ png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length, int keep) { int handled = 0; /* the chunk was handled */ png_debug(1, "in png_handle_unknown"); #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing * the bug which meant that setting a non-default behavior for a specific * chunk would be ignored (the default was always used unless a user * callback was installed). * * 'keep' is the value from the png_chunk_unknown_handling, the setting for * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here. * This is just an optimization to avoid multiple calls to the lookup * function. */ # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name); # endif # endif /* One of the following methods will read the chunk or skip it (at least one * of these is always defined because this is the only way to switch on * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) */ # ifdef PNG_READ_USER_CHUNKS_SUPPORTED /* The user callback takes precedence over the chunk keep value, but the * keep value is still required to validate a save of a critical chunk. */ if (png_ptr->read_user_chunk_fn != NULL) { if (png_cache_unknown_chunk(png_ptr, length) != 0) { /* Callback to user unknown chunk handler */ int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr, &png_ptr->unknown_chunk); /* ret is: * negative: An error occurred; png_chunk_error will be called. * zero: The chunk was not handled, the chunk will be discarded * unless png_set_keep_unknown_chunks has been used to set * a 'keep' behavior for this particular chunk, in which * case that will be used. A critical chunk will cause an * error at this point unless it is to be saved. * positive: The chunk was handled, libpng will ignore/discard it. */ if (ret < 0) png_chunk_error(png_ptr, "error in user chunk"); else if (ret == 0) { /* If the keep value is 'default' or 'never' override it, but * still error out on critical chunks unless the keep value is * 'always' While this is weird it is the behavior in 1.4.12. * A possible improvement would be to obey the value set for the * chunk, but this would be an API change that would probably * damage some applications. * * The png_app_warning below catches the case that matters, where * the application has not set specific save or ignore for this * chunk or global save or ignore. */ if (keep < PNG_HANDLE_CHUNK_IF_SAFE) { # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE) { png_chunk_warning(png_ptr, "Saving unknown chunk:"); png_app_warning(png_ptr, "forcing save of an unhandled chunk;" " please call png_set_keep_unknown_chunks"); /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */ } # endif keep = PNG_HANDLE_CHUNK_IF_SAFE; } } else /* chunk was handled */ { handled = 1; /* Critical chunks can be safely discarded at this point. */ keep = PNG_HANDLE_CHUNK_NEVER; } } else keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */ } else /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */ # endif /* READ_USER_CHUNKS */ # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED { /* keep is currently just the per-chunk setting, if there was no * setting change it to the global default now (not that this may * still be AS_DEFAULT) then obtain the cache of the chunk if required, * if not simply skip the chunk. */ if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT) keep = png_ptr->unknown_default; if (keep == PNG_HANDLE_CHUNK_ALWAYS || (keep == PNG_HANDLE_CHUNK_IF_SAFE && PNG_CHUNK_ANCILLARY(png_ptr->chunk_name))) { if (png_cache_unknown_chunk(png_ptr, length) == 0) keep = PNG_HANDLE_CHUNK_NEVER; } else png_crc_finish(png_ptr, length); } # else # ifndef PNG_READ_USER_CHUNKS_SUPPORTED # error no method to support READ_UNKNOWN_CHUNKS # endif { /* If here there is no read callback pointer set and no support is * compiled in to just save the unknown chunks, so simply skip this * chunk. If 'keep' is something other than AS_DEFAULT or NEVER then * the app has erroneously asked for unknown chunk saving when there * is no support. */ if (keep > PNG_HANDLE_CHUNK_NEVER) png_app_error(png_ptr, "no unknown chunk support available"); png_crc_finish(png_ptr, length); } # endif # ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED /* Now store the chunk in the chunk list if appropriate, and if the limits * permit it. */ if (keep == PNG_HANDLE_CHUNK_ALWAYS || (keep == PNG_HANDLE_CHUNK_IF_SAFE && PNG_CHUNK_ANCILLARY(png_ptr->chunk_name))) { # ifdef PNG_USER_LIMITS_SUPPORTED switch (png_ptr->user_chunk_cache_max) { case 2: png_ptr->user_chunk_cache_max = 1; png_chunk_benign_error(png_ptr, "no space in chunk cache"); /* FALLTHROUGH */ case 1: /* NOTE: prior to 1.6.0 this case resulted in an unknown critical * chunk being skipped, now there will be a hard error below. */ break; default: /* not at limit */ --(png_ptr->user_chunk_cache_max); /* FALLTHROUGH */ case 0: /* no limit */ # endif /* USER_LIMITS */ /* Here when the limit isn't reached or when limits are compiled * out; store the chunk. */ png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1); handled = 1; # ifdef PNG_USER_LIMITS_SUPPORTED break; } # endif } # else /* no store support: the chunk must be handled by the user callback */ PNG_UNUSED(info_ptr) # endif /* Regardless of the error handling below the cached data (if any) can be * freed now. Notice that the data is not freed if there is a png_error, but * it will be freed by destroy_read_struct. */ if (png_ptr->unknown_chunk.data != NULL) png_free(png_ptr, png_ptr->unknown_chunk.data); png_ptr->unknown_chunk.data = NULL; #else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */ /* There is no support to read an unknown chunk, so just skip it. */ png_crc_finish(png_ptr, length); PNG_UNUSED(info_ptr) PNG_UNUSED(keep) #endif /* !READ_UNKNOWN_CHUNKS */ /* Check for unhandled critical chunks */ if (handled == 0 && PNG_CHUNK_CRITICAL(png_ptr->chunk_name)) png_chunk_error(png_ptr, "unhandled critical chunk"); } /* This function is called to verify that a chunk name is valid. * This function can't have the "critical chunk check" incorporated * into it, since in the future we will need to be able to call user * functions to handle unknown critical chunks after we check that * the chunk name itself is valid. */ /* Bit hacking: the test for an invalid byte in the 4 byte chunk name is: * * ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97)) */ void /* PRIVATE */ png_check_chunk_name(png_const_structrp png_ptr, const png_uint_32 chunk_name) { int i; png_uint_32 cn=chunk_name; png_debug(1, "in png_check_chunk_name"); for (i=1; i<=4; ++i) { int c = cn & 0xff; if (c < 65 || c > 122 || (c > 90 && c < 97)) png_chunk_error(png_ptr, "invalid chunk type"); cn >>= 8; } } void /* PRIVATE */ png_check_chunk_length(png_const_structrp png_ptr, const png_uint_32 length) { png_alloc_size_t limit = PNG_UINT_31_MAX; # ifdef PNG_SET_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_malloc_max > 0 && png_ptr->user_chunk_malloc_max < limit) limit = png_ptr->user_chunk_malloc_max; # elif PNG_USER_CHUNK_MALLOC_MAX > 0 if (PNG_USER_CHUNK_MALLOC_MAX < limit) limit = PNG_USER_CHUNK_MALLOC_MAX; # endif if (png_ptr->chunk_name == png_IDAT) { png_alloc_size_t idat_limit = PNG_UINT_31_MAX; size_t row_factor = (png_ptr->width * png_ptr->channels * (png_ptr->bit_depth > 8? 2: 1) + 1 + (png_ptr->interlaced? 6: 0)); if (png_ptr->height > PNG_UINT_32_MAX/row_factor) idat_limit=PNG_UINT_31_MAX; else idat_limit = png_ptr->height * row_factor; row_factor = row_factor > 32566? 32566 : row_factor; idat_limit += 6 + 5*(idat_limit/row_factor+1); /* zlib+deflate overhead */ idat_limit=idat_limit < PNG_UINT_31_MAX? idat_limit : PNG_UINT_31_MAX; limit = limit < idat_limit? idat_limit : limit; } if (length > limit) { png_debug2(0," length = %lu, limit = %lu", (unsigned long)length,(unsigned long)limit); png_chunk_error(png_ptr, "chunk data is too large"); } } /* Combines the row recently read in with the existing pixels in the row. This * routine takes care of alpha and transparency if requested. This routine also * handles the two methods of progressive display of interlaced images, * depending on the 'display' value; if 'display' is true then the whole row * (dp) is filled from the start by replicating the available pixels. If * 'display' is false only those pixels present in the pass are filled in. */ void /* PRIVATE */ png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display) { unsigned int pixel_depth = png_ptr->transformed_pixel_depth; png_const_bytep sp = png_ptr->row_buf + 1; png_alloc_size_t row_width = png_ptr->width; unsigned int pass = png_ptr->pass; png_bytep end_ptr = 0; png_byte end_byte = 0; unsigned int end_mask; png_debug(1, "in png_combine_row"); /* Added in 1.5.6: it should not be possible to enter this routine until at * least one row has been read from the PNG data and transformed. */ if (pixel_depth == 0) png_error(png_ptr, "internal row logic error"); /* Added in 1.5.4: the pixel depth should match the information returned by * any call to png_read_update_info at this point. Do not continue if we got * this wrong. */ if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes != PNG_ROWBYTES(pixel_depth, row_width)) png_error(png_ptr, "internal row size calculation error"); /* Don't expect this to ever happen: */ if (row_width == 0) png_error(png_ptr, "internal row width error"); /* Preserve the last byte in cases where only part of it will be overwritten, * the multiply below may overflow, we don't care because ANSI-C guarantees * we get the low bits. */ end_mask = (pixel_depth * row_width) & 7; if (end_mask != 0) { /* end_ptr == NULL is a flag to say do nothing */ end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1; end_byte = *end_ptr; # ifdef PNG_READ_PACKSWAP_SUPPORTED if ((png_ptr->transformations & PNG_PACKSWAP) != 0) /* little-endian byte */ end_mask = (unsigned int)(0xff << end_mask); else /* big-endian byte */ # endif end_mask = 0xff >> end_mask; /* end_mask is now the bits to *keep* from the destination row */ } /* For non-interlaced images this reduces to a memcpy(). A memcpy() * will also happen if interlacing isn't supported or if the application * does not call png_set_interlace_handling(). In the latter cases the * caller just gets a sequence of the unexpanded rows from each interlace * pass. */ #ifdef PNG_READ_INTERLACING_SUPPORTED if (png_ptr->interlaced != 0 && (png_ptr->transformations & PNG_INTERLACE) != 0 && pass < 6 && (display == 0 || /* The following copies everything for 'display' on passes 0, 2 and 4. */ (display == 1 && (pass & 1) != 0))) { /* Narrow images may have no bits in a pass; the caller should handle * this, but this test is cheap: */ if (row_width <= PNG_PASS_START_COL(pass)) return; if (pixel_depth < 8) { /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit * into 32 bits, then a single loop over the bytes using the four byte * values in the 32-bit mask can be used. For the 'display' option the * expanded mask may also not require any masking within a byte. To * make this work the PACKSWAP option must be taken into account - it * simply requires the pixels to be reversed in each byte. * * The 'regular' case requires a mask for each of the first 6 passes, * the 'display' case does a copy for the even passes in the range * 0..6. This has already been handled in the test above. * * The masks are arranged as four bytes with the first byte to use in * the lowest bits (little-endian) regardless of the order (PACKSWAP or * not) of the pixels in each byte. * * NOTE: the whole of this logic depends on the caller of this function * only calling it on rows appropriate to the pass. This function only * understands the 'x' logic; the 'y' logic is handled by the caller. * * The following defines allow generation of compile time constant bit * masks for each pixel depth and each possibility of swapped or not * swapped bytes. Pass 'p' is in the range 0..6; 'x', a pixel index, * is in the range 0..7; and the result is 1 if the pixel is to be * copied in the pass, 0 if not. 'S' is for the sparkle method, 'B' * for the block method. * * With some compilers a compile time expression of the general form: * * (shift >= 32) ? (a >> (shift-32)) : (b >> shift) * * Produces warnings with values of 'shift' in the range 33 to 63 * because the right hand side of the ?: expression is evaluated by * the compiler even though it isn't used. Microsoft Visual C (various * versions) and the Intel C compiler are known to do this. To avoid * this the following macros are used in 1.5.6. This is a temporary * solution to avoid destabilizing the code during the release process. */ # if PNG_USE_COMPILE_TIME_MASKS # define PNG_LSR(x,s) ((x)>>((s) & 0x1f)) # define PNG_LSL(x,s) ((x)<<((s) & 0x1f)) # else # define PNG_LSR(x,s) ((x)>>(s)) # define PNG_LSL(x,s) ((x)<<(s)) # endif # define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\ PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1) # define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\ PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1) /* Return a mask for pass 'p' pixel 'x' at depth 'd'. The mask is * little endian - the first pixel is at bit 0 - however the extra * parameter 's' can be set to cause the mask position to be swapped * within each byte, to match the PNG format. This is done by XOR of * the shift with 7, 6 or 4 for bit depths 1, 2 and 4. */ # define PIXEL_MASK(p,x,d,s) \ (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0)))) /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask. */ # define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0) # define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0) /* Combine 8 of these to get the full mask. For the 1-bpp and 2-bpp * cases the result needs replicating, for the 4-bpp case the above * generates a full 32 bits. */ # define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1))) # define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\ S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\ S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d) # define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\ B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\ B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d) #if PNG_USE_COMPILE_TIME_MASKS /* Utility macros to construct all the masks for a depth/swap * combination. The 's' parameter says whether the format is PNG * (big endian bytes) or not. Only the three odd-numbered passes are * required for the display/block algorithm. */ # define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\ S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) } # define B_MASKS(d,s) { B_MASK(1,d,s), B_MASK(3,d,s), B_MASK(5,d,s) } # define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2)) /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and * then pass: */ static PNG_CONST png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] = { /* Little-endian byte masks for PACKSWAP */ { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) }, /* Normal (big-endian byte) masks - PNG format */ { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) } }; /* display_mask has only three entries for the odd passes, so index by * pass>>1. */ static PNG_CONST png_uint_32 display_mask[2][3][3] = { /* Little-endian byte masks for PACKSWAP */ { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) }, /* Normal (big-endian byte) masks - PNG format */ { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) } }; # define MASK(pass,depth,display,png)\ ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\ row_mask[png][DEPTH_INDEX(depth)][pass]) #else /* !PNG_USE_COMPILE_TIME_MASKS */ /* This is the runtime alternative: it seems unlikely that this will * ever be either smaller or faster than the compile time approach. */ # define MASK(pass,depth,display,png)\ ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png)) #endif /* !USE_COMPILE_TIME_MASKS */ /* Use the appropriate mask to copy the required bits. In some cases * the byte mask will be 0 or 0xff; optimize these cases. row_width is * the number of pixels, but the code copies bytes, so it is necessary * to special case the end. */ png_uint_32 pixels_per_byte = 8 / pixel_depth; png_uint_32 mask; # ifdef PNG_READ_PACKSWAP_SUPPORTED if ((png_ptr->transformations & PNG_PACKSWAP) != 0) mask = MASK(pass, pixel_depth, display, 0); else # endif mask = MASK(pass, pixel_depth, display, 1); for (;;) { png_uint_32 m; /* It doesn't matter in the following if png_uint_32 has more than * 32 bits because the high bits always match those in m<<24; it is, * however, essential to use OR here, not +, because of this. */ m = mask; mask = (m >> 8) | (m << 24); /* rotate right to good compilers */ m &= 0xff; if (m != 0) /* something to copy */ { if (m != 0xff) *dp = (png_byte)((*dp & ~m) | (*sp & m)); else *dp = *sp; } /* NOTE: this may overwrite the last byte with garbage if the image * is not an exact number of bytes wide; libpng has always done * this. */ if (row_width <= pixels_per_byte) break; /* May need to restore part of the last byte */ row_width -= pixels_per_byte; ++dp; ++sp; } } else /* pixel_depth >= 8 */ { unsigned int bytes_to_copy, bytes_to_jump; /* Validate the depth - it must be a multiple of 8 */ if (pixel_depth & 7) png_error(png_ptr, "invalid user transform pixel depth"); pixel_depth >>= 3; /* now in bytes */ row_width *= pixel_depth; /* Regardless of pass number the Adam 7 interlace always results in a * fixed number of pixels to copy then to skip. There may be a * different number of pixels to skip at the start though. */ { unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth; row_width -= offset; dp += offset; sp += offset; } /* Work out the bytes to copy. */ if (display != 0) { /* When doing the 'block' algorithm the pixel in the pass gets * replicated to adjacent pixels. This is why the even (0,2,4,6) * passes are skipped above - the entire expanded row is copied. */ bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth; /* But don't allow this number to exceed the actual row width. */ if (bytes_to_copy > row_width) bytes_to_copy = (unsigned int)/*SAFE*/row_width; } else /* normal row; Adam7 only ever gives us one pixel to copy. */ bytes_to_copy = pixel_depth; /* In Adam7 there is a constant offset between where the pixels go. */ bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth; /* And simply copy these bytes. Some optimization is possible here, * depending on the value of 'bytes_to_copy'. Special case the low * byte counts, which we know to be frequent. * * Notice that these cases all 'return' rather than 'break' - this * avoids an unnecessary test on whether to restore the last byte * below. */ switch (bytes_to_copy) { case 1: for (;;) { *dp = *sp; if (row_width <= bytes_to_jump) return; dp += bytes_to_jump; sp += bytes_to_jump; row_width -= bytes_to_jump; } case 2: /* There is a possibility of a partial copy at the end here; this * slows the code down somewhat. */ do { dp[0] = sp[0]; dp[1] = sp[1]; if (row_width <= bytes_to_jump) return; sp += bytes_to_jump; dp += bytes_to_jump; row_width -= bytes_to_jump; } while (row_width > 1); /* And there can only be one byte left at this point: */ *dp = *sp; return; case 3: /* This can only be the RGB case, so each copy is exactly one * pixel and it is not necessary to check for a partial copy. */ for (;;) { dp[0] = sp[0]; dp[1] = sp[1]; dp[2] = sp[2]; if (row_width <= bytes_to_jump) return; sp += bytes_to_jump; dp += bytes_to_jump; row_width -= bytes_to_jump; } default: #if PNG_ALIGN_TYPE != PNG_ALIGN_NONE /* Check for double byte alignment and, if possible, use a * 16-bit copy. Don't attempt this for narrow images - ones that * are less than an interlace panel wide. Don't attempt it for * wide bytes_to_copy either - use the memcpy there. */ if (bytes_to_copy < 16 /*else use memcpy*/ && png_isaligned(dp, png_uint_16) && png_isaligned(sp, png_uint_16) && bytes_to_copy % (sizeof (png_uint_16)) == 0 && bytes_to_jump % (sizeof (png_uint_16)) == 0) { /* Everything is aligned for png_uint_16 copies, but try for * png_uint_32 first. */ if (png_isaligned(dp, png_uint_32) && png_isaligned(sp, png_uint_32) && bytes_to_copy % (sizeof (png_uint_32)) == 0 && bytes_to_jump % (sizeof (png_uint_32)) == 0) { png_uint_32p dp32 = png_aligncast(png_uint_32p,dp); png_const_uint_32p sp32 = png_aligncastconst( png_const_uint_32p, sp); size_t skip = (bytes_to_jump-bytes_to_copy) / (sizeof (png_uint_32)); do { size_t c = bytes_to_copy; do { *dp32++ = *sp32++; c -= (sizeof (png_uint_32)); } while (c > 0); if (row_width <= bytes_to_jump) return; dp32 += skip; sp32 += skip; row_width -= bytes_to_jump; } while (bytes_to_copy <= row_width); /* Get to here when the row_width truncates the final copy. * There will be 1-3 bytes left to copy, so don't try the * 16-bit loop below. */ dp = (png_bytep)dp32; sp = (png_const_bytep)sp32; do *dp++ = *sp++; while (--row_width > 0); return; } /* Else do it in 16-bit quantities, but only if the size is * not too large. */ else { png_uint_16p dp16 = png_aligncast(png_uint_16p, dp); png_const_uint_16p sp16 = png_aligncastconst( png_const_uint_16p, sp); size_t skip = (bytes_to_jump-bytes_to_copy) / (sizeof (png_uint_16)); do { size_t c = bytes_to_copy; do { *dp16++ = *sp16++; c -= (sizeof (png_uint_16)); } while (c > 0); if (row_width <= bytes_to_jump) return; dp16 += skip; sp16 += skip; row_width -= bytes_to_jump; } while (bytes_to_copy <= row_width); /* End of row - 1 byte left, bytes_to_copy > row_width: */ dp = (png_bytep)dp16; sp = (png_const_bytep)sp16; do *dp++ = *sp++; while (--row_width > 0); return; } } #endif /* ALIGN_TYPE code */ /* The true default - use a memcpy: */ for (;;) { memcpy(dp, sp, bytes_to_copy); if (row_width <= bytes_to_jump) return; sp += bytes_to_jump; dp += bytes_to_jump; row_width -= bytes_to_jump; if (bytes_to_copy > row_width) bytes_to_copy = (unsigned int)/*SAFE*/row_width; } } /* NOT REACHED*/ } /* pixel_depth >= 8 */ /* Here if pixel_depth < 8 to check 'end_ptr' below. */ } else #endif /* READ_INTERLACING */ /* If here then the switch above wasn't used so just memcpy the whole row * from the temporary row buffer (notice that this overwrites the end of the * destination row if it is a partial byte.) */ memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width)); /* Restore the overwritten bits from the last byte if necessary. */ if (end_ptr != NULL) *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask)); } #ifdef PNG_READ_INTERLACING_SUPPORTED void /* PRIVATE */ png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass, png_uint_32 transformations /* Because these may affect the byte layout */) { /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Offset to next interlace block */ static PNG_CONST unsigned int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; png_debug(1, "in png_do_read_interlace"); if (row != NULL && row_info != NULL) { png_uint_32 final_width; final_width = row_info->width * png_pass_inc[pass]; switch (row_info->pixel_depth) { case 1: { png_bytep sp = row + (size_t)((row_info->width - 1) >> 3); png_bytep dp = row + (size_t)((final_width - 1) >> 3); unsigned int sshift, dshift; unsigned int s_start, s_end; int s_inc; int jstop = (int)png_pass_inc[pass]; png_byte v; png_uint_32 i; int j; #ifdef PNG_READ_PACKSWAP_SUPPORTED if ((transformations & PNG_PACKSWAP) != 0) { sshift = ((row_info->width + 7) & 0x07); dshift = ((final_width + 7) & 0x07); s_start = 7; s_end = 0; s_inc = -1; } else #endif { sshift = 7 - ((row_info->width + 7) & 0x07); dshift = 7 - ((final_width + 7) & 0x07); s_start = 0; s_end = 7; s_inc = 1; } for (i = 0; i < row_info->width; i++) { v = (png_byte)((*sp >> sshift) & 0x01); for (j = 0; j < jstop; j++) { unsigned int tmp = *dp & (0x7f7f >> (7 - dshift)); tmp |= (unsigned int)(v << dshift); *dp = (png_byte)(tmp & 0xff); if (dshift == s_end) { dshift = s_start; dp--; } else dshift = (unsigned int)((int)dshift + s_inc); } if (sshift == s_end) { sshift = s_start; sp--; } else sshift = (unsigned int)((int)sshift + s_inc); } break; } case 2: { png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2); png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2); unsigned int sshift, dshift; unsigned int s_start, s_end; int s_inc; int jstop = (int)png_pass_inc[pass]; png_uint_32 i; #ifdef PNG_READ_PACKSWAP_SUPPORTED if ((transformations & PNG_PACKSWAP) != 0) { sshift = (((row_info->width + 3) & 0x03) << 1); dshift = (((final_width + 3) & 0x03) << 1); s_start = 6; s_end = 0; s_inc = -2; } else #endif { sshift = ((3 - ((row_info->width + 3) & 0x03)) << 1); dshift = ((3 - ((final_width + 3) & 0x03)) << 1); s_start = 0; s_end = 6; s_inc = 2; } for (i = 0; i < row_info->width; i++) { png_byte v; int j; v = (png_byte)((*sp >> sshift) & 0x03); for (j = 0; j < jstop; j++) { unsigned int tmp = *dp & (0x3f3f >> (6 - dshift)); tmp |= (unsigned int)(v << dshift); *dp = (png_byte)(tmp & 0xff); if (dshift == s_end) { dshift = s_start; dp--; } else dshift = (unsigned int)((int)dshift + s_inc); } if (sshift == s_end) { sshift = s_start; sp--; } else sshift = (unsigned int)((int)sshift + s_inc); } break; } case 4: { png_bytep sp = row + (size_t)((row_info->width - 1) >> 1); png_bytep dp = row + (size_t)((final_width - 1) >> 1); unsigned int sshift, dshift; unsigned int s_start, s_end; int s_inc; png_uint_32 i; int jstop = (int)png_pass_inc[pass]; #ifdef PNG_READ_PACKSWAP_SUPPORTED if ((transformations & PNG_PACKSWAP) != 0) { sshift = (((row_info->width + 1) & 0x01) << 2); dshift = (((final_width + 1) & 0x01) << 2); s_start = 4; s_end = 0; s_inc = -4; } else #endif { sshift = ((1 - ((row_info->width + 1) & 0x01)) << 2); dshift = ((1 - ((final_width + 1) & 0x01)) << 2); s_start = 0; s_end = 4; s_inc = 4; } for (i = 0; i < row_info->width; i++) { png_byte v = (png_byte)((*sp >> sshift) & 0x0f); int j; for (j = 0; j < jstop; j++) { unsigned int tmp = *dp & (0xf0f >> (4 - dshift)); tmp |= (unsigned int)(v << dshift); *dp = (png_byte)(tmp & 0xff); if (dshift == s_end) { dshift = s_start; dp--; } else dshift = (unsigned int)((int)dshift + s_inc); } if (sshift == s_end) { sshift = s_start; sp--; } else sshift = (unsigned int)((int)sshift + s_inc); } break; } default: { size_t pixel_bytes = (row_info->pixel_depth >> 3); png_bytep sp = row + (size_t)(row_info->width - 1) * pixel_bytes; png_bytep dp = row + (size_t)(final_width - 1) * pixel_bytes; int jstop = (int)png_pass_inc[pass]; png_uint_32 i; for (i = 0; i < row_info->width; i++) { png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */ int j; memcpy(v, sp, pixel_bytes); for (j = 0; j < jstop; j++) { memcpy(dp, v, pixel_bytes); dp -= pixel_bytes; } sp -= pixel_bytes; } break; } } row_info->width = final_width; row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width); } #ifndef PNG_READ_PACKSWAP_SUPPORTED PNG_UNUSED(transformations) /* Silence compiler warning */ #endif } #endif /* READ_INTERLACING */ static void png_read_filter_row_sub(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { size_t i; size_t istop = row_info->rowbytes; unsigned int bpp = (row_info->pixel_depth + 7) >> 3; png_bytep rp = row + bpp; PNG_UNUSED(prev_row) for (i = bpp; i < istop; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff); rp++; } } static void png_read_filter_row_up(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { size_t i; size_t istop = row_info->rowbytes; png_bytep rp = row; png_const_bytep pp = prev_row; for (i = 0; i < istop; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); rp++; } } static void png_read_filter_row_avg(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { size_t i; png_bytep rp = row; png_const_bytep pp = prev_row; unsigned int bpp = (row_info->pixel_depth + 7) >> 3; size_t istop = row_info->rowbytes - bpp; for (i = 0; i < bpp; i++) { *rp = (png_byte)(((int)(*rp) + ((int)(*pp++) / 2 )) & 0xff); rp++; } for (i = 0; i < istop; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff); rp++; } } static void png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_bytep rp_end = row + row_info->rowbytes; int a, c; /* First pixel/byte */ c = *prev_row++; a = *row + c; *row++ = (png_byte)a; /* Remainder */ while (row < rp_end) { int b, pa, pb, pc, p; a &= 0xff; /* From previous iteration or start */ b = *prev_row++; p = b - c; pc = a - c; #ifdef PNG_USE_ABS pa = abs(p); pb = abs(pc); pc = abs(p + pc); #else pa = p < 0 ? -p : p; pb = pc < 0 ? -pc : pc; pc = (p + pc) < 0 ? -(p + pc) : p + pc; #endif /* Find the best predictor, the least of pa, pb, pc favoring the earlier * ones in the case of a tie. */ if (pb < pa) { pa = pb; a = b; } if (pc < pa) a = c; /* Calculate the current pixel in a, and move the previous row pixel to c * for the next time round the loop */ c = b; a += *row; *row++ = (png_byte)a; } } static void png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { unsigned int bpp = (row_info->pixel_depth + 7) >> 3; png_bytep rp_end = row + bpp; /* Process the first pixel in the row completely (this is the same as 'up' * because there is only one candidate predictor for the first row). */ while (row < rp_end) { int a = *row + *prev_row++; *row++ = (png_byte)a; } /* Remainder */ rp_end = rp_end + (row_info->rowbytes - bpp); while (row < rp_end) { int a, b, c, pa, pb, pc, p; c = *(prev_row - bpp); a = *(row - bpp); b = *prev_row++; p = b - c; pc = a - c; #ifdef PNG_USE_ABS pa = abs(p); pb = abs(pc); pc = abs(p + pc); #else pa = p < 0 ? -p : p; pb = pc < 0 ? -pc : pc; pc = (p + pc) < 0 ? -(p + pc) : p + pc; #endif if (pb < pa) { pa = pb; a = b; } if (pc < pa) a = c; a += *row; *row++ = (png_byte)a; } } static void png_init_filter_functions(png_structrp pp) /* This function is called once for every PNG image (except for PNG images * that only use PNG_FILTER_VALUE_NONE for all rows) to set the * implementations required to reverse the filtering of PNG rows. Reversing * the filter is the first transformation performed on the row data. It is * performed in place, therefore an implementation can be selected based on * the image pixel format. If the implementation depends on image width then * take care to ensure that it works correctly if the image is interlaced - * interlacing causes the actual row width to vary. */ { unsigned int bpp = (pp->pixel_depth + 7) >> 3; pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub; pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up; pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg; if (bpp == 1) pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = png_read_filter_row_paeth_1byte_pixel; else pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = png_read_filter_row_paeth_multibyte_pixel; #ifdef PNG_FILTER_OPTIMIZATIONS /* To use this define PNG_FILTER_OPTIMIZATIONS as the name of a function to * call to install hardware optimizations for the above functions; simply * replace whatever elements of the pp->read_filter[] array with a hardware * specific (or, for that matter, generic) optimization. * * To see an example of this examine what configure.ac does when * --enable-arm-neon is specified on the command line. */ PNG_FILTER_OPTIMIZATIONS(pp, bpp); #endif } void /* PRIVATE */ png_read_filter_row(png_structrp pp, png_row_infop row_info, png_bytep row, png_const_bytep prev_row, int filter) { /* OPTIMIZATION: DO NOT MODIFY THIS FUNCTION, instead #define * PNG_FILTER_OPTIMIZATIONS to a function that overrides the generic * implementations. See png_init_filter_functions above. */ if (filter > PNG_FILTER_VALUE_NONE && filter < PNG_FILTER_VALUE_LAST) { if (pp->read_filter[0] == NULL) png_init_filter_functions(pp); pp->read_filter[filter-1](row_info, row, prev_row); } } #ifdef PNG_SEQUENTIAL_READ_SUPPORTED void /* PRIVATE */ png_read_IDAT_data(png_structrp png_ptr, png_bytep output, png_alloc_size_t avail_out) { /* Loop reading IDATs and decompressing the result into output[avail_out] */ png_ptr->zstream.next_out = output; png_ptr->zstream.avail_out = 0; /* safety: set below */ if (output == NULL) avail_out = 0; do { int ret; png_byte tmpbuf[PNG_INFLATE_BUF_SIZE]; if (png_ptr->zstream.avail_in == 0) { uInt avail_in; png_bytep buffer; while (png_ptr->idat_size == 0) { png_crc_finish(png_ptr, 0); png_ptr->idat_size = png_read_chunk_header(png_ptr); /* This is an error even in the 'check' case because the code just * consumed a non-IDAT header. */ if (png_ptr->chunk_name != png_IDAT) png_error(png_ptr, "Not enough image data"); } avail_in = png_ptr->IDAT_read_size; if (avail_in > png_ptr->idat_size) avail_in = (uInt)png_ptr->idat_size; /* A PNG with a gradually increasing IDAT size will defeat this attempt * to minimize memory usage by causing lots of re-allocs, but * realistically doing IDAT_read_size re-allocs is not likely to be a * big problem. */ buffer = png_read_buffer(png_ptr, avail_in, 0/*error*/); png_crc_read(png_ptr, buffer, avail_in); png_ptr->idat_size -= avail_in; png_ptr->zstream.next_in = buffer; png_ptr->zstream.avail_in = avail_in; } /* And set up the output side. */ if (output != NULL) /* standard read */ { uInt out = ZLIB_IO_MAX; if (out > avail_out) out = (uInt)avail_out; avail_out -= out; png_ptr->zstream.avail_out = out; } else /* after last row, checking for end */ { png_ptr->zstream.next_out = tmpbuf; png_ptr->zstream.avail_out = (sizeof tmpbuf); } /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the * process. If the LZ stream is truncated the sequential reader will * terminally damage the stream, above, by reading the chunk header of the * following chunk (it then exits with png_error). * * TODO: deal more elegantly with truncated IDAT lists. */ ret = PNG_INFLATE(png_ptr, Z_NO_FLUSH); /* Take the unconsumed output back. */ if (output != NULL) avail_out += png_ptr->zstream.avail_out; else /* avail_out counts the extra bytes */ avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out; png_ptr->zstream.avail_out = 0; if (ret == Z_STREAM_END) { /* Do this for safety; we won't read any more into this row. */ png_ptr->zstream.next_out = NULL; png_ptr->mode |= PNG_AFTER_IDAT; png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED; if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0) png_chunk_benign_error(png_ptr, "Extra compressed data"); break; } if (ret != Z_OK) { png_zstream_error(png_ptr, ret); if (output != NULL) png_chunk_error(png_ptr, png_ptr->zstream.msg); else /* checking */ { png_chunk_benign_error(png_ptr, png_ptr->zstream.msg); return; } } } while (avail_out > 0); if (avail_out > 0) { /* The stream ended before the image; this is the same as too few IDATs so * should be handled the same way. */ if (output != NULL) png_error(png_ptr, "Not enough image data"); else /* the deflate stream contained extra data */ png_chunk_benign_error(png_ptr, "Too much image data"); } } void /* PRIVATE */ png_read_finish_IDAT(png_structrp png_ptr) { /* We don't need any more data and the stream should have ended, however the * LZ end code may actually not have been processed. In this case we must * read it otherwise stray unread IDAT data or, more likely, an IDAT chunk * may still remain to be consumed. */ if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0) { /* The NULL causes png_read_IDAT_data to swallow any remaining bytes in * the compressed stream, but the stream may be damaged too, so even after * this call we may need to terminate the zstream ownership. */ png_read_IDAT_data(png_ptr, NULL, 0); png_ptr->zstream.next_out = NULL; /* safety */ /* Now clear everything out for safety; the following may not have been * done. */ if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0) { png_ptr->mode |= PNG_AFTER_IDAT; png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED; } } /* If the zstream has not been released do it now *and* terminate the reading * of the final IDAT chunk. */ if (png_ptr->zowner == png_IDAT) { /* Always do this; the pointers otherwise point into the read buffer. */ png_ptr->zstream.next_in = NULL; png_ptr->zstream.avail_in = 0; /* Now we no longer own the zstream. */ png_ptr->zowner = 0; /* The slightly weird semantics of the sequential IDAT reading is that we * are always in or at the end of an IDAT chunk, so we always need to do a * crc_finish here. If idat_size is non-zero we also need to read the * spurious bytes at the end of the chunk now. */ (void)png_crc_finish(png_ptr, png_ptr->idat_size); } } void /* PRIVATE */ png_read_finish_row(png_structrp png_ptr) { /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; png_debug(1, "in png_read_finish_row"); png_ptr->row_number++; if (png_ptr->row_number < png_ptr->num_rows) return; if (png_ptr->interlaced != 0) { png_ptr->row_number = 0; /* TO DO: don't do this if prev_row isn't needed (requires * read-ahead of the next row's filter byte. */ memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1); do { png_ptr->pass++; if (png_ptr->pass >= 7) break; png_ptr->iwidth = (png_ptr->width + png_pass_inc[png_ptr->pass] - 1 - png_pass_start[png_ptr->pass]) / png_pass_inc[png_ptr->pass]; if ((png_ptr->transformations & PNG_INTERLACE) == 0) { png_ptr->num_rows = (png_ptr->height + png_pass_yinc[png_ptr->pass] - 1 - png_pass_ystart[png_ptr->pass]) / png_pass_yinc[png_ptr->pass]; } else /* if (png_ptr->transformations & PNG_INTERLACE) */ break; /* libpng deinterlacing sees every row */ } while (png_ptr->num_rows == 0 || png_ptr->iwidth == 0); if (png_ptr->pass < 7) return; } /* Here after at the end of the last row of the last pass. */ png_read_finish_IDAT(png_ptr); } #endif /* SEQUENTIAL_READ */ void /* PRIVATE */ png_read_start_row(png_structrp png_ptr) { /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; unsigned int max_pixel_depth; size_t row_bytes; png_debug(1, "in png_read_start_row"); #ifdef PNG_READ_TRANSFORMS_SUPPORTED png_init_read_transformations(png_ptr); #endif if (png_ptr->interlaced != 0) { if ((png_ptr->transformations & PNG_INTERLACE) == 0) png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 - png_pass_ystart[0]) / png_pass_yinc[0]; else png_ptr->num_rows = png_ptr->height; png_ptr->iwidth = (png_ptr->width + png_pass_inc[png_ptr->pass] - 1 - png_pass_start[png_ptr->pass]) / png_pass_inc[png_ptr->pass]; } else { png_ptr->num_rows = png_ptr->height; png_ptr->iwidth = png_ptr->width; } max_pixel_depth = (unsigned int)png_ptr->pixel_depth; /* WARNING: * png_read_transform_info (pngrtran.c) performs a simpler set of * calculations to calculate the final pixel depth, then * png_do_read_transforms actually does the transforms. This means that the * code which effectively calculates this value is actually repeated in three * separate places. They must all match. Innocent changes to the order of * transformations can and will break libpng in a way that causes memory * overwrites. * * TODO: fix this. */ #ifdef PNG_READ_PACK_SUPPORTED if ((png_ptr->transformations & PNG_PACK) != 0 && png_ptr->bit_depth < 8) max_pixel_depth = 8; #endif #ifdef PNG_READ_EXPAND_SUPPORTED if ((png_ptr->transformations & PNG_EXPAND) != 0) { if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if (png_ptr->num_trans != 0) max_pixel_depth = 32; else max_pixel_depth = 24; } else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) { if (max_pixel_depth < 8) max_pixel_depth = 8; if (png_ptr->num_trans != 0) max_pixel_depth *= 2; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) { if (png_ptr->num_trans != 0) { max_pixel_depth *= 4; max_pixel_depth /= 3; } } } #endif #ifdef PNG_READ_EXPAND_16_SUPPORTED if ((png_ptr->transformations & PNG_EXPAND_16) != 0) { # ifdef PNG_READ_EXPAND_SUPPORTED /* In fact it is an error if it isn't supported, but checking is * the safe way. */ if ((png_ptr->transformations & PNG_EXPAND) != 0) { if (png_ptr->bit_depth < 16) max_pixel_depth *= 2; } else # endif png_ptr->transformations &= ~PNG_EXPAND_16; } #endif #ifdef PNG_READ_FILLER_SUPPORTED if ((png_ptr->transformations & (PNG_FILLER)) != 0) { if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) { if (max_pixel_depth <= 8) max_pixel_depth = 16; else max_pixel_depth = 32; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB || png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if (max_pixel_depth <= 32) max_pixel_depth = 32; else max_pixel_depth = 64; } } #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0) { if ( #ifdef PNG_READ_EXPAND_SUPPORTED (png_ptr->num_trans != 0 && (png_ptr->transformations & PNG_EXPAND) != 0) || #endif #ifdef PNG_READ_FILLER_SUPPORTED (png_ptr->transformations & (PNG_FILLER)) != 0 || #endif png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (max_pixel_depth <= 16) max_pixel_depth = 32; else max_pixel_depth = 64; } else { if (max_pixel_depth <= 8) { if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA) max_pixel_depth = 32; else max_pixel_depth = 24; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA) max_pixel_depth = 64; else max_pixel_depth = 48; } } #endif #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \ defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0) { unsigned int user_pixel_depth = png_ptr->user_transform_depth * png_ptr->user_transform_channels; if (user_pixel_depth > max_pixel_depth) max_pixel_depth = user_pixel_depth; } #endif /* This value is stored in png_struct and double checked in the row read * code. */ png_ptr->maximum_pixel_depth = (png_byte)max_pixel_depth; png_ptr->transformed_pixel_depth = 0; /* calculated on demand */ /* Align the width on the next larger 8 pixels. Mainly used * for interlacing */ row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7)); /* Calculate the maximum bytes needed, adding a byte and a pixel * for safety's sake */ row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) + 1 + ((max_pixel_depth + 7) >> 3U); #ifdef PNG_MAX_MALLOC_64K if (row_bytes > (png_uint_32)65536L) png_error(png_ptr, "This image requires a row greater than 64KB"); #endif if (row_bytes + 48 > png_ptr->old_big_row_buf_size) { png_free(png_ptr, png_ptr->big_row_buf); png_free(png_ptr, png_ptr->big_prev_row); if (png_ptr->interlaced != 0) png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr, row_bytes + 48); else png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 48); png_ptr->big_prev_row = (png_bytep)png_malloc(png_ptr, row_bytes + 48); #ifdef PNG_ALIGNED_MEMORY_SUPPORTED /* Use 16-byte aligned memory for row_buf with at least 16 bytes * of padding before and after row_buf; treat prev_row similarly. * NOTE: the alignment is to the start of the pixels, one beyond the start * of the buffer, because of the filter byte. Prior to libpng 1.5.6 this * was incorrect; the filter byte was aligned, which had the exact * opposite effect of that intended. */ { png_bytep temp = png_ptr->big_row_buf + 32; int extra = (int)((temp - (png_bytep)0) & 0x0f); png_ptr->row_buf = temp - extra - 1/*filter byte*/; temp = png_ptr->big_prev_row + 32; extra = (int)((temp - (png_bytep)0) & 0x0f); png_ptr->prev_row = temp - extra - 1/*filter byte*/; } #else /* Use 31 bytes of padding before and 17 bytes after row_buf. */ png_ptr->row_buf = png_ptr->big_row_buf + 31; png_ptr->prev_row = png_ptr->big_prev_row + 31; #endif png_ptr->old_big_row_buf_size = row_bytes + 48; } #ifdef PNG_MAX_MALLOC_64K if (png_ptr->rowbytes > 65535) png_error(png_ptr, "This image requires a row greater than 64KB"); #endif if (png_ptr->rowbytes > (PNG_SIZE_MAX - 1)) png_error(png_ptr, "Row has too many bytes to allocate in memory"); memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1); png_debug1(3, "width = %u,", png_ptr->width); png_debug1(3, "height = %u,", png_ptr->height); png_debug1(3, "iwidth = %u,", png_ptr->iwidth); png_debug1(3, "num_rows = %u,", png_ptr->num_rows); png_debug1(3, "rowbytes = %lu,", (unsigned long)png_ptr->rowbytes); png_debug1(3, "irowbytes = %lu", (unsigned long)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1); /* The sequential reader needs a buffer for IDAT, but the progressive reader * does not, so free the read buffer now regardless; the sequential reader * reallocates it on demand. */ if (png_ptr->read_buffer != NULL) { png_bytep buffer = png_ptr->read_buffer; png_ptr->read_buffer_size = 0; png_ptr->read_buffer = NULL; png_free(png_ptr, buffer); } /* Finally claim the zstream for the inflate of the IDAT data, use the bits * value from the stream (note that this will result in a fatal error if the * IDAT stream has a bogus deflate header window_bits value, but this should * not be happening any longer!) */ if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK) png_error(png_ptr, png_ptr->zstream.msg); png_ptr->flags |= PNG_FLAG_ROW_INIT; } #endif /* READ */
./CrossVul/dataset_final_sorted/CWE-369/c/bad_225_0
crossvul-cpp_data_bad_951_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % L AAA Y Y EEEEE RRRR % % L A A Y Y E R R % % L AAAAA Y EEE RRRR % % L A A Y E R R % % LLLLL A A Y EEEEE R R % % % % MagickCore Image Layering Methods % % % % Software Design % % Cristy % % Anthony Thyssen % % January 2006 % % % % % % Copyright 1999-2019 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://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/artifact.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/composite.h" #include "MagickCore/effect.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/profile.h" #include "MagickCore/resource_.h" #include "MagickCore/resize.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l e a r B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClearBounds() Clear the area specified by the bounds in an image to % transparency. This typically used to handle Background Disposal for the % previous frame in an animation sequence. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % void ClearBounds(Image *image,RectangleInfo *bounds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to had the area cleared in % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static void ClearBounds(Image *image,RectangleInfo *bounds, ExceptionInfo *exception) { ssize_t y; if (bounds->x < 0) return; if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); for (y=0; y < (ssize_t) bounds->height; y++) { register ssize_t x; register Quantum *magick_restrict q; q=GetAuthenticPixels(image,bounds->x,bounds->y+y,bounds->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) bounds->width; x++) { SetPixelAlpha(image,TransparentAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s B o u n d s C l e a r e d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsBoundsCleared() tests whether any pixel in the bounds given, gets cleared % when going from the first image to the second image. This typically used % to check if a proposed disposal method will work successfully to generate % the second frame image from the first disposed form of the previous frame. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % MagickBooleanType IsBoundsCleared(const Image *image1, % const Image *image2,RectangleInfo bounds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image1, image 2: the images to check for cleared pixels % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsBoundsCleared(const Image *image1, const Image *image2,RectangleInfo *bounds,ExceptionInfo *exception) { register const Quantum *p, *q; register ssize_t x; ssize_t y; if (bounds->x < 0) return(MagickFalse); for (y=0; y < (ssize_t) bounds->height; y++) { p=GetVirtualPixels(image1,bounds->x,bounds->y+y,bounds->width,1,exception); q=GetVirtualPixels(image2,bounds->x,bounds->y+y,bounds->width,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) bounds->width; x++) { if ((GetPixelAlpha(image1,p) >= (Quantum) (QuantumRange/2)) && (GetPixelAlpha(image2,q) < (Quantum) (QuantumRange/2))) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) bounds->width) break; } return(y < (ssize_t) bounds->height ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o a l e s c e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CoalesceImages() composites a set of images while respecting any page % offsets and disposal methods. GIF, MIFF, and MNG animation sequences % typically start with an image background and each subsequent image % varies in size and offset. A new image sequence is returned with all % images the same size as the first images virtual canvas and composited % with the next image in the sequence. % % The format of the CoalesceImages method is: % % Image *CoalesceImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CoalesceImages(const Image *image,ExceptionInfo *exception) { Image *coalesce_image, *dispose_image, *previous; register Image *next; RectangleInfo bounds; /* Coalesce the image sequence. */ 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); next=GetFirstImageInList(image); bounds=next->page; if (bounds.width == 0) { bounds.width=next->columns; if (bounds.x > 0) bounds.width+=bounds.x; } if (bounds.height == 0) { bounds.height=next->rows; if (bounds.y > 0) bounds.height+=bounds.y; } bounds.x=0; bounds.y=0; coalesce_image=CloneImage(next,bounds.width,bounds.height,MagickTrue, exception); if (coalesce_image == (Image *) NULL) return((Image *) NULL); coalesce_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(coalesce_image,exception); coalesce_image->alpha_trait=next->alpha_trait; coalesce_image->page=bounds; coalesce_image->dispose=NoneDispose; /* Coalesce rest of the images. */ dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); (void) CompositeImage(coalesce_image,next,CopyCompositeOp,MagickTrue, next->page.x,next->page.y,exception); next=GetNextImageInList(next); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { /* Determine the bounds that was overlaid in the previous image. */ previous=GetPreviousImageInList(next); bounds=previous->page; bounds.width=previous->columns; bounds.height=previous->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) coalesce_image->columns) bounds.width=coalesce_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) coalesce_image->rows) bounds.height=coalesce_image->rows-bounds.y; /* Replace the dispose image with the new coalesced image. */ if (GetPreviousImageInList(next)->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); if (dispose_image == (Image *) NULL) { coalesce_image=DestroyImageList(coalesce_image); return((Image *) NULL); } } /* Clear the overlaid area of the coalesced bounds for background disposal */ if (next->previous->dispose == BackgroundDispose) ClearBounds(dispose_image,&bounds,exception); /* Next image is the dispose image, overlaid with next frame in sequence. */ coalesce_image->next=CloneImage(dispose_image,0,0,MagickTrue,exception); coalesce_image->next->previous=coalesce_image; previous=coalesce_image; coalesce_image=GetNextImageInList(coalesce_image); (void) CompositeImage(coalesce_image,next, next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp, MagickTrue,next->page.x,next->page.y,exception); (void) CloneImageProfiles(coalesce_image,next); (void) CloneImageProperties(coalesce_image,next); (void) CloneImageArtifacts(coalesce_image,next); coalesce_image->page=previous->page; /* If a pixel goes opaque to transparent, use background dispose. */ if (IsBoundsCleared(previous,coalesce_image,&bounds,exception) != MagickFalse) coalesce_image->dispose=BackgroundDispose; else coalesce_image->dispose=NoneDispose; previous->dispose=coalesce_image->dispose; } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(coalesce_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D i s p o s e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisposeImages() returns the coalesced frames of a GIF animation as it would % appear after the GIF dispose method of that frame has been applied. That is % it returned the appearance of each frame before the next is overlaid. % % The format of the DisposeImages method is: % % Image *DisposeImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *DisposeImages(const Image *images,ExceptionInfo *exception) { Image *dispose_image, *dispose_images; RectangleInfo bounds; register Image *image, *next; /* Run the image through the animation sequence */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(images); dispose_image=CloneImage(image,image->page.width,image->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return((Image *) NULL); dispose_image->page=image->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(dispose_image,exception); dispose_images=NewImageList(); for (next=image; image != (Image *) NULL; image=GetNextImageInList(image)) { Image *current_image; /* Overlay this frame's image over the previous disposal image. */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } (void) CompositeImage(current_image,next, next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp, MagickTrue,next->page.x,next->page.y,exception); /* Handle Background dispose: image is displayed for the delay period. */ if (next->dispose == BackgroundDispose) { bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds,exception); } /* Select the appropriate previous/disposed image. */ if (next->dispose == PreviousDispose) current_image=DestroyImage(current_image); else { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; current_image=(Image *) NULL; } /* Save the dispose image just calculated for return. */ { Image *dispose; dispose=CloneImage(dispose_image,0,0,MagickTrue,exception); if (dispose == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } (void) CloneImageProfiles(dispose,next); (void) CloneImageProperties(dispose,next); (void) CloneImageArtifacts(dispose,next); dispose->page.x=0; dispose->page.y=0; dispose->dispose=next->dispose; AppendImageToList(&dispose_images,dispose); } } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(dispose_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComparePixels() Compare the two pixels and return true if the pixels % differ according to the given LayerType comparision method. % % This currently only used internally by CompareImagesBounds(). It is % doubtful that this sub-routine will be useful outside this module. % % The format of the ComparePixels method is: % % MagickBooleanType *ComparePixels(const LayerMethod method, % const PixelInfo *p,const PixelInfo *q) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o p, q: the pixels to test for appropriate differences. % */ static MagickBooleanType ComparePixels(const LayerMethod method, const PixelInfo *p,const PixelInfo *q) { double o1, o2; /* Any change in pixel values */ if (method == CompareAnyLayer) return((MagickBooleanType)(IsFuzzyEquivalencePixelInfo(p,q) == MagickFalse)); o1 = (p->alpha_trait != UndefinedPixelTrait) ? p->alpha : OpaqueAlpha; o2 = (q->alpha_trait != UndefinedPixelTrait) ? q->alpha : OpaqueAlpha; /* Pixel goes from opaque to transprency. */ if (method == CompareClearLayer) return((MagickBooleanType) ( (o1 >= ((double) QuantumRange/2.0)) && (o2 < ((double) QuantumRange/2.0)) ) ); /* Overlay would change first pixel by second. */ if (method == CompareOverlayLayer) { if (o2 < ((double) QuantumRange/2.0)) return MagickFalse; return((MagickBooleanType) (IsFuzzyEquivalencePixelInfo(p,q) == MagickFalse)); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e I m a g e B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImagesBounds() Given two images return the smallest rectangular area % by which the two images differ, accourding to the given 'Compare...' % layer method. % % This currently only used internally in this module, but may eventually % be used by other modules. % % The format of the CompareImagesBounds method is: % % RectangleInfo *CompareImagesBounds(const LayerMethod method, % const Image *image1,const Image *image2,ExceptionInfo *exception) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of CompareAnyLayer, % CompareClearLayer, CompareOverlayLayer. % % o image1, image2: the two images to compare. % % o exception: return any errors or warnings in this structure. % */ static RectangleInfo CompareImagesBounds(const Image *image1, const Image *image2,const LayerMethod method,ExceptionInfo *exception) { RectangleInfo bounds; PixelInfo pixel1, pixel2; register const Quantum *p, *q; register ssize_t x; ssize_t y; /* Set bounding box of the differences between images. */ GetPixelInfo(image1,&pixel1); GetPixelInfo(image2,&pixel2); for (x=0; x < (ssize_t) image1->columns; x++) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (y=0; y < (ssize_t) image1->rows; y++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (y < (ssize_t) image1->rows) break; } if (x >= (ssize_t) image1->columns) { /* Images are identical, return a null image. */ bounds.x=-1; bounds.y=-1; bounds.width=1; bounds.height=1; return(bounds); } bounds.x=x; for (x=(ssize_t) image1->columns-1; x >= 0; x--) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (y=0; y < (ssize_t) image1->rows; y++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (y < (ssize_t) image1->rows) break; } bounds.width=(size_t) (x-bounds.x+1); for (y=0; y < (ssize_t) image1->rows; y++) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image1->columns; x++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) image1->columns) break; } bounds.y=y; for (y=(ssize_t) image1->rows-1; y >= 0; y--) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image1->columns; x++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) image1->columns) break; } bounds.height=(size_t) (y-bounds.y+1); return(bounds); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p a r e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImagesLayers() compares each image with the next in a sequence and % returns the minimum bounding region of all the pixel differences (of the % LayerMethod specified) it discovers. % % Images do NOT have to be the same size, though it is best that all the % images are 'coalesced' (images are all the same size, on a flattened % canvas, so as to represent exactly how an specific frame should look). % % No GIF dispose methods are applied, so GIF animations must be coalesced % before applying this image operator to find differences to them. % % The format of the CompareImagesLayers method is: % % Image *CompareImagesLayers(const Image *images, % const LayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers type to compare images with. Must be one of... % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CompareImagesLayers(const Image *image, const LayerMethod method,ExceptionInfo *exception) { Image *image_a, *image_b, *layers; RectangleInfo *bounds; register const Image *next; register ssize_t i; assert(image != (const 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); assert((method == CompareAnyLayer) || (method == CompareClearLayer) || (method == CompareOverlayLayer)); /* Allocate bounds memory. */ next=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(next),sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Set up first comparision images. */ image_a=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (image_a == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_a->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(image_a,exception); image_a->page=next->page; image_a->page.x=0; image_a->page.y=0; (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); /* Compute the bounding box of changes for the later images */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { image_b=CloneImage(image_a,0,0,MagickTrue,exception); if (image_b == (Image *) NULL) { image_a=DestroyImage(image_a); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); bounds[i]=CompareImagesBounds(image_b,image_a,method,exception); image_b=DestroyImage(image_b); i++; } image_a=DestroyImage(image_a); /* Clone first image in sequence. */ next=GetFirstImageInList(image); layers=CloneImage(next,0,0,MagickTrue,exception); if (layers == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } /* Deconstruct the image sequence. */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { if ((bounds[i].x == -1) && (bounds[i].y == -1) && (bounds[i].width == 1) && (bounds[i].height == 1)) { /* An empty frame is returned from CompareImageBounds(), which means the current frame is identical to the previous frame. */ i++; continue; } image_a=CloneImage(next,0,0,MagickTrue,exception); if (image_a == (Image *) NULL) break; image_b=CropImage(image_a,&bounds[i],exception); image_a=DestroyImage(image_a); if (image_b == (Image *) NULL) break; AppendImageToList(&layers,image_b); i++; } bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); if (next != (Image *) NULL) { layers=DestroyImageList(layers); return((Image *) NULL); } return(GetFirstImageInList(layers)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p t i m i z e L a y e r F r a m e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeLayerFrames() takes a coalesced GIF animation, and compares each % frame against the three different 'disposal' forms of the previous frame. % From this it then attempts to select the smallest cropped image and % disposal method needed to reproduce the resulting image. % % Note that this not easy, and may require the expansion of the bounds % of previous frame, simply clear pixels for the next animation frame to % transparency according to the selected dispose method. % % The format of the OptimizeLayerFrames method is: % % Image *OptimizeLayerFrames(const Image *image, % const LayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers technique to optimize with. Must be one of... % OptimizeImageLayer, or OptimizePlusLayer. The Plus form allows % the addition of extra 'zero delay' frames to clear pixels from % the previous frame, and the removal of frames that done change, % merging the delay times together. % % o exception: return any errors or warnings in this structure. % */ /* Define a 'fake' dispose method where the frame is duplicated, (for OptimizePlusLayer) with a extra zero time delay frame which does a BackgroundDisposal to clear the pixels that need to be cleared. */ #define DupDispose ((DisposeType)9) /* Another 'fake' dispose method used to removed frames that don't change. */ #define DelDispose ((DisposeType)8) #define DEBUG_OPT_FRAME 0 static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method, ExceptionInfo *exception) { ExceptionInfo *sans_exception; Image *prev_image, *dup_image, *bgnd_image, *optimized_image; RectangleInfo try_bounds, bgnd_bounds, dup_bounds, *bounds; MagickBooleanType add_frames, try_cleared, cleared; DisposeType *disposals; register const Image *curr; register ssize_t i; assert(image != (const 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); assert(method == OptimizeLayer || method == OptimizeImageLayer || method == OptimizePlusLayer); /* Are we allowed to add/remove frames from animation? */ add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse; /* Ensure all the images are the same size. */ curr=GetFirstImageInList(image); for (; curr != (Image *) NULL; curr=GetNextImageInList(curr)) { if ((curr->columns != image->columns) || (curr->rows != image->rows)) ThrowImageException(OptionError,"ImagesAreNotTheSameSize"); if ((curr->page.x != 0) || (curr->page.y != 0) || (curr->page.width != image->page.width) || (curr->page.height != image->page.height)) ThrowImageException(OptionError,"ImagePagesAreNotCoalesced"); } /* Allocate memory (times 2 if we allow the use of frame duplications) */ curr=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); disposals=(DisposeType *) AcquireQuantumMemory((size_t) GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*disposals)); if (disposals == (DisposeType *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialise Previous Image as fully transparent */ prev_image=CloneImage(curr,curr->columns,curr->rows,MagickTrue,exception); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */ prev_image->page.x=0; prev_image->page.y=0; prev_image->dispose=NoneDispose; prev_image->background_color.alpha_trait=BlendPixelTrait; prev_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(prev_image,exception); /* Figure out the area of overlay of the first frame No pixel could be cleared as all pixels are already cleared. */ #if DEBUG_OPT_FRAME i=0; (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif disposals[0]=NoneDispose; bounds[0]=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g\n\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); #endif /* Compute the bounding box of changes for each pair of images. */ i=1; bgnd_image=(Image *) NULL; dup_image=(Image *) NULL; dup_bounds.width=0; dup_bounds.height=0; dup_bounds.x=0; dup_bounds.y=0; curr=GetNextImageInList(curr); for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr)) { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif /* Assume none disposal is the best */ bounds[i]=CompareImagesBounds(curr->previous,curr,CompareAnyLayer,exception); cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception); disposals[i-1]=NoneDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g%s%s\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y, bounds[i].x < 0?" (unchanged)":"", cleared?" (pixels cleared)":""); #endif if ( bounds[i].x < 0 ) { /* Image frame is exactly the same as the previous frame! If not adding frames leave it to be cropped down to a null image. Otherwise mark previous image for deleted, transfering its crop bounds to the current image. */ if ( add_frames && i>=2 ) { disposals[i-1]=DelDispose; disposals[i]=NoneDispose; bounds[i]=bounds[i-1]; i++; continue; } } else { /* Compare a none disposal against a previous disposal */ try_bounds=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "test_prev: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels were cleared)":""); #endif if ( (!try_cleared && cleared ) || try_bounds.width * try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=try_cleared; bounds[i]=try_bounds; disposals[i-1]=PreviousDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"previous: accepted\n"); } else { (void) FormatLocaleFile(stderr,"previous: rejected\n"); #endif } /* If we are allowed lets try a complex frame duplication. It is useless if the previous image already clears pixels correctly. This method will always clear all the pixels that need to be cleared. */ dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */ if ( add_frames ) { dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (dup_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); return((Image *) NULL); } dup_bounds=CompareImagesBounds(dup_image,curr,CompareClearLayer,exception); ClearBounds(dup_image,&dup_bounds,exception); try_bounds=CompareImagesBounds(dup_image,curr,CompareAnyLayer,exception); if ( cleared || dup_bounds.width*dup_bounds.height +try_bounds.width*try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=MagickFalse; bounds[i]=try_bounds; disposals[i-1]=DupDispose; /* to be finalised later, if found to be optimial */ } else dup_bounds.width=dup_bounds.height=0; } /* Now compare against a simple background disposal */ bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (bgnd_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); return((Image *) NULL); } bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */ ClearBounds(bgnd_image,&bgnd_bounds,exception); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "background: %s\n", try_cleared?"(pixels cleared)":""); #endif if ( try_cleared ) { /* Straight background disposal failed to clear pixels needed! Lets try expanding the disposal area of the previous frame, to include the pixels that are cleared. This guaranteed to work, though may not be the most optimized solution. */ try_bounds=CompareImagesBounds(curr->previous,curr,CompareClearLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_clear: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_bounds.x<0?" (no expand nessary)":""); #endif if ( bgnd_bounds.x < 0 ) bgnd_bounds = try_bounds; else { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_bgnd: %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif if ( try_bounds.x < bgnd_bounds.x ) { bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; bgnd_bounds.x = try_bounds.x; } else { try_bounds.width += try_bounds.x - bgnd_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; } if ( try_bounds.y < bgnd_bounds.y ) { bgnd_bounds.height += bgnd_bounds.y - try_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; bgnd_bounds.y = try_bounds.y; } else { try_bounds.height += try_bounds.y - bgnd_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; } #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, " to : %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif } ClearBounds(bgnd_image,&bgnd_bounds,exception); #if DEBUG_OPT_FRAME /* Something strange is happening with a specific animation * CompareAnyLayers (normal method) and CompareClearLayers returns the whole * image, which is not posibly correct! As verified by previous tests. * Something changed beyond the bgnd_bounds clearing. But without being able * to see, or writet he image at this point it is hard to tell what is wrong! * Only CompareOverlay seemed to return something sensible. */ try_bounds=CompareImagesBounds(bgnd_image,curr,CompareClearLayer,exception); (void) FormatLocaleFile(stderr, "expand_ctst: %.20gx%.20g%+.20g%+.20g\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y ); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_any : %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif try_bounds=CompareImagesBounds(bgnd_image,curr,CompareOverlayLayer,exception); #if DEBUG_OPT_FRAME try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_test: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif } /* Test if this background dispose is smaller than any of the other methods we tryed before this (including duplicated frame) */ if ( cleared || bgnd_bounds.width*bgnd_bounds.height +try_bounds.width*try_bounds.height < bounds[i-1].width*bounds[i-1].height +dup_bounds.width*dup_bounds.height +bounds[i].width*bounds[i].height ) { cleared=MagickFalse; bounds[i-1]=bgnd_bounds; bounds[i]=try_bounds; if ( disposals[i-1] == DupDispose ) dup_image=DestroyImage(dup_image); disposals[i-1]=BackgroundDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"expand_bgnd: accepted\n"); } else { (void) FormatLocaleFile(stderr,"expand_bgnd: reject\n"); #endif } } /* Finalise choice of dispose, set new prev_image, and junk any extra images as appropriate, */ if ( disposals[i-1] == DupDispose ) { if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); prev_image=DestroyImage(prev_image); prev_image=dup_image, dup_image=(Image *) NULL; bounds[i+1]=bounds[i]; bounds[i]=dup_bounds; disposals[i-1]=DupDispose; disposals[i]=BackgroundDispose; i++; } else { if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); if ( disposals[i-1] != PreviousDispose ) prev_image=DestroyImage(prev_image); if ( disposals[i-1] == BackgroundDispose ) prev_image=bgnd_image, bgnd_image=(Image *) NULL; if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); if ( disposals[i-1] == NoneDispose ) { prev_image=ReferenceImage(curr->previous); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } } } assert(prev_image != (Image *) NULL); disposals[i]=disposals[i-1]; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "final %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i-1, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]), (double) bounds[i-1].width,(double) bounds[i-1].height, (double) bounds[i-1].x,(double) bounds[i-1].y ); #endif #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "interum %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]), (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); (void) FormatLocaleFile(stderr,"\n"); #endif i++; } prev_image=DestroyImage(prev_image); /* Optimize all images in sequence. */ sans_exception=AcquireExceptionInfo(); i=0; curr=GetFirstImageInList(image); optimized_image=NewImageList(); while ( curr != (const Image *) NULL ) { prev_image=CloneImage(curr,0,0,MagickTrue,exception); if (prev_image == (Image *) NULL) break; if (prev_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(prev_image,OpaqueAlphaChannel,exception); if ( disposals[i] == DelDispose ) { size_t time = 0; while ( disposals[i] == DelDispose ) { time += curr->delay*1000/curr->ticks_per_second; curr=GetNextImageInList(curr); i++; } time += curr->delay*1000/curr->ticks_per_second; prev_image->ticks_per_second = 100L; prev_image->delay = time*prev_image->ticks_per_second/1000; } bgnd_image=CropImage(prev_image,&bounds[i],sans_exception); prev_image=DestroyImage(prev_image); if (bgnd_image == (Image *) NULL) break; bgnd_image->dispose=disposals[i]; if ( disposals[i] == DupDispose ) { bgnd_image->delay=0; bgnd_image->dispose=NoneDispose; } else curr=GetNextImageInList(curr); AppendImageToList(&optimized_image,bgnd_image); i++; } sans_exception=DestroyExceptionInfo(sans_exception); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); if (curr != (Image *) NULL) { optimized_image=DestroyImageList(optimized_image); return((Image *) NULL); } return(GetFirstImageInList(optimized_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageLayers() compares each image the GIF disposed forms of the % previous image in the sequence. From this it attempts to select the % smallest cropped image to replace each frame, while preserving the results % of the GIF animation. % % The format of the OptimizeImageLayers method is: % % Image *OptimizeImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizeImageLayers(const Image *image, ExceptionInfo *exception) { return(OptimizeLayerFrames(image,OptimizeImageLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e P l u s I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImagePlusLayers() is exactly as OptimizeImageLayers(), but may % also add or even remove extra frames in the animation, if it improves % the total number of pixels in the resulting GIF animation. % % The format of the OptimizePlusImageLayers method is: % % Image *OptimizePlusImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizePlusImageLayers(const Image *image, ExceptionInfo *exception) { return OptimizeLayerFrames(image,OptimizePlusLayer,exception); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e T r a n s p a r e n c y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageTransparency() takes a frame optimized GIF animation, and % compares the overlayed pixels against the disposal image resulting from all % the previous frames in the animation. Any pixel that does not change the % disposal image (and thus does not effect the outcome of an overlay) is made % transparent. % % WARNING: This modifies the current images directly, rather than generate % a new image sequence. % % The format of the OptimizeImageTransperency method is: % % void OptimizeImageTransperency(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence % % o exception: return any errors or warnings in this structure. % */ MagickExport void OptimizeImageTransparency(const Image *image, ExceptionInfo *exception) { Image *dispose_image; register Image *next; /* Run the image through the animation sequence */ 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); next=GetFirstImageInList(image); dispose_image=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return; dispose_image->page=next->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.alpha_trait=BlendPixelTrait; dispose_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(dispose_image,exception); while ( next != (Image *) NULL ) { Image *current_image; /* Overlay this frame's image over the previous disposal image */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_image=DestroyImage(dispose_image); return; } (void) CompositeImage(current_image,next,next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp,MagickTrue,next->page.x,next->page.y, exception); /* At this point the image would be displayed, for the delay period ** Work out the disposal of the previous image */ if (next->dispose == BackgroundDispose) { RectangleInfo bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds,exception); } if (next->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; } else current_image=DestroyImage(current_image); /* Optimize Transparency of the next frame (if present) */ next=GetNextImageInList(next); if (next != (Image *) NULL) { (void) CompositeImage(next,dispose_image,ChangeMaskCompositeOp, MagickTrue,-(next->page.x),-(next->page.y),exception); } } dispose_image=DestroyImage(dispose_image); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e D u p l i c a t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveDuplicateLayers() removes any image that is exactly the same as the % next image in the given image list. Image size and virtual canvas offset % must also match, though not the virtual canvas size itself. % % No check is made with regards to image disposal setting, though it is the % dispose setting of later image that is kept. Also any time delays are also % added together. As such coalesced image animations should still produce the % same result, though with duplicte frames merged into a single frame. % % The format of the RemoveDuplicateLayers method is: % % void RemoveDuplicateLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveDuplicateLayers(Image **images, ExceptionInfo *exception) { register Image *curr, *next; RectangleInfo bounds; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); curr=GetFirstImageInList(*images); for (; (next=GetNextImageInList(curr)) != (Image *) NULL; curr=next) { if ( curr->columns != next->columns || curr->rows != next->rows || curr->page.x != next->page.x || curr->page.y != next->page.y ) continue; bounds=CompareImagesBounds(curr,next,CompareAnyLayer,exception); if ( bounds.x < 0 ) { /* the two images are the same, merge time delays and delete one. */ size_t time; time = curr->delay*1000/curr->ticks_per_second; time += next->delay*1000/next->ticks_per_second; next->ticks_per_second = 100L; next->delay = time*curr->ticks_per_second/1000; next->iterations = curr->iterations; *images = curr; (void) DeleteImageFromList(images); } } *images = GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e Z e r o D e l a y L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveZeroDelayLayers() removes any image that as a zero delay time. Such % images generally represent intermediate or partial updates in GIF % animations used for file optimization. They are not ment to be displayed % to users of the animation. Viewable images in an animation should have a % time delay of 3 or more centi-seconds (hundredths of a second). % % However if all the frames have a zero time delay, then either the animation % is as yet incomplete, or it is not a GIF animation. This a non-sensible % situation, so no image will be removed and a 'Zero Time Animation' warning % (exception) given. % % No warning will be given if no image was removed because all images had an % appropriate non-zero time delay set. % % Due to the special requirements of GIF disposal handling, GIF animations % should be coalesced first, before calling this function, though that is not % a requirement. % % The format of the RemoveZeroDelayLayers method is: % % void RemoveZeroDelayLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveZeroDelayLayers(Image **images, ExceptionInfo *exception) { Image *i; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); i=GetFirstImageInList(*images); for ( ; i != (Image *) NULL; i=GetNextImageInList(i)) if ( i->delay != 0L ) break; if ( i == (Image *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ZeroTimeAnimation","`%s'",GetFirstImageInList(*images)->filename); return; } i=GetFirstImageInList(*images); while ( i != (Image *) NULL ) { if ( i->delay == 0L ) { (void) DeleteImageFromList(&i); *images=i; } else i=GetNextImageInList(i); } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeLayers() compose the source image sequence over the destination % image sequence, starting with the current image in both lists. % % Each layer from the two image lists are composted together until the end of % one of the image lists is reached. The offset of each composition is also % adjusted to match the virtual canvas offsets of each layer. As such the % given offset is relative to the virtual canvas, and not the actual image. % % Composition uses given x and y offsets, as the 'origin' location of the % source images virtual canvas (not the real image) allowing you to compose a % list of 'layer images' into the destiantioni images. This makes it well % sutiable for directly composing 'Clears Frame Animations' or 'Coaleased % Animations' onto a static or other 'Coaleased Animation' destination image % list. GIF disposal handling is not looked at. % % Special case:- If one of the image sequences is the last image (just a % single image remaining), that image is repeatally composed with all the % images in the other image list. Either the source or destination lists may % be the single image, for this situation. % % In the case of a single destination image (or last image given), that image % will ve cloned to match the number of images remaining in the source image % list. % % This is equivelent to the "-layer Composite" Shell API operator. % % % The format of the CompositeLayers method is: % % void CompositeLayers(Image *destination, const CompositeOperator % compose, Image *source, const ssize_t x_offset, const ssize_t y_offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o destination: the destination images and results % % o source: source image(s) for the layer composition % % o compose, x_offset, y_offset: arguments passed on to CompositeImages() % % o exception: return any errors or warnings in this structure. % */ static inline void CompositeCanvas(Image *destination, const CompositeOperator compose,Image *source,ssize_t x_offset, ssize_t y_offset,ExceptionInfo *exception) { const char *value; x_offset+=source->page.x-destination->page.x; y_offset+=source->page.y-destination->page.y; value=GetImageArtifact(source,"compose:outside-overlay"); (void) CompositeImage(destination,source,compose, (value != (const char *) NULL) && (IsStringTrue(value) != MagickFalse) ? MagickFalse : MagickTrue,x_offset,y_offset,exception); } MagickExport void CompositeLayers(Image *destination, const CompositeOperator compose, Image *source,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { assert(destination != (Image *) NULL); assert(destination->signature == MagickCoreSignature); assert(source != (Image *) NULL); assert(source->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (source->debug != MagickFalse || destination->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s - %s", source->filename,destination->filename); /* Overlay single source image over destation image/list */ if ( source->next == (Image *) NULL ) while ( destination != (Image *) NULL ) { CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); destination=GetNextImageInList(destination); } /* Overlay source image list over single destination. Multiple clones of destination image are created to match source list. Original Destination image becomes first image of generated list. As such the image list pointer does not require any change in caller. Some animation attributes however also needs coping in this case. */ else if ( destination->next == (Image *) NULL ) { Image *dest = CloneImage(destination,0,0,MagickTrue,exception); CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); /* copy source image attributes ? */ if ( source->next != (Image *) NULL ) { destination->delay = source->delay; destination->iterations = source->iterations; } source=GetNextImageInList(source); while ( source != (Image *) NULL ) { AppendImageToList(&destination, CloneImage(dest,0,0,MagickTrue,exception)); destination=GetLastImageInList(destination); CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); destination->delay = source->delay; destination->iterations = source->iterations; source=GetNextImageInList(source); } dest=DestroyImage(dest); } /* Overlay a source image list over a destination image list until either list runs out of images. (Does not repeat) */ else while ( source != (Image *) NULL && destination != (Image *) NULL ) { CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); source=GetNextImageInList(source); destination=GetNextImageInList(destination); } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e r g e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MergeImageLayers() composes all the image layers from the current given % image onward to produce a single image of the merged layers. % % The inital canvas's size depends on the given LayerMethod, and is % initialized using the first images background color. The images % are then compositied onto that image in sequence using the given % composition that has been assigned to each individual image. % % The format of the MergeImageLayers is: % % Image *MergeImageLayers(Image *image,const LayerMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image list to be composited together % % o method: the method of selecting the size of the initial canvas. % % MergeLayer: Merge all layers onto a canvas just large enough % to hold all the actual images. The virtual canvas of the % first image is preserved but otherwise ignored. % % FlattenLayer: Use the virtual canvas size of first image. % Images which fall outside this canvas is clipped. % This can be used to 'fill out' a given virtual canvas. % % MosaicLayer: Start with the virtual canvas of the first image, % enlarging left and right edges to contain all images. % Images with negative offsets will be clipped. % % TrimBoundsLayer: Determine the overall bounds of all the image % layers just as in "MergeLayer", then adjust the the canvas % and offsets to be relative to those bounds, without overlaying % the images. % % WARNING: a new image is not returned, the original image % sequence page data is modified instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MergeImageLayers(Image *image,const LayerMethod method, ExceptionInfo *exception) { #define MergeLayersTag "Merge/Layers" Image *canvas; MagickBooleanType proceed; RectangleInfo page; register const Image *next; size_t number_images, height, width; ssize_t scene; 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); /* Determine canvas image size, and its virtual canvas size and offset */ page=image->page; width=image->columns; height=image->rows; switch (method) { case TrimBoundsLayer: case MergeLayer: default: { next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (page.x > next->page.x) { width+=page.x-next->page.x; page.x=next->page.x; } if (page.y > next->page.y) { height+=page.y-next->page.y; page.y=next->page.y; } if ((ssize_t) width < (next->page.x+(ssize_t) next->columns-page.x)) width=(size_t) next->page.x+(ssize_t) next->columns-page.x; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows-page.y)) height=(size_t) next->page.y+(ssize_t) next->rows-page.y; } break; } case FlattenLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; page.x=0; page.y=0; break; } case MosaicLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { if (method == MosaicLayer) { page.x=next->page.x; page.y=next->page.y; if ((ssize_t) width < (next->page.x+(ssize_t) next->columns)) width=(size_t) next->page.x+next->columns; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows)) height=(size_t) next->page.y+next->rows; } } page.width=width; page.height=height; page.x=0; page.y=0; } break; } /* Set virtual canvas size if not defined. */ if (page.width == 0) page.width=page.x < 0 ? width : width+page.x; if (page.height == 0) page.height=page.y < 0 ? height : height+page.y; /* Handle "TrimBoundsLayer" method separately to normal 'layer merge'. */ if (method == TrimBoundsLayer) { number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { image->page.x-=page.x; image->page.y-=page.y; image->page.width=width; image->page.height=height; proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return((Image *) NULL); } /* Create canvas size of width and height, and background color. */ canvas=CloneImage(image,width,height,MagickTrue,exception); if (canvas == (Image *) NULL) return((Image *) NULL); (void) SetImageBackgroundColor(canvas,exception); canvas->page=page; canvas->dispose=UndefinedDispose; /* Compose images onto canvas, with progress monitor */ number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { (void) CompositeImage(canvas,image,image->compose,MagickTrue,image->page.x- canvas->page.x,image->page.y-canvas->page.y,exception); proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return(canvas); }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_951_0
crossvul-cpp_data_bad_2303_3
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library Win32-specific Routines. Adapted from tif_unix.c 4/5/95 by * Scott Wagner (wagner@itek.com), Itek Graphix, Rochester, NY USA */ #include "tiffiop.h" #include <windows.h> static tmsize_t _tiffReadProc(thandle_t fd, void* buf, tmsize_t size) { /* tmsize_t is 64bit on 64bit systems, but the WinAPI ReadFile takes * 32bit sizes, so we loop through the data in suitable 32bit sized * chunks */ uint8* ma; uint64 mb; DWORD n; DWORD o; tmsize_t p; ma=(uint8*)buf; mb=size; p=0; while (mb>0) { n=0x80000000UL; if ((uint64)n>mb) n=(DWORD)mb; if (!ReadFile(fd,(LPVOID)ma,n,&o,NULL)) return(0); ma+=o; mb-=o; p+=o; if (o!=n) break; } return(p); } static tmsize_t _tiffWriteProc(thandle_t fd, void* buf, tmsize_t size) { /* tmsize_t is 64bit on 64bit systems, but the WinAPI WriteFile takes * 32bit sizes, so we loop through the data in suitable 32bit sized * chunks */ uint8* ma; uint64 mb; DWORD n; DWORD o; tmsize_t p; ma=(uint8*)buf; mb=size; p=0; while (mb>0) { n=0x80000000UL; if ((uint64)n>mb) n=(DWORD)mb; if (!WriteFile(fd,(LPVOID)ma,n,&o,NULL)) return(0); ma+=o; mb-=o; p+=o; if (o!=n) break; } return(p); } static uint64 _tiffSeekProc(thandle_t fd, uint64 off, int whence) { LARGE_INTEGER offli; DWORD dwMoveMethod; offli.QuadPart = off; switch(whence) { case SEEK_SET: dwMoveMethod = FILE_BEGIN; break; case SEEK_CUR: dwMoveMethod = FILE_CURRENT; break; case SEEK_END: dwMoveMethod = FILE_END; break; default: dwMoveMethod = FILE_BEGIN; break; } offli.LowPart=SetFilePointer(fd,offli.LowPart,&offli.HighPart,dwMoveMethod); if ((offli.LowPart==INVALID_SET_FILE_POINTER)&&(GetLastError()!=NO_ERROR)) offli.QuadPart=0; return(offli.QuadPart); } static int _tiffCloseProc(thandle_t fd) { return (CloseHandle(fd) ? 0 : -1); } static uint64 _tiffSizeProc(thandle_t fd) { ULARGE_INTEGER m; m.LowPart=GetFileSize(fd,&m.HighPart); return(m.QuadPart); } static int _tiffDummyMapProc(thandle_t fd, void** pbase, toff_t* psize) { (void) fd; (void) pbase; (void) psize; return (0); } /* * From "Hermann Josef Hill" <lhill@rhein-zeitung.de>: * * Windows uses both a handle and a pointer for file mapping, * but according to the SDK documentation and Richter's book * "Advanced Windows Programming" it is safe to free the handle * after obtaining the file mapping pointer * * This removes a nasty OS dependency and cures a problem * with Visual C++ 5.0 */ static int _tiffMapProc(thandle_t fd, void** pbase, toff_t* psize) { uint64 size; tmsize_t sizem; HANDLE hMapFile; size = _tiffSizeProc(fd); sizem = (tmsize_t)size; if ((uint64)sizem!=size) return (0); /* By passing in 0 for the maximum file size, it specifies that we create a file mapping object for the full file size. */ hMapFile = CreateFileMapping(fd, NULL, PAGE_READONLY, 0, 0, NULL); if (hMapFile == NULL) return (0); *pbase = MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0); CloseHandle(hMapFile); if (*pbase == NULL) return (0); *psize = size; return(1); } static void _tiffDummyUnmapProc(thandle_t fd, void* base, toff_t size) { (void) fd; (void) base; (void) size; } static void _tiffUnmapProc(thandle_t fd, void* base, toff_t size) { (void) fd; (void) size; UnmapViewOfFile(base); } /* * Open a TIFF file descriptor for read/writing. * Note that TIFFFdOpen and TIFFOpen recognise the character 'u' in the mode * string, which forces the file to be opened unmapped. */ TIFF* TIFFFdOpen(int ifd, const char* name, const char* mode) { TIFF* tif; int fSuppressMap; int m; fSuppressMap=0; for (m=0; mode[m]!=0; m++) { if (mode[m]=='u') { fSuppressMap=1; break; } } tif = TIFFClientOpen(name, mode, (thandle_t)ifd, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, fSuppressMap ? _tiffDummyMapProc : _tiffMapProc, fSuppressMap ? _tiffDummyUnmapProc : _tiffUnmapProc); if (tif) tif->tif_fd = ifd; return (tif); } #ifndef _WIN32_WCE /* * Open a TIFF file for read/writing. */ TIFF* TIFFOpen(const char* name, const char* mode) { static const char module[] = "TIFFOpen"; thandle_t fd; int m; DWORD dwMode; TIFF* tif; m = _TIFFgetMode(mode, module); switch(m) { case O_RDONLY: dwMode = OPEN_EXISTING; break; case O_RDWR: dwMode = OPEN_ALWAYS; break; case O_RDWR|O_CREAT: dwMode = OPEN_ALWAYS; break; case O_RDWR|O_TRUNC: dwMode = CREATE_ALWAYS; break; case O_RDWR|O_CREAT|O_TRUNC: dwMode = CREATE_ALWAYS; break; default: return ((TIFF*)0); } fd = (thandle_t)CreateFileA(name, (m == O_RDONLY)?GENERIC_READ:(GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, dwMode, (m == O_RDONLY)?FILE_ATTRIBUTE_READONLY:FILE_ATTRIBUTE_NORMAL, NULL); if (fd == INVALID_HANDLE_VALUE) { TIFFErrorExt(0, module, "%s: Cannot open", name); return ((TIFF *)0); } tif = TIFFFdOpen((int)fd, name, mode); if(!tif) CloseHandle(fd); return tif; } /* * Open a TIFF file with a Unicode filename, for read/writing. */ TIFF* TIFFOpenW(const wchar_t* name, const char* mode) { static const char module[] = "TIFFOpenW"; thandle_t fd; int m; DWORD dwMode; int mbsize; char *mbname; TIFF *tif; m = _TIFFgetMode(mode, module); switch(m) { case O_RDONLY: dwMode = OPEN_EXISTING; break; case O_RDWR: dwMode = OPEN_ALWAYS; break; case O_RDWR|O_CREAT: dwMode = OPEN_ALWAYS; break; case O_RDWR|O_TRUNC: dwMode = CREATE_ALWAYS; break; case O_RDWR|O_CREAT|O_TRUNC: dwMode = CREATE_ALWAYS; break; default: return ((TIFF*)0); } fd = (thandle_t)CreateFileW(name, (m == O_RDONLY)?GENERIC_READ:(GENERIC_READ|GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, dwMode, (m == O_RDONLY)?FILE_ATTRIBUTE_READONLY:FILE_ATTRIBUTE_NORMAL, NULL); if (fd == INVALID_HANDLE_VALUE) { TIFFErrorExt(0, module, "%S: Cannot open", name); return ((TIFF *)0); } mbname = NULL; mbsize = WideCharToMultiByte(CP_ACP, 0, name, -1, NULL, 0, NULL, NULL); if (mbsize > 0) { mbname = (char *)_TIFFmalloc(mbsize); if (!mbname) { TIFFErrorExt(0, module, "Can't allocate space for filename conversion buffer"); return ((TIFF*)0); } WideCharToMultiByte(CP_ACP, 0, name, -1, mbname, mbsize, NULL, NULL); } tif = TIFFFdOpen((int)fd, (mbname != NULL) ? mbname : "<unknown>", mode); if(!tif) CloseHandle(fd); _TIFFfree(mbname); return tif; } #endif /* ndef _WIN32_WCE */ void* _TIFFmalloc(tmsize_t s) { return (malloc((size_t) s)); } void _TIFFfree(void* p) { free(p); } void* _TIFFrealloc(void* p, tmsize_t s) { return (realloc(p, (size_t) s)); } void _TIFFmemset(void* p, int v, tmsize_t c) { memset(p, v, (size_t) c); } void _TIFFmemcpy(void* d, const void* s, tmsize_t c) { memcpy(d, s, (size_t) c); } int _TIFFmemcmp(const void* p1, const void* p2, tmsize_t c) { return (memcmp(p1, p2, (size_t) c)); } #ifndef _WIN32_WCE #if (_MSC_VER < 1500) # define vsnprintf _vsnprintf #endif static void Win32WarningHandler(const char* module, const char* fmt, va_list ap) { #ifndef TIF_PLATFORM_CONSOLE LPTSTR szTitle; LPTSTR szTmp; LPCTSTR szTitleText = "%s Warning"; LPCTSTR szDefaultModule = "LIBTIFF"; LPCTSTR szTmpModule = (module == NULL) ? szDefaultModule : module; SIZE_T nBufSize = (strlen(szTmpModule) + strlen(szTitleText) + strlen(fmt) + 256)*sizeof(char); if ((szTitle = (LPTSTR)LocalAlloc(LMEM_FIXED, nBufSize)) == NULL) return; sprintf(szTitle, szTitleText, szTmpModule); szTmp = szTitle + (strlen(szTitle)+2)*sizeof(char); vsnprintf(szTmp, nBufSize-(strlen(szTitle)+2)*sizeof(char), fmt, ap); MessageBoxA(GetFocus(), szTmp, szTitle, MB_OK | MB_ICONINFORMATION); LocalFree(szTitle); return; #else if (module != NULL) fprintf(stderr, "%s: ", module); fprintf(stderr, "Warning, "); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); #endif } TIFFErrorHandler _TIFFwarningHandler = Win32WarningHandler; static void Win32ErrorHandler(const char* module, const char* fmt, va_list ap) { #ifndef TIF_PLATFORM_CONSOLE LPTSTR szTitle; LPTSTR szTmp; LPCTSTR szTitleText = "%s Error"; LPCTSTR szDefaultModule = "LIBTIFF"; LPCTSTR szTmpModule = (module == NULL) ? szDefaultModule : module; SIZE_T nBufSize = (strlen(szTmpModule) + strlen(szTitleText) + strlen(fmt) + 256)*sizeof(char); if ((szTitle = (LPTSTR)LocalAlloc(LMEM_FIXED, nBufSize)) == NULL) return; sprintf(szTitle, szTitleText, szTmpModule); szTmp = szTitle + (strlen(szTitle)+2)*sizeof(char); vsnprintf(szTmp, nBufSize-(strlen(szTitle)+2)*sizeof(char), fmt, ap); MessageBoxA(GetFocus(), szTmp, szTitle, MB_OK | MB_ICONEXCLAMATION); LocalFree(szTitle); return; #else if (module != NULL) fprintf(stderr, "%s: ", module); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); #endif } TIFFErrorHandler _TIFFerrorHandler = Win32ErrorHandler; #endif /* ndef _WIN32_WCE */ /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-369/c/bad_2303_3
crossvul-cpp_data_good_153_1
/* * rdbmp.c * * This file was part of the Independent JPEG Group's software: * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2009-2010 by Guido Vollbeding. * libjpeg-turbo Modifications: * Modified 2011 by Siarhei Siamashka. * Copyright (C) 2015, 2017-2018, D. R. Commander. * For conditions of distribution and use, see the accompanying README.ijg * file. * * This file contains routines to read input images in Microsoft "BMP" * format (MS Windows 3.x, OS/2 1.x, and OS/2 2.x flavors). * Currently, only 8-bit and 24-bit images are supported, not 1-bit or * 4-bit (feeding such low-depth images into JPEG would be silly anyway). * Also, we don't support RLE-compressed files. * * These routines may need modification for non-Unix environments or * specialized applications. As they stand, they assume input from * an ordinary stdio stream. They further assume that reading begins * at the start of the file; start_input may need work if the * user interface has already read some data (e.g., to determine that * the file is indeed BMP format). * * This code contributed by James Arthur Boucher. */ #include "cmyk.h" #include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */ #ifdef BMP_SUPPORTED /* Macros to deal with unsigned chars as efficiently as compiler allows */ #ifdef HAVE_UNSIGNED_CHAR typedef unsigned char U_CHAR; #define UCH(x) ((int)(x)) #else /* !HAVE_UNSIGNED_CHAR */ #ifdef __CHAR_UNSIGNED__ typedef char U_CHAR; #define UCH(x) ((int)(x)) #else typedef char U_CHAR; #define UCH(x) ((int)(x) & 0xFF) #endif #endif /* HAVE_UNSIGNED_CHAR */ #define ReadOK(file, buffer, len) \ (JFREAD(file, buffer, len) == ((size_t)(len))) static int alpha_index[JPEG_NUMCS] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 3, 0, 0, -1 }; /* Private version of data source object */ typedef struct _bmp_source_struct *bmp_source_ptr; typedef struct _bmp_source_struct { struct cjpeg_source_struct pub; /* public fields */ j_compress_ptr cinfo; /* back link saves passing separate parm */ JSAMPARRAY colormap; /* BMP colormap (converted to my format) */ jvirt_sarray_ptr whole_image; /* Needed to reverse row order */ JDIMENSION source_row; /* Current source row number */ JDIMENSION row_width; /* Physical width of scanlines in file */ int bits_per_pixel; /* remembers 8- or 24-bit format */ boolean use_inversion_array; /* TRUE = preload the whole image, which is stored in bottom-up order, and feed it to the calling program in top-down order FALSE = the calling program will maintain its own image buffer and read the rows in bottom-up order */ U_CHAR *iobuffer; /* I/O buffer (used to buffer a single row from disk if use_inversion_array == FALSE) */ } bmp_source_struct; LOCAL(int) read_byte(bmp_source_ptr sinfo) /* Read next byte from BMP file */ { register FILE *infile = sinfo->pub.input_file; register int c; if ((c = getc(infile)) == EOF) ERREXIT(sinfo->cinfo, JERR_INPUT_EOF); return c; } LOCAL(void) read_colormap(bmp_source_ptr sinfo, int cmaplen, int mapentrysize) /* Read the colormap from a BMP file */ { int i, gray = 1; switch (mapentrysize) { case 3: /* BGR format (occurs in OS/2 files) */ for (i = 0; i < cmaplen; i++) { sinfo->colormap[2][i] = (JSAMPLE)read_byte(sinfo); sinfo->colormap[1][i] = (JSAMPLE)read_byte(sinfo); sinfo->colormap[0][i] = (JSAMPLE)read_byte(sinfo); if (sinfo->colormap[2][i] != sinfo->colormap[1][i] || sinfo->colormap[1][i] != sinfo->colormap[0][i]) gray = 0; } break; case 4: /* BGR0 format (occurs in MS Windows files) */ for (i = 0; i < cmaplen; i++) { sinfo->colormap[2][i] = (JSAMPLE)read_byte(sinfo); sinfo->colormap[1][i] = (JSAMPLE)read_byte(sinfo); sinfo->colormap[0][i] = (JSAMPLE)read_byte(sinfo); (void)read_byte(sinfo); if (sinfo->colormap[2][i] != sinfo->colormap[1][i] || sinfo->colormap[1][i] != sinfo->colormap[0][i]) gray = 0; } break; default: ERREXIT(sinfo->cinfo, JERR_BMP_BADCMAP); break; } if (sinfo->cinfo->in_color_space == JCS_UNKNOWN && gray) sinfo->cinfo->in_color_space = JCS_GRAYSCALE; if (sinfo->cinfo->in_color_space == JCS_GRAYSCALE && !gray) ERREXIT(sinfo->cinfo, JERR_BAD_IN_COLORSPACE); } /* * Read one row of pixels. * The image has been read into the whole_image array, but is otherwise * unprocessed. We must read it out in top-to-bottom row order, and if * it is an 8-bit image, we must expand colormapped pixels to 24bit format. */ METHODDEF(JDIMENSION) get_8bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading 8-bit colormap indexes */ { bmp_source_ptr source = (bmp_source_ptr)sinfo; register JSAMPARRAY colormap = source->colormap; JSAMPARRAY image_ptr; register int t; register JSAMPROW inptr, outptr; register JDIMENSION col; if (source->use_inversion_array) { /* Fetch next row from virtual array */ source->source_row--; image_ptr = (*cinfo->mem->access_virt_sarray) ((j_common_ptr)cinfo, source->whole_image, source->source_row, (JDIMENSION)1, FALSE); inptr = image_ptr[0]; } else { if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width)) ERREXIT(cinfo, JERR_INPUT_EOF); inptr = source->iobuffer; } /* Expand the colormap indexes to real data */ outptr = source->pub.buffer[0]; if (cinfo->in_color_space == JCS_GRAYSCALE) { for (col = cinfo->image_width; col > 0; col--) { t = GETJSAMPLE(*inptr++); *outptr++ = colormap[0][t]; } } else if (cinfo->in_color_space == JCS_CMYK) { for (col = cinfo->image_width; col > 0; col--) { t = GETJSAMPLE(*inptr++); rgb_to_cmyk(colormap[0][t], colormap[1][t], colormap[2][t], outptr, outptr + 1, outptr + 2, outptr + 3); outptr += 4; } } else { register int rindex = rgb_red[cinfo->in_color_space]; register int gindex = rgb_green[cinfo->in_color_space]; register int bindex = rgb_blue[cinfo->in_color_space]; register int aindex = alpha_index[cinfo->in_color_space]; register int ps = rgb_pixelsize[cinfo->in_color_space]; if (aindex >= 0) { for (col = cinfo->image_width; col > 0; col--) { t = GETJSAMPLE(*inptr++); outptr[rindex] = colormap[0][t]; outptr[gindex] = colormap[1][t]; outptr[bindex] = colormap[2][t]; outptr[aindex] = 0xFF; outptr += ps; } } else { for (col = cinfo->image_width; col > 0; col--) { t = GETJSAMPLE(*inptr++); outptr[rindex] = colormap[0][t]; outptr[gindex] = colormap[1][t]; outptr[bindex] = colormap[2][t]; outptr += ps; } } } return 1; } METHODDEF(JDIMENSION) get_24bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading 24-bit pixels */ { bmp_source_ptr source = (bmp_source_ptr)sinfo; JSAMPARRAY image_ptr; register JSAMPROW inptr, outptr; register JDIMENSION col; if (source->use_inversion_array) { /* Fetch next row from virtual array */ source->source_row--; image_ptr = (*cinfo->mem->access_virt_sarray) ((j_common_ptr)cinfo, source->whole_image, source->source_row, (JDIMENSION)1, FALSE); inptr = image_ptr[0]; } else { if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width)) ERREXIT(cinfo, JERR_INPUT_EOF); inptr = source->iobuffer; } /* Transfer data. Note source values are in BGR order * (even though Microsoft's own documents say the opposite). */ outptr = source->pub.buffer[0]; if (cinfo->in_color_space == JCS_EXT_BGR) { MEMCOPY(outptr, inptr, source->row_width); } else if (cinfo->in_color_space == JCS_CMYK) { for (col = cinfo->image_width; col > 0; col--) { /* can omit GETJSAMPLE() safely */ JSAMPLE b = *inptr++, g = *inptr++, r = *inptr++; rgb_to_cmyk(r, g, b, outptr, outptr + 1, outptr + 2, outptr + 3); outptr += 4; } } else { register int rindex = rgb_red[cinfo->in_color_space]; register int gindex = rgb_green[cinfo->in_color_space]; register int bindex = rgb_blue[cinfo->in_color_space]; register int aindex = alpha_index[cinfo->in_color_space]; register int ps = rgb_pixelsize[cinfo->in_color_space]; if (aindex >= 0) { for (col = cinfo->image_width; col > 0; col--) { outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */ outptr[gindex] = *inptr++; outptr[rindex] = *inptr++; outptr[aindex] = 0xFF; outptr += ps; } } else { for (col = cinfo->image_width; col > 0; col--) { outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */ outptr[gindex] = *inptr++; outptr[rindex] = *inptr++; outptr += ps; } } } return 1; } METHODDEF(JDIMENSION) get_32bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) /* This version is for reading 32-bit pixels */ { bmp_source_ptr source = (bmp_source_ptr)sinfo; JSAMPARRAY image_ptr; register JSAMPROW inptr, outptr; register JDIMENSION col; if (source->use_inversion_array) { /* Fetch next row from virtual array */ source->source_row--; image_ptr = (*cinfo->mem->access_virt_sarray) ((j_common_ptr)cinfo, source->whole_image, source->source_row, (JDIMENSION)1, FALSE); inptr = image_ptr[0]; } else { if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width)) ERREXIT(cinfo, JERR_INPUT_EOF); inptr = source->iobuffer; } /* Transfer data. Note source values are in BGR order * (even though Microsoft's own documents say the opposite). */ outptr = source->pub.buffer[0]; if (cinfo->in_color_space == JCS_EXT_BGRX || cinfo->in_color_space == JCS_EXT_BGRA) { MEMCOPY(outptr, inptr, source->row_width); } else if (cinfo->in_color_space == JCS_CMYK) { for (col = cinfo->image_width; col > 0; col--) { /* can omit GETJSAMPLE() safely */ JSAMPLE b = *inptr++, g = *inptr++, r = *inptr++; rgb_to_cmyk(r, g, b, outptr, outptr + 1, outptr + 2, outptr + 3); inptr++; /* skip the 4th byte (Alpha channel) */ outptr += 4; } } else { register int rindex = rgb_red[cinfo->in_color_space]; register int gindex = rgb_green[cinfo->in_color_space]; register int bindex = rgb_blue[cinfo->in_color_space]; register int aindex = alpha_index[cinfo->in_color_space]; register int ps = rgb_pixelsize[cinfo->in_color_space]; if (aindex >= 0) { for (col = cinfo->image_width; col > 0; col--) { outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */ outptr[gindex] = *inptr++; outptr[rindex] = *inptr++; outptr[aindex] = *inptr++; outptr += ps; } } else { for (col = cinfo->image_width; col > 0; col--) { outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */ outptr[gindex] = *inptr++; outptr[rindex] = *inptr++; inptr++; /* skip the 4th byte (Alpha channel) */ outptr += ps; } } } return 1; } /* * This method loads the image into whole_image during the first call on * get_pixel_rows. The get_pixel_rows pointer is then adjusted to call * get_8bit_row, get_24bit_row, or get_32bit_row on subsequent calls. */ METHODDEF(JDIMENSION) preload_image(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { bmp_source_ptr source = (bmp_source_ptr)sinfo; register FILE *infile = source->pub.input_file; register JSAMPROW out_ptr; JSAMPARRAY image_ptr; JDIMENSION row; cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress; /* Read the data into a virtual array in input-file row order. */ for (row = 0; row < cinfo->image_height; row++) { if (progress != NULL) { progress->pub.pass_counter = (long)row; progress->pub.pass_limit = (long)cinfo->image_height; (*progress->pub.progress_monitor) ((j_common_ptr)cinfo); } image_ptr = (*cinfo->mem->access_virt_sarray) ((j_common_ptr)cinfo, source->whole_image, row, (JDIMENSION)1, TRUE); out_ptr = image_ptr[0]; if (fread(out_ptr, 1, source->row_width, infile) != source->row_width) { if (feof(infile)) ERREXIT(cinfo, JERR_INPUT_EOF); else ERREXIT(cinfo, JERR_FILE_READ); } } if (progress != NULL) progress->completed_extra_passes++; /* Set up to read from the virtual array in top-to-bottom order */ switch (source->bits_per_pixel) { case 8: source->pub.get_pixel_rows = get_8bit_row; break; case 24: source->pub.get_pixel_rows = get_24bit_row; break; case 32: source->pub.get_pixel_rows = get_32bit_row; break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); } source->source_row = cinfo->image_height; /* And read the first row */ return (*source->pub.get_pixel_rows) (cinfo, sinfo); } /* * Read the file header; return image size and component count. */ METHODDEF(void) start_input_bmp(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { bmp_source_ptr source = (bmp_source_ptr)sinfo; U_CHAR bmpfileheader[14]; U_CHAR bmpinfoheader[64]; #define GET_2B(array, offset) \ ((unsigned short)UCH(array[offset]) + \ (((unsigned short)UCH(array[offset + 1])) << 8)) #define GET_4B(array, offset) \ ((unsigned int)UCH(array[offset]) + \ (((unsigned int)UCH(array[offset + 1])) << 8) + \ (((unsigned int)UCH(array[offset + 2])) << 16) + \ (((unsigned int)UCH(array[offset + 3])) << 24)) unsigned int bfOffBits; unsigned int headerSize; int biWidth; int biHeight; unsigned short biPlanes; unsigned int biCompression; int biXPelsPerMeter, biYPelsPerMeter; unsigned int biClrUsed = 0; int mapentrysize = 0; /* 0 indicates no colormap */ int bPad; JDIMENSION row_width = 0; /* Read and verify the bitmap file header */ if (!ReadOK(source->pub.input_file, bmpfileheader, 14)) ERREXIT(cinfo, JERR_INPUT_EOF); if (GET_2B(bmpfileheader, 0) != 0x4D42) /* 'BM' */ ERREXIT(cinfo, JERR_BMP_NOT); bfOffBits = GET_4B(bmpfileheader, 10); /* We ignore the remaining fileheader fields */ /* The infoheader might be 12 bytes (OS/2 1.x), 40 bytes (Windows), * or 64 bytes (OS/2 2.x). Check the first 4 bytes to find out which. */ if (!ReadOK(source->pub.input_file, bmpinfoheader, 4)) ERREXIT(cinfo, JERR_INPUT_EOF); headerSize = GET_4B(bmpinfoheader, 0); if (headerSize < 12 || headerSize > 64) ERREXIT(cinfo, JERR_BMP_BADHEADER); if (!ReadOK(source->pub.input_file, bmpinfoheader + 4, headerSize - 4)) ERREXIT(cinfo, JERR_INPUT_EOF); switch (headerSize) { case 12: /* Decode OS/2 1.x header (Microsoft calls this a BITMAPCOREHEADER) */ biWidth = (int)GET_2B(bmpinfoheader, 4); biHeight = (int)GET_2B(bmpinfoheader, 6); biPlanes = GET_2B(bmpinfoheader, 8); source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 10); switch (source->bits_per_pixel) { case 8: /* colormapped image */ mapentrysize = 3; /* OS/2 uses RGBTRIPLE colormap */ TRACEMS2(cinfo, 1, JTRC_BMP_OS2_MAPPED, biWidth, biHeight); break; case 24: /* RGB image */ TRACEMS2(cinfo, 1, JTRC_BMP_OS2, biWidth, biHeight); break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); break; } break; case 40: case 64: /* Decode Windows 3.x header (Microsoft calls this a BITMAPINFOHEADER) */ /* or OS/2 2.x header, which has additional fields that we ignore */ biWidth = (int)GET_4B(bmpinfoheader, 4); biHeight = (int)GET_4B(bmpinfoheader, 8); biPlanes = GET_2B(bmpinfoheader, 12); source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 14); biCompression = GET_4B(bmpinfoheader, 16); biXPelsPerMeter = (int)GET_4B(bmpinfoheader, 24); biYPelsPerMeter = (int)GET_4B(bmpinfoheader, 28); biClrUsed = GET_4B(bmpinfoheader, 32); /* biSizeImage, biClrImportant fields are ignored */ switch (source->bits_per_pixel) { case 8: /* colormapped image */ mapentrysize = 4; /* Windows uses RGBQUAD colormap */ TRACEMS2(cinfo, 1, JTRC_BMP_MAPPED, biWidth, biHeight); break; case 24: /* RGB image */ TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight); break; case 32: /* RGB image + Alpha channel */ TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight); break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); break; } if (biCompression != 0) ERREXIT(cinfo, JERR_BMP_COMPRESSED); if (biXPelsPerMeter > 0 && biYPelsPerMeter > 0) { /* Set JFIF density parameters from the BMP data */ cinfo->X_density = (UINT16)(biXPelsPerMeter / 100); /* 100 cm per meter */ cinfo->Y_density = (UINT16)(biYPelsPerMeter / 100); cinfo->density_unit = 2; /* dots/cm */ } break; default: ERREXIT(cinfo, JERR_BMP_BADHEADER); return; } if (biWidth <= 0 || biHeight <= 0) ERREXIT(cinfo, JERR_BMP_EMPTY); if (biPlanes != 1) ERREXIT(cinfo, JERR_BMP_BADPLANES); /* Compute distance to bitmap data --- will adjust for colormap below */ bPad = bfOffBits - (headerSize + 14); /* Read the colormap, if any */ if (mapentrysize > 0) { if (biClrUsed <= 0) biClrUsed = 256; /* assume it's 256 */ else if (biClrUsed > 256) ERREXIT(cinfo, JERR_BMP_BADCMAP); /* Allocate space to store the colormap */ source->colormap = (*cinfo->mem->alloc_sarray) ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)biClrUsed, (JDIMENSION)3); /* and read it from the file */ read_colormap(source, (int)biClrUsed, mapentrysize); /* account for size of colormap */ bPad -= biClrUsed * mapentrysize; } /* Skip any remaining pad bytes */ if (bPad < 0) /* incorrect bfOffBits value? */ ERREXIT(cinfo, JERR_BMP_BADHEADER); while (--bPad >= 0) { (void)read_byte(source); } /* Compute row width in file, including padding to 4-byte boundary */ switch (source->bits_per_pixel) { case 8: if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_EXT_RGB; if (IsExtRGB(cinfo->in_color_space)) cinfo->input_components = rgb_pixelsize[cinfo->in_color_space]; else if (cinfo->in_color_space == JCS_GRAYSCALE) cinfo->input_components = 1; else if (cinfo->in_color_space == JCS_CMYK) cinfo->input_components = 4; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); row_width = (JDIMENSION)biWidth; break; case 24: if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_EXT_BGR; if (IsExtRGB(cinfo->in_color_space)) cinfo->input_components = rgb_pixelsize[cinfo->in_color_space]; else if (cinfo->in_color_space == JCS_CMYK) cinfo->input_components = 4; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); row_width = (JDIMENSION)(biWidth * 3); break; case 32: if (cinfo->in_color_space == JCS_UNKNOWN) cinfo->in_color_space = JCS_EXT_BGRA; if (IsExtRGB(cinfo->in_color_space)) cinfo->input_components = rgb_pixelsize[cinfo->in_color_space]; else if (cinfo->in_color_space == JCS_CMYK) cinfo->input_components = 4; else ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE); row_width = (JDIMENSION)(biWidth * 4); break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); } while ((row_width & 3) != 0) row_width++; source->row_width = row_width; if (source->use_inversion_array) { /* Allocate space for inversion array, prepare for preload pass */ source->whole_image = (*cinfo->mem->request_virt_sarray) ((j_common_ptr)cinfo, JPOOL_IMAGE, FALSE, row_width, (JDIMENSION)biHeight, (JDIMENSION)1); source->pub.get_pixel_rows = preload_image; if (cinfo->progress != NULL) { cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress; progress->total_extra_passes++; /* count file input as separate pass */ } } else { source->iobuffer = (U_CHAR *) (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, row_width); switch (source->bits_per_pixel) { case 8: source->pub.get_pixel_rows = get_8bit_row; break; case 24: source->pub.get_pixel_rows = get_24bit_row; break; case 32: source->pub.get_pixel_rows = get_32bit_row; break; default: ERREXIT(cinfo, JERR_BMP_BADDEPTH); } } /* Ensure that biWidth * cinfo->input_components doesn't exceed the maximum value of the JDIMENSION type. This is only a danger with BMP files, since their width and height fields are 32-bit integers. */ if ((unsigned long long)biWidth * (unsigned long long)cinfo->input_components > 0xFFFFFFFFULL) ERREXIT(cinfo, JERR_WIDTH_OVERFLOW); /* Allocate one-row buffer for returned data */ source->pub.buffer = (*cinfo->mem->alloc_sarray) ((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)(biWidth * cinfo->input_components), (JDIMENSION)1); source->pub.buffer_height = 1; cinfo->data_precision = 8; cinfo->image_width = (JDIMENSION)biWidth; cinfo->image_height = (JDIMENSION)biHeight; } /* * Finish up at the end of the file. */ METHODDEF(void) finish_input_bmp(j_compress_ptr cinfo, cjpeg_source_ptr sinfo) { /* no work */ } /* * The module selection routine for BMP format input. */ GLOBAL(cjpeg_source_ptr) jinit_read_bmp(j_compress_ptr cinfo, boolean use_inversion_array) { bmp_source_ptr source; /* Create module interface object */ source = (bmp_source_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, sizeof(bmp_source_struct)); source->cinfo = cinfo; /* make back link for subroutines */ /* Fill in method ptrs, except get_pixel_rows which start_input sets */ source->pub.start_input = start_input_bmp; source->pub.finish_input = finish_input_bmp; source->use_inversion_array = use_inversion_array; return (cjpeg_source_ptr)source; } #endif /* BMP_SUPPORTED */
./CrossVul/dataset_final_sorted/CWE-369/c/good_153_1
crossvul-cpp_data_bad_4854_1
/* $Id$ */ /* WARNING: The type of JPEG encapsulation defined by the TIFF Version 6.0 specification is now totally obsolete and deprecated for new applications and images. This file was was created solely in order to read unconverted images still present on some users' computer systems. It will never be extended to write such files. Writing new-style JPEG compressed TIFFs is implemented in tif_jpeg.c. The code is carefully crafted to robustly read all gathered JPEG-in-TIFF testfiles, and anticipate as much as possible all other... But still, it may fail on some. If you encounter problems, please report them on the TIFF mailing list and/or to Joris Van Damme <info@awaresystems.be>. Please read the file called "TIFF Technical Note #2" if you need to be convinced this compression scheme is bad and breaks TIFF. That document is linked to from the LibTiff site <http://www.remotesensing.org/libtiff/> and from AWare Systems' TIFF section <http://www.awaresystems.be/imaging/tiff.html>. It is also absorbed in Adobe's specification supplements, marked "draft" up to this day, but supported by the TIFF community. This file interfaces with Release 6B of the JPEG Library written by the Independent JPEG Group. Previous versions of this file required a hack inside the LibJpeg library. This version no longer requires that. Remember to remove the hack if you update from the old version. Copyright (c) Joris Van Damme <info@awaresystems.be> Copyright (c) AWare Systems <http://www.awaresystems.be/> The licence agreement for this file is the same as the rest of the LibTiff library. IN NO EVENT SHALL JORIS VAN DAMME OR AWARE SYSTEMS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Joris Van Damme and/or AWare Systems may be available for custom development. If you like what you see, and need anything similar or related, contact <info@awaresystems.be>. */ /* What is what, and what is not? This decoder starts with an input stream, that is essentially the JpegInterchangeFormat stream, if any, followed by the strile data, if any. This stream is read in OJPEGReadByte and related functions. It analyzes the start of this stream, until it encounters non-marker data, i.e. compressed image data. Some of the header markers it sees have no actual content, like the SOI marker, and APP/COM markers that really shouldn't even be there. Some other markers do have content, and the valuable bits and pieces of information in these markers are saved, checking all to verify that the stream is more or less within expected bounds. This happens inside the OJPEGReadHeaderInfoSecStreamXxx functions. Some OJPEG imagery contains no valid JPEG header markers. This situation is picked up on if we've seen no SOF marker when we're at the start of the compressed image data. In this case, the tables are read from JpegXxxTables tags, and the other bits and pieces of information is initialized to its most basic value. This is implemented in the OJPEGReadHeaderInfoSecTablesXxx functions. When this is complete, a good and valid JPEG header can be assembled, and this is passed through to LibJpeg. When that's done, the remainder of the input stream, i.e. the compressed image data, can be passed through unchanged. This is done in OJPEGWriteStream functions. LibTiff rightly expects to know the subsampling values before decompression. Just like in new-style JPEG-in-TIFF, though, or even more so, actually, the YCbCrsubsampling tag is notoriously unreliable. To correct these tag values with the ones inside the JPEG stream, the first part of the input stream is pre-scanned in OJPEGSubsamplingCorrect, making no note of any other data, reporting no warnings or errors, up to the point where either these values are read, or it's clear they aren't there. This means that some of the data is read twice, but we feel speed in correcting these values is important enough to warrant this sacrifice. Although there is currently no define or other configuration mechanism to disable this behaviour, the actual header scanning is build to robustly respond with error report if it should encounter an uncorrected mismatch of subsampling values. See OJPEGReadHeaderInfoSecStreamSof. The restart interval and restart markers are the most tricky part... The restart interval can be specified in a tag. It can also be set inside the input JPEG stream. It can be used inside the input JPEG stream. If reading from strile data, we've consistently discovered the need to insert restart markers in between the different striles, as is also probably the most likely interpretation of the original TIFF 6.0 specification. With all this setting of interval, and actual use of markers that is not predictable at the time of valid JPEG header assembly, the restart thing may turn out the Achilles heel of this implementation. Fortunately, most OJPEG writer vendors succeed in reading back what they write, which may be the reason why we've been able to discover ways that seem to work. Some special provision is made for planarconfig separate OJPEG files. These seem to consistently contain header info, a SOS marker, a plane, SOS marker, plane, SOS, and plane. This may or may not be a valid JPEG configuration, we don't know and don't care. We want LibTiff to be able to access the planes individually, without huge buffering inside LibJpeg, anyway. So we compose headers to feed to LibJpeg, in this case, that allow us to pass a single plane such that LibJpeg sees a valid single-channel JPEG stream. Locating subsequent SOS markers, and thus subsequent planes, is done inside OJPEGReadSecondarySos. The benefit of the scheme is... that it works, basically. We know of no other that does. It works without checking software tag, or otherwise going about things in an OJPEG flavor specific manner. Instead, it is a single scheme, that covers the cases with and without JpegInterchangeFormat, with and without striles, with part of the header in JpegInterchangeFormat and remainder in first strile, etc. It is forgiving and robust, may likely work with OJPEG flavors we've not seen yet, and makes most out of the data. Another nice side-effect is that a complete JPEG single valid stream is build if planarconfig is not separate (vast majority). We may one day use that to build converters to JPEG, and/or to new-style JPEG compression inside TIFF. A disadvantage is the lack of random access to the individual striles. This is the reason for much of the complicated restart-and-position stuff inside OJPEGPreDecode. Applications would do well accessing all striles in order, as this will result in a single sequential scan of the input stream, and no restarting of LibJpeg decoding session. */ #define WIN32_LEAN_AND_MEAN #define VC_EXTRALEAN #include "tiffiop.h" #ifdef OJPEG_SUPPORT /* Configuration defines here are: * JPEG_ENCAP_EXTERNAL: The normal way to call libjpeg, uses longjump. In some environments, * like eg LibTiffDelphi, this is not possible. For this reason, the actual calls to * libjpeg, with longjump stuff, are encapsulated in dedicated functions. When * JPEG_ENCAP_EXTERNAL is defined, these encapsulating functions are declared external * to this unit, and can be defined elsewhere to use stuff other then longjump. * The default mode, without JPEG_ENCAP_EXTERNAL, implements the call encapsulators * here, internally, with normal longjump. * SETJMP, LONGJMP, JMP_BUF: On some machines/environments a longjump equivalent is * conveniently available, but still it may be worthwhile to use _setjmp or sigsetjmp * in place of plain setjmp. These macros will make it easier. It is useless * to fiddle with these if you define JPEG_ENCAP_EXTERNAL. * OJPEG_BUFFER: Define the size of the desired buffer here. Should be small enough so as to guarantee * instant processing, optimal streaming and optimal use of processor cache, but also big * enough so as to not result in significant call overhead. It should be at least a few * bytes to accommodate some structures (this is verified in asserts), but it would not be * sensible to make it this small anyway, and it should be at most 64K since it is indexed * with uint16. We recommend 2K. * EGYPTIANWALK: You could also define EGYPTIANWALK here, but it is not used anywhere and has * absolutely no effect. That is why most people insist the EGYPTIANWALK is a bit silly. */ /* define LIBJPEG_ENCAP_EXTERNAL */ #define SETJMP(jbuf) setjmp(jbuf) #define LONGJMP(jbuf,code) longjmp(jbuf,code) #define JMP_BUF jmp_buf #define OJPEG_BUFFER 2048 /* define EGYPTIANWALK */ #define JPEG_MARKER_SOF0 0xC0 #define JPEG_MARKER_SOF1 0xC1 #define JPEG_MARKER_SOF3 0xC3 #define JPEG_MARKER_DHT 0xC4 #define JPEG_MARKER_RST0 0XD0 #define JPEG_MARKER_SOI 0xD8 #define JPEG_MARKER_EOI 0xD9 #define JPEG_MARKER_SOS 0xDA #define JPEG_MARKER_DQT 0xDB #define JPEG_MARKER_DRI 0xDD #define JPEG_MARKER_APP0 0xE0 #define JPEG_MARKER_COM 0xFE #define FIELD_OJPEG_JPEGINTERCHANGEFORMAT (FIELD_CODEC+0) #define FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH (FIELD_CODEC+1) #define FIELD_OJPEG_JPEGQTABLES (FIELD_CODEC+2) #define FIELD_OJPEG_JPEGDCTABLES (FIELD_CODEC+3) #define FIELD_OJPEG_JPEGACTABLES (FIELD_CODEC+4) #define FIELD_OJPEG_JPEGPROC (FIELD_CODEC+5) #define FIELD_OJPEG_JPEGRESTARTINTERVAL (FIELD_CODEC+6) static const TIFFField ojpegFields[] = { {TIFFTAG_JPEGIFOFFSET,1,1,TIFF_LONG8,0,TIFF_SETGET_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGINTERCHANGEFORMAT,TRUE,FALSE,"JpegInterchangeFormat",NULL}, {TIFFTAG_JPEGIFBYTECOUNT,1,1,TIFF_LONG8,0,TIFF_SETGET_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH,TRUE,FALSE,"JpegInterchangeFormatLength",NULL}, {TIFFTAG_JPEGQTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGQTABLES,FALSE,TRUE,"JpegQTables",NULL}, {TIFFTAG_JPEGDCTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGDCTABLES,FALSE,TRUE,"JpegDcTables",NULL}, {TIFFTAG_JPEGACTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGACTABLES,FALSE,TRUE,"JpegAcTables",NULL}, {TIFFTAG_JPEGPROC,1,1,TIFF_SHORT,0,TIFF_SETGET_UINT16,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGPROC,FALSE,FALSE,"JpegProc",NULL}, {TIFFTAG_JPEGRESTARTINTERVAL,1,1,TIFF_SHORT,0,TIFF_SETGET_UINT16,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGRESTARTINTERVAL,FALSE,FALSE,"JpegRestartInterval",NULL}, }; #ifndef LIBJPEG_ENCAP_EXTERNAL #include <setjmp.h> #endif /* We undefine FAR to avoid conflict with JPEG definition */ #ifdef FAR #undef FAR #endif /* Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is not defined. Unfortunately, the MinGW and Borland compilers include a typedef for INT32, which causes a conflict. MSVC does not include a conflicting typedef given the headers which are included. */ #if defined(__BORLANDC__) || defined(__MINGW32__) # define XMD_H 1 #endif /* Define "boolean" as unsigned char, not int, per Windows custom. */ #if defined(__WIN32__) && !defined(__MINGW32__) # ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */ typedef unsigned char boolean; # endif # define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */ #endif #include "jpeglib.h" #include "jerror.h" typedef struct jpeg_error_mgr jpeg_error_mgr; typedef struct jpeg_common_struct jpeg_common_struct; typedef struct jpeg_decompress_struct jpeg_decompress_struct; typedef struct jpeg_source_mgr jpeg_source_mgr; typedef enum { osibsNotSetYet, osibsJpegInterchangeFormat, osibsStrile, osibsEof } OJPEGStateInBufferSource; typedef enum { ososSoi, ososQTable0,ososQTable1,ososQTable2,ososQTable3, ososDcTable0,ososDcTable1,ososDcTable2,ososDcTable3, ososAcTable0,ososAcTable1,ososAcTable2,ososAcTable3, ososDri, ososSof, ososSos, ososCompressed, ososRst, ososEoi } OJPEGStateOutState; typedef struct { TIFF* tif; #ifndef LIBJPEG_ENCAP_EXTERNAL JMP_BUF exit_jmpbuf; #endif TIFFVGetMethod vgetparent; TIFFVSetMethod vsetparent; TIFFPrintMethod printdir; uint64 file_size; uint32 image_width; uint32 image_length; uint32 strile_width; uint32 strile_length; uint32 strile_length_total; uint8 samples_per_pixel; uint8 plane_sample_offset; uint8 samples_per_pixel_per_plane; uint64 jpeg_interchange_format; uint64 jpeg_interchange_format_length; uint8 jpeg_proc; uint8 subsamplingcorrect; uint8 subsamplingcorrect_done; uint8 subsampling_tag; uint8 subsampling_hor; uint8 subsampling_ver; uint8 subsampling_force_desubsampling_inside_decompression; uint8 qtable_offset_count; uint8 dctable_offset_count; uint8 actable_offset_count; uint64 qtable_offset[3]; uint64 dctable_offset[3]; uint64 actable_offset[3]; uint8* qtable[4]; uint8* dctable[4]; uint8* actable[4]; uint16 restart_interval; uint8 restart_index; uint8 sof_log; uint8 sof_marker_id; uint32 sof_x; uint32 sof_y; uint8 sof_c[3]; uint8 sof_hv[3]; uint8 sof_tq[3]; uint8 sos_cs[3]; uint8 sos_tda[3]; struct { uint8 log; OJPEGStateInBufferSource in_buffer_source; uint32 in_buffer_next_strile; uint64 in_buffer_file_pos; uint64 in_buffer_file_togo; } sos_end[3]; uint8 readheader_done; uint8 writeheader_done; uint16 write_cursample; uint32 write_curstrile; uint8 libjpeg_session_active; uint8 libjpeg_jpeg_query_style; jpeg_error_mgr libjpeg_jpeg_error_mgr; jpeg_decompress_struct libjpeg_jpeg_decompress_struct; jpeg_source_mgr libjpeg_jpeg_source_mgr; uint8 subsampling_convert_log; uint32 subsampling_convert_ylinelen; uint32 subsampling_convert_ylines; uint32 subsampling_convert_clinelen; uint32 subsampling_convert_clines; uint32 subsampling_convert_ybuflen; uint32 subsampling_convert_cbuflen; uint32 subsampling_convert_ycbcrbuflen; uint8* subsampling_convert_ycbcrbuf; uint8* subsampling_convert_ybuf; uint8* subsampling_convert_cbbuf; uint8* subsampling_convert_crbuf; uint32 subsampling_convert_ycbcrimagelen; uint8** subsampling_convert_ycbcrimage; uint32 subsampling_convert_clinelenout; uint32 subsampling_convert_state; uint32 bytes_per_line; /* if the codec outputs subsampled data, a 'line' in bytes_per_line */ uint32 lines_per_strile; /* and lines_per_strile means subsampling_ver desubsampled rows */ OJPEGStateInBufferSource in_buffer_source; uint32 in_buffer_next_strile; uint32 in_buffer_strile_count; uint64 in_buffer_file_pos; uint8 in_buffer_file_pos_log; uint64 in_buffer_file_togo; uint16 in_buffer_togo; uint8* in_buffer_cur; uint8 in_buffer[OJPEG_BUFFER]; OJPEGStateOutState out_state; uint8 out_buffer[OJPEG_BUFFER]; uint8* skip_buffer; } OJPEGState; static int OJPEGVGetField(TIFF* tif, uint32 tag, va_list ap); static int OJPEGVSetField(TIFF* tif, uint32 tag, va_list ap); static void OJPEGPrintDir(TIFF* tif, FILE* fd, long flags); static int OJPEGFixupTags(TIFF* tif); static int OJPEGSetupDecode(TIFF* tif); static int OJPEGPreDecode(TIFF* tif, uint16 s); static int OJPEGPreDecodeSkipRaw(TIFF* tif); static int OJPEGPreDecodeSkipScanlines(TIFF* tif); static int OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s); static int OJPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc); static int OJPEGDecodeScanlines(TIFF* tif, uint8* buf, tmsize_t cc); static void OJPEGPostDecode(TIFF* tif, uint8* buf, tmsize_t cc); static int OJPEGSetupEncode(TIFF* tif); static int OJPEGPreEncode(TIFF* tif, uint16 s); static int OJPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s); static int OJPEGPostEncode(TIFF* tif); static void OJPEGCleanup(TIFF* tif); static void OJPEGSubsamplingCorrect(TIFF* tif); static int OJPEGReadHeaderInfo(TIFF* tif); static int OJPEGReadSecondarySos(TIFF* tif, uint16 s); static int OJPEGWriteHeaderInfo(TIFF* tif); static void OJPEGLibjpegSessionAbort(TIFF* tif); static int OJPEGReadHeaderInfoSec(TIFF* tif); static int OJPEGReadHeaderInfoSecStreamDri(TIFF* tif); static int OJPEGReadHeaderInfoSecStreamDqt(TIFF* tif); static int OJPEGReadHeaderInfoSecStreamDht(TIFF* tif); static int OJPEGReadHeaderInfoSecStreamSof(TIFF* tif, uint8 marker_id); static int OJPEGReadHeaderInfoSecStreamSos(TIFF* tif); static int OJPEGReadHeaderInfoSecTablesQTable(TIFF* tif); static int OJPEGReadHeaderInfoSecTablesDcTable(TIFF* tif); static int OJPEGReadHeaderInfoSecTablesAcTable(TIFF* tif); static int OJPEGReadBufferFill(OJPEGState* sp); static int OJPEGReadByte(OJPEGState* sp, uint8* byte); static int OJPEGReadBytePeek(OJPEGState* sp, uint8* byte); static void OJPEGReadByteAdvance(OJPEGState* sp); static int OJPEGReadWord(OJPEGState* sp, uint16* word); static int OJPEGReadBlock(OJPEGState* sp, uint16 len, void* mem); static void OJPEGReadSkip(OJPEGState* sp, uint16 len); static int OJPEGWriteStream(TIFF* tif, void** mem, uint32* len); static void OJPEGWriteStreamSoi(TIFF* tif, void** mem, uint32* len); static void OJPEGWriteStreamQTable(TIFF* tif, uint8 table_index, void** mem, uint32* len); static void OJPEGWriteStreamDcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len); static void OJPEGWriteStreamAcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len); static void OJPEGWriteStreamDri(TIFF* tif, void** mem, uint32* len); static void OJPEGWriteStreamSof(TIFF* tif, void** mem, uint32* len); static void OJPEGWriteStreamSos(TIFF* tif, void** mem, uint32* len); static int OJPEGWriteStreamCompressed(TIFF* tif, void** mem, uint32* len); static void OJPEGWriteStreamRst(TIFF* tif, void** mem, uint32* len); static void OJPEGWriteStreamEoi(TIFF* tif, void** mem, uint32* len); #ifdef LIBJPEG_ENCAP_EXTERNAL extern int jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo); extern int jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image); extern int jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo); extern int jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines); extern int jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines); extern void jpeg_encap_unwind(TIFF* tif); #else static int jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* j); static int jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image); static int jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo); static int jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines); static int jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines); static void jpeg_encap_unwind(TIFF* tif); #endif static void OJPEGLibjpegJpegErrorMgrOutputMessage(jpeg_common_struct* cinfo); static void OJPEGLibjpegJpegErrorMgrErrorExit(jpeg_common_struct* cinfo); static void OJPEGLibjpegJpegSourceMgrInitSource(jpeg_decompress_struct* cinfo); static boolean OJPEGLibjpegJpegSourceMgrFillInputBuffer(jpeg_decompress_struct* cinfo); static void OJPEGLibjpegJpegSourceMgrSkipInputData(jpeg_decompress_struct* cinfo, long num_bytes); static boolean OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct* cinfo, int desired); static void OJPEGLibjpegJpegSourceMgrTermSource(jpeg_decompress_struct* cinfo); int TIFFInitOJPEG(TIFF* tif, int scheme) { static const char module[]="TIFFInitOJPEG"; OJPEGState* sp; assert(scheme==COMPRESSION_OJPEG); /* * Merge codec-specific tag information. */ if (!_TIFFMergeFields(tif, ojpegFields, TIFFArrayCount(ojpegFields))) { TIFFErrorExt(tif->tif_clientdata, module, "Merging Old JPEG codec-specific tags failed"); return 0; } /* state block */ sp=_TIFFmalloc(sizeof(OJPEGState)); if (sp==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"No space for OJPEG state block"); return(0); } _TIFFmemset(sp,0,sizeof(OJPEGState)); sp->tif=tif; sp->jpeg_proc=1; sp->subsampling_hor=2; sp->subsampling_ver=2; TIFFSetField(tif,TIFFTAG_YCBCRSUBSAMPLING,2,2); /* tif codec methods */ tif->tif_fixuptags=OJPEGFixupTags; tif->tif_setupdecode=OJPEGSetupDecode; tif->tif_predecode=OJPEGPreDecode; tif->tif_postdecode=OJPEGPostDecode; tif->tif_decoderow=OJPEGDecode; tif->tif_decodestrip=OJPEGDecode; tif->tif_decodetile=OJPEGDecode; tif->tif_setupencode=OJPEGSetupEncode; tif->tif_preencode=OJPEGPreEncode; tif->tif_postencode=OJPEGPostEncode; tif->tif_encoderow=OJPEGEncode; tif->tif_encodestrip=OJPEGEncode; tif->tif_encodetile=OJPEGEncode; tif->tif_cleanup=OJPEGCleanup; tif->tif_data=(uint8*)sp; /* tif tag methods */ sp->vgetparent=tif->tif_tagmethods.vgetfield; tif->tif_tagmethods.vgetfield=OJPEGVGetField; sp->vsetparent=tif->tif_tagmethods.vsetfield; tif->tif_tagmethods.vsetfield=OJPEGVSetField; sp->printdir=tif->tif_tagmethods.printdir; tif->tif_tagmethods.printdir=OJPEGPrintDir; /* Some OJPEG files don't have strip or tile offsets or bytecounts tags. Some others do, but have totally meaningless or corrupt values in these tags. In these cases, the JpegInterchangeFormat stream is reliable. In any case, this decoder reads the compressed data itself, from the most reliable locations, and we need to notify encapsulating LibTiff not to read raw strips or tiles for us. */ tif->tif_flags|=TIFF_NOREADRAW; return(1); } static int OJPEGVGetField(TIFF* tif, uint32 tag, va_list ap) { OJPEGState* sp=(OJPEGState*)tif->tif_data; switch(tag) { case TIFFTAG_JPEGIFOFFSET: *va_arg(ap,uint64*)=(uint64)sp->jpeg_interchange_format; break; case TIFFTAG_JPEGIFBYTECOUNT: *va_arg(ap,uint64*)=(uint64)sp->jpeg_interchange_format_length; break; case TIFFTAG_YCBCRSUBSAMPLING: if (sp->subsamplingcorrect_done==0) OJPEGSubsamplingCorrect(tif); *va_arg(ap,uint16*)=(uint16)sp->subsampling_hor; *va_arg(ap,uint16*)=(uint16)sp->subsampling_ver; break; case TIFFTAG_JPEGQTABLES: *va_arg(ap,uint32*)=(uint32)sp->qtable_offset_count; *va_arg(ap,void**)=(void*)sp->qtable_offset; break; case TIFFTAG_JPEGDCTABLES: *va_arg(ap,uint32*)=(uint32)sp->dctable_offset_count; *va_arg(ap,void**)=(void*)sp->dctable_offset; break; case TIFFTAG_JPEGACTABLES: *va_arg(ap,uint32*)=(uint32)sp->actable_offset_count; *va_arg(ap,void**)=(void*)sp->actable_offset; break; case TIFFTAG_JPEGPROC: *va_arg(ap,uint16*)=(uint16)sp->jpeg_proc; break; case TIFFTAG_JPEGRESTARTINTERVAL: *va_arg(ap,uint16*)=sp->restart_interval; break; default: return (*sp->vgetparent)(tif,tag,ap); } return (1); } static int OJPEGVSetField(TIFF* tif, uint32 tag, va_list ap) { static const char module[]="OJPEGVSetField"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint32 ma; uint64* mb; uint32 n; const TIFFField* fip; switch(tag) { case TIFFTAG_JPEGIFOFFSET: sp->jpeg_interchange_format=(uint64)va_arg(ap,uint64); break; case TIFFTAG_JPEGIFBYTECOUNT: sp->jpeg_interchange_format_length=(uint64)va_arg(ap,uint64); break; case TIFFTAG_YCBCRSUBSAMPLING: sp->subsampling_tag=1; sp->subsampling_hor=(uint8)va_arg(ap,uint16_vap); sp->subsampling_ver=(uint8)va_arg(ap,uint16_vap); tif->tif_dir.td_ycbcrsubsampling[0]=sp->subsampling_hor; tif->tif_dir.td_ycbcrsubsampling[1]=sp->subsampling_ver; break; case TIFFTAG_JPEGQTABLES: ma=(uint32)va_arg(ap,uint32); if (ma!=0) { if (ma>3) { TIFFErrorExt(tif->tif_clientdata,module,"JpegQTables tag has incorrect count"); return(0); } sp->qtable_offset_count=(uint8)ma; mb=(uint64*)va_arg(ap,uint64*); for (n=0; n<ma; n++) sp->qtable_offset[n]=mb[n]; } break; case TIFFTAG_JPEGDCTABLES: ma=(uint32)va_arg(ap,uint32); if (ma!=0) { if (ma>3) { TIFFErrorExt(tif->tif_clientdata,module,"JpegDcTables tag has incorrect count"); return(0); } sp->dctable_offset_count=(uint8)ma; mb=(uint64*)va_arg(ap,uint64*); for (n=0; n<ma; n++) sp->dctable_offset[n]=mb[n]; } break; case TIFFTAG_JPEGACTABLES: ma=(uint32)va_arg(ap,uint32); if (ma!=0) { if (ma>3) { TIFFErrorExt(tif->tif_clientdata,module,"JpegAcTables tag has incorrect count"); return(0); } sp->actable_offset_count=(uint8)ma; mb=(uint64*)va_arg(ap,uint64*); for (n=0; n<ma; n++) sp->actable_offset[n]=mb[n]; } break; case TIFFTAG_JPEGPROC: sp->jpeg_proc=(uint8)va_arg(ap,uint16_vap); break; case TIFFTAG_JPEGRESTARTINTERVAL: sp->restart_interval=(uint16)va_arg(ap,uint16_vap); break; default: return (*sp->vsetparent)(tif,tag,ap); } fip = TIFFFieldWithTag(tif,tag); if( fip == NULL ) /* shouldn't happen */ return(0); TIFFSetFieldBit(tif,fip->field_bit); tif->tif_flags|=TIFF_DIRTYDIRECT; return(1); } static void OJPEGPrintDir(TIFF* tif, FILE* fd, long flags) { OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8 m; (void)flags; assert(sp!=NULL); if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGINTERCHANGEFORMAT)) fprintf(fd," JpegInterchangeFormat: " TIFF_UINT64_FORMAT "\n",(TIFF_UINT64_T)sp->jpeg_interchange_format); if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH)) fprintf(fd," JpegInterchangeFormatLength: " TIFF_UINT64_FORMAT "\n",(TIFF_UINT64_T)sp->jpeg_interchange_format_length); if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGQTABLES)) { fprintf(fd," JpegQTables:"); for (m=0; m<sp->qtable_offset_count; m++) fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->qtable_offset[m]); fprintf(fd,"\n"); } if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGDCTABLES)) { fprintf(fd," JpegDcTables:"); for (m=0; m<sp->dctable_offset_count; m++) fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->dctable_offset[m]); fprintf(fd,"\n"); } if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGACTABLES)) { fprintf(fd," JpegAcTables:"); for (m=0; m<sp->actable_offset_count; m++) fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->actable_offset[m]); fprintf(fd,"\n"); } if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGPROC)) fprintf(fd," JpegProc: %u\n",(unsigned int)sp->jpeg_proc); if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGRESTARTINTERVAL)) fprintf(fd," JpegRestartInterval: %u\n",(unsigned int)sp->restart_interval); if (sp->printdir) (*sp->printdir)(tif, fd, flags); } static int OJPEGFixupTags(TIFF* tif) { (void) tif; return(1); } static int OJPEGSetupDecode(TIFF* tif) { static const char module[]="OJPEGSetupDecode"; TIFFWarningExt(tif->tif_clientdata,module,"Depreciated and troublesome old-style JPEG compression mode, please convert to new-style JPEG compression and notify vendor of writing software"); return(1); } static int OJPEGPreDecode(TIFF* tif, uint16 s) { OJPEGState* sp=(OJPEGState*)tif->tif_data; uint32 m; if (sp->subsamplingcorrect_done==0) OJPEGSubsamplingCorrect(tif); if (sp->readheader_done==0) { if (OJPEGReadHeaderInfo(tif)==0) return(0); } if (sp->sos_end[s].log==0) { if (OJPEGReadSecondarySos(tif,s)==0) return(0); } if isTiled(tif) m=tif->tif_curtile; else m=tif->tif_curstrip; if ((sp->writeheader_done!=0) && ((sp->write_cursample!=s) || (sp->write_curstrile>m))) { if (sp->libjpeg_session_active!=0) OJPEGLibjpegSessionAbort(tif); sp->writeheader_done=0; } if (sp->writeheader_done==0) { sp->plane_sample_offset=(uint8)s; sp->write_cursample=s; sp->write_curstrile=s*tif->tif_dir.td_stripsperimage; if ((sp->in_buffer_file_pos_log==0) || (sp->in_buffer_file_pos-sp->in_buffer_togo!=sp->sos_end[s].in_buffer_file_pos)) { sp->in_buffer_source=sp->sos_end[s].in_buffer_source; sp->in_buffer_next_strile=sp->sos_end[s].in_buffer_next_strile; sp->in_buffer_file_pos=sp->sos_end[s].in_buffer_file_pos; sp->in_buffer_file_pos_log=0; sp->in_buffer_file_togo=sp->sos_end[s].in_buffer_file_togo; sp->in_buffer_togo=0; sp->in_buffer_cur=0; } if (OJPEGWriteHeaderInfo(tif)==0) return(0); } while (sp->write_curstrile<m) { if (sp->libjpeg_jpeg_query_style==0) { if (OJPEGPreDecodeSkipRaw(tif)==0) return(0); } else { if (OJPEGPreDecodeSkipScanlines(tif)==0) return(0); } sp->write_curstrile++; } return(1); } static int OJPEGPreDecodeSkipRaw(TIFF* tif) { OJPEGState* sp=(OJPEGState*)tif->tif_data; uint32 m; m=sp->lines_per_strile; if (sp->subsampling_convert_state!=0) { if (sp->subsampling_convert_clines-sp->subsampling_convert_state>=m) { sp->subsampling_convert_state+=m; if (sp->subsampling_convert_state==sp->subsampling_convert_clines) sp->subsampling_convert_state=0; return(1); } m-=sp->subsampling_convert_clines-sp->subsampling_convert_state; sp->subsampling_convert_state=0; } while (m>=sp->subsampling_convert_clines) { if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0) return(0); m-=sp->subsampling_convert_clines; } if (m>0) { if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0) return(0); sp->subsampling_convert_state=m; } return(1); } static int OJPEGPreDecodeSkipScanlines(TIFF* tif) { static const char module[]="OJPEGPreDecodeSkipScanlines"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint32 m; if (sp->skip_buffer==NULL) { sp->skip_buffer=_TIFFmalloc(sp->bytes_per_line); if (sp->skip_buffer==NULL) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } } for (m=0; m<sp->lines_per_strile; m++) { if (jpeg_read_scanlines_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),&sp->skip_buffer,1)==0) return(0); } return(1); } static int OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s) { OJPEGState* sp=(OJPEGState*)tif->tif_data; (void)s; if (sp->libjpeg_jpeg_query_style==0) { if (OJPEGDecodeRaw(tif,buf,cc)==0) return(0); } else { if (OJPEGDecodeScanlines(tif,buf,cc)==0) return(0); } return(1); } static int OJPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc) { static const char module[]="OJPEGDecodeRaw"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8* m; tmsize_t n; uint8* oy; uint8* ocb; uint8* ocr; uint8* p; uint32 q; uint8* r; uint8 sx,sy; if (cc%sp->bytes_per_line!=0) { TIFFErrorExt(tif->tif_clientdata,module,"Fractional scanline not read"); return(0); } assert(cc>0); m=buf; n=cc; do { if (sp->subsampling_convert_state==0) { if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0) return(0); } oy=sp->subsampling_convert_ybuf+sp->subsampling_convert_state*sp->subsampling_ver*sp->subsampling_convert_ylinelen; ocb=sp->subsampling_convert_cbbuf+sp->subsampling_convert_state*sp->subsampling_convert_clinelen; ocr=sp->subsampling_convert_crbuf+sp->subsampling_convert_state*sp->subsampling_convert_clinelen; p=m; for (q=0; q<sp->subsampling_convert_clinelenout; q++) { r=oy; for (sy=0; sy<sp->subsampling_ver; sy++) { for (sx=0; sx<sp->subsampling_hor; sx++) *p++=*r++; r+=sp->subsampling_convert_ylinelen-sp->subsampling_hor; } oy+=sp->subsampling_hor; *p++=*ocb++; *p++=*ocr++; } sp->subsampling_convert_state++; if (sp->subsampling_convert_state==sp->subsampling_convert_clines) sp->subsampling_convert_state=0; m+=sp->bytes_per_line; n-=sp->bytes_per_line; } while(n>0); return(1); } static int OJPEGDecodeScanlines(TIFF* tif, uint8* buf, tmsize_t cc) { static const char module[]="OJPEGDecodeScanlines"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8* m; tmsize_t n; if (cc%sp->bytes_per_line!=0) { TIFFErrorExt(tif->tif_clientdata,module,"Fractional scanline not read"); return(0); } assert(cc>0); m=buf; n=cc; do { if (jpeg_read_scanlines_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),&m,1)==0) return(0); m+=sp->bytes_per_line; n-=sp->bytes_per_line; } while(n>0); return(1); } static void OJPEGPostDecode(TIFF* tif, uint8* buf, tmsize_t cc) { OJPEGState* sp=(OJPEGState*)tif->tif_data; (void)buf; (void)cc; sp->write_curstrile++; if (sp->write_curstrile%tif->tif_dir.td_stripsperimage==0) { assert(sp->libjpeg_session_active!=0); OJPEGLibjpegSessionAbort(tif); sp->writeheader_done=0; } } static int OJPEGSetupEncode(TIFF* tif) { static const char module[]="OJPEGSetupEncode"; TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead"); return(0); } static int OJPEGPreEncode(TIFF* tif, uint16 s) { static const char module[]="OJPEGPreEncode"; (void)s; TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead"); return(0); } static int OJPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s) { static const char module[]="OJPEGEncode"; (void)buf; (void)cc; (void)s; TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead"); return(0); } static int OJPEGPostEncode(TIFF* tif) { static const char module[]="OJPEGPostEncode"; TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead"); return(0); } static void OJPEGCleanup(TIFF* tif) { OJPEGState* sp=(OJPEGState*)tif->tif_data; if (sp!=0) { tif->tif_tagmethods.vgetfield=sp->vgetparent; tif->tif_tagmethods.vsetfield=sp->vsetparent; tif->tif_tagmethods.printdir=sp->printdir; if (sp->qtable[0]!=0) _TIFFfree(sp->qtable[0]); if (sp->qtable[1]!=0) _TIFFfree(sp->qtable[1]); if (sp->qtable[2]!=0) _TIFFfree(sp->qtable[2]); if (sp->qtable[3]!=0) _TIFFfree(sp->qtable[3]); if (sp->dctable[0]!=0) _TIFFfree(sp->dctable[0]); if (sp->dctable[1]!=0) _TIFFfree(sp->dctable[1]); if (sp->dctable[2]!=0) _TIFFfree(sp->dctable[2]); if (sp->dctable[3]!=0) _TIFFfree(sp->dctable[3]); if (sp->actable[0]!=0) _TIFFfree(sp->actable[0]); if (sp->actable[1]!=0) _TIFFfree(sp->actable[1]); if (sp->actable[2]!=0) _TIFFfree(sp->actable[2]); if (sp->actable[3]!=0) _TIFFfree(sp->actable[3]); if (sp->libjpeg_session_active!=0) OJPEGLibjpegSessionAbort(tif); if (sp->subsampling_convert_ycbcrbuf!=0) _TIFFfree(sp->subsampling_convert_ycbcrbuf); if (sp->subsampling_convert_ycbcrimage!=0) _TIFFfree(sp->subsampling_convert_ycbcrimage); if (sp->skip_buffer!=0) _TIFFfree(sp->skip_buffer); _TIFFfree(sp); tif->tif_data=NULL; _TIFFSetDefaultCompressionState(tif); } } static void OJPEGSubsamplingCorrect(TIFF* tif) { static const char module[]="OJPEGSubsamplingCorrect"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8 mh; uint8 mv; _TIFFFillStriles( tif ); assert(sp->subsamplingcorrect_done==0); if ((tif->tif_dir.td_samplesperpixel!=3) || ((tif->tif_dir.td_photometric!=PHOTOMETRIC_YCBCR) && (tif->tif_dir.td_photometric!=PHOTOMETRIC_ITULAB))) { if (sp->subsampling_tag!=0) TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag not appropriate for this Photometric and/or SamplesPerPixel"); sp->subsampling_hor=1; sp->subsampling_ver=1; sp->subsampling_force_desubsampling_inside_decompression=0; } else { sp->subsamplingcorrect_done=1; mh=sp->subsampling_hor; mv=sp->subsampling_ver; sp->subsamplingcorrect=1; OJPEGReadHeaderInfoSec(tif); if (sp->subsampling_force_desubsampling_inside_decompression!=0) { sp->subsampling_hor=1; sp->subsampling_ver=1; } sp->subsamplingcorrect=0; if (((sp->subsampling_hor!=mh) || (sp->subsampling_ver!=mv)) && (sp->subsampling_force_desubsampling_inside_decompression==0)) { if (sp->subsampling_tag==0) TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag is not set, yet subsampling inside JPEG data [%d,%d] does not match default values [2,2]; assuming subsampling inside JPEG data is correct",sp->subsampling_hor,sp->subsampling_ver); else TIFFWarningExt(tif->tif_clientdata,module,"Subsampling inside JPEG data [%d,%d] does not match subsampling tag values [%d,%d]; assuming subsampling inside JPEG data is correct",sp->subsampling_hor,sp->subsampling_ver,mh,mv); } if (sp->subsampling_force_desubsampling_inside_decompression!=0) { if (sp->subsampling_tag==0) TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag is not set, yet subsampling inside JPEG data does not match default values [2,2] (nor any other values allowed in TIFF); assuming subsampling inside JPEG data is correct and desubsampling inside JPEG decompression"); else TIFFWarningExt(tif->tif_clientdata,module,"Subsampling inside JPEG data does not match subsampling tag values [%d,%d] (nor any other values allowed in TIFF); assuming subsampling inside JPEG data is correct and desubsampling inside JPEG decompression",mh,mv); } if (sp->subsampling_force_desubsampling_inside_decompression==0) { if (sp->subsampling_hor<sp->subsampling_ver) TIFFWarningExt(tif->tif_clientdata,module,"Subsampling values [%d,%d] are not allowed in TIFF",sp->subsampling_hor,sp->subsampling_ver); } } sp->subsamplingcorrect_done=1; } static int OJPEGReadHeaderInfo(TIFF* tif) { static const char module[]="OJPEGReadHeaderInfo"; OJPEGState* sp=(OJPEGState*)tif->tif_data; assert(sp->readheader_done==0); sp->image_width=tif->tif_dir.td_imagewidth; sp->image_length=tif->tif_dir.td_imagelength; if isTiled(tif) { sp->strile_width=tif->tif_dir.td_tilewidth; sp->strile_length=tif->tif_dir.td_tilelength; sp->strile_length_total=((sp->image_length+sp->strile_length-1)/sp->strile_length)*sp->strile_length; } else { sp->strile_width=sp->image_width; sp->strile_length=tif->tif_dir.td_rowsperstrip; sp->strile_length_total=sp->image_length; } if (tif->tif_dir.td_samplesperpixel==1) { sp->samples_per_pixel=1; sp->plane_sample_offset=0; sp->samples_per_pixel_per_plane=sp->samples_per_pixel; sp->subsampling_hor=1; sp->subsampling_ver=1; } else { if (tif->tif_dir.td_samplesperpixel!=3) { TIFFErrorExt(tif->tif_clientdata,module,"SamplesPerPixel %d not supported for this compression scheme",sp->samples_per_pixel); return(0); } sp->samples_per_pixel=3; sp->plane_sample_offset=0; if (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG) sp->samples_per_pixel_per_plane=3; else sp->samples_per_pixel_per_plane=1; } if (sp->strile_length<sp->image_length) { if (sp->strile_length%(sp->subsampling_ver*8)!=0) { TIFFErrorExt(tif->tif_clientdata,module,"Incompatible vertical subsampling and image strip/tile length"); return(0); } sp->restart_interval=(uint16)(((sp->strile_width+sp->subsampling_hor*8-1)/(sp->subsampling_hor*8))*(sp->strile_length/(sp->subsampling_ver*8))); } if (OJPEGReadHeaderInfoSec(tif)==0) return(0); sp->sos_end[0].log=1; sp->sos_end[0].in_buffer_source=sp->in_buffer_source; sp->sos_end[0].in_buffer_next_strile=sp->in_buffer_next_strile; sp->sos_end[0].in_buffer_file_pos=sp->in_buffer_file_pos-sp->in_buffer_togo; sp->sos_end[0].in_buffer_file_togo=sp->in_buffer_file_togo+sp->in_buffer_togo; sp->readheader_done=1; return(1); } static int OJPEGReadSecondarySos(TIFF* tif, uint16 s) { OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8 m; assert(s>0); assert(s<3); assert(sp->sos_end[0].log!=0); assert(sp->sos_end[s].log==0); sp->plane_sample_offset=(uint8)(s-1); while(sp->sos_end[sp->plane_sample_offset].log==0) sp->plane_sample_offset--; sp->in_buffer_source=sp->sos_end[sp->plane_sample_offset].in_buffer_source; sp->in_buffer_next_strile=sp->sos_end[sp->plane_sample_offset].in_buffer_next_strile; sp->in_buffer_file_pos=sp->sos_end[sp->plane_sample_offset].in_buffer_file_pos; sp->in_buffer_file_pos_log=0; sp->in_buffer_file_togo=sp->sos_end[sp->plane_sample_offset].in_buffer_file_togo; sp->in_buffer_togo=0; sp->in_buffer_cur=0; while(sp->plane_sample_offset<s) { do { if (OJPEGReadByte(sp,&m)==0) return(0); if (m==255) { do { if (OJPEGReadByte(sp,&m)==0) return(0); if (m!=255) break; } while(1); if (m==JPEG_MARKER_SOS) break; } } while(1); sp->plane_sample_offset++; if (OJPEGReadHeaderInfoSecStreamSos(tif)==0) return(0); sp->sos_end[sp->plane_sample_offset].log=1; sp->sos_end[sp->plane_sample_offset].in_buffer_source=sp->in_buffer_source; sp->sos_end[sp->plane_sample_offset].in_buffer_next_strile=sp->in_buffer_next_strile; sp->sos_end[sp->plane_sample_offset].in_buffer_file_pos=sp->in_buffer_file_pos-sp->in_buffer_togo; sp->sos_end[sp->plane_sample_offset].in_buffer_file_togo=sp->in_buffer_file_togo+sp->in_buffer_togo; } return(1); } static int OJPEGWriteHeaderInfo(TIFF* tif) { static const char module[]="OJPEGWriteHeaderInfo"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8** m; uint32 n; /* if a previous attempt failed, don't try again */ if (sp->libjpeg_session_active != 0) return 0; sp->out_state=ososSoi; sp->restart_index=0; jpeg_std_error(&(sp->libjpeg_jpeg_error_mgr)); sp->libjpeg_jpeg_error_mgr.output_message=OJPEGLibjpegJpegErrorMgrOutputMessage; sp->libjpeg_jpeg_error_mgr.error_exit=OJPEGLibjpegJpegErrorMgrErrorExit; sp->libjpeg_jpeg_decompress_struct.err=&(sp->libjpeg_jpeg_error_mgr); sp->libjpeg_jpeg_decompress_struct.client_data=(void*)tif; if (jpeg_create_decompress_encap(sp,&(sp->libjpeg_jpeg_decompress_struct))==0) return(0); sp->libjpeg_session_active=1; sp->libjpeg_jpeg_source_mgr.bytes_in_buffer=0; sp->libjpeg_jpeg_source_mgr.init_source=OJPEGLibjpegJpegSourceMgrInitSource; sp->libjpeg_jpeg_source_mgr.fill_input_buffer=OJPEGLibjpegJpegSourceMgrFillInputBuffer; sp->libjpeg_jpeg_source_mgr.skip_input_data=OJPEGLibjpegJpegSourceMgrSkipInputData; sp->libjpeg_jpeg_source_mgr.resync_to_restart=OJPEGLibjpegJpegSourceMgrResyncToRestart; sp->libjpeg_jpeg_source_mgr.term_source=OJPEGLibjpegJpegSourceMgrTermSource; sp->libjpeg_jpeg_decompress_struct.src=&(sp->libjpeg_jpeg_source_mgr); if (jpeg_read_header_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),1)==0) return(0); if ((sp->subsampling_force_desubsampling_inside_decompression==0) && (sp->samples_per_pixel_per_plane>1)) { sp->libjpeg_jpeg_decompress_struct.raw_data_out=1; #if JPEG_LIB_VERSION >= 70 sp->libjpeg_jpeg_decompress_struct.do_fancy_upsampling=FALSE; #endif sp->libjpeg_jpeg_query_style=0; if (sp->subsampling_convert_log==0) { assert(sp->subsampling_convert_ycbcrbuf==0); assert(sp->subsampling_convert_ycbcrimage==0); sp->subsampling_convert_ylinelen=((sp->strile_width+sp->subsampling_hor*8-1)/(sp->subsampling_hor*8)*sp->subsampling_hor*8); sp->subsampling_convert_ylines=sp->subsampling_ver*8; sp->subsampling_convert_clinelen=sp->subsampling_convert_ylinelen/sp->subsampling_hor; sp->subsampling_convert_clines=8; sp->subsampling_convert_ybuflen=sp->subsampling_convert_ylinelen*sp->subsampling_convert_ylines; sp->subsampling_convert_cbuflen=sp->subsampling_convert_clinelen*sp->subsampling_convert_clines; sp->subsampling_convert_ycbcrbuflen=sp->subsampling_convert_ybuflen+2*sp->subsampling_convert_cbuflen; sp->subsampling_convert_ycbcrbuf=_TIFFmalloc(sp->subsampling_convert_ycbcrbuflen); if (sp->subsampling_convert_ycbcrbuf==0) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } sp->subsampling_convert_ybuf=sp->subsampling_convert_ycbcrbuf; sp->subsampling_convert_cbbuf=sp->subsampling_convert_ybuf+sp->subsampling_convert_ybuflen; sp->subsampling_convert_crbuf=sp->subsampling_convert_cbbuf+sp->subsampling_convert_cbuflen; sp->subsampling_convert_ycbcrimagelen=3+sp->subsampling_convert_ylines+2*sp->subsampling_convert_clines; sp->subsampling_convert_ycbcrimage=_TIFFmalloc(sp->subsampling_convert_ycbcrimagelen*sizeof(uint8*)); if (sp->subsampling_convert_ycbcrimage==0) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } m=sp->subsampling_convert_ycbcrimage; *m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3); *m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3+sp->subsampling_convert_ylines); *m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3+sp->subsampling_convert_ylines+sp->subsampling_convert_clines); for (n=0; n<sp->subsampling_convert_ylines; n++) *m++=sp->subsampling_convert_ybuf+n*sp->subsampling_convert_ylinelen; for (n=0; n<sp->subsampling_convert_clines; n++) *m++=sp->subsampling_convert_cbbuf+n*sp->subsampling_convert_clinelen; for (n=0; n<sp->subsampling_convert_clines; n++) *m++=sp->subsampling_convert_crbuf+n*sp->subsampling_convert_clinelen; sp->subsampling_convert_clinelenout=((sp->strile_width+sp->subsampling_hor-1)/sp->subsampling_hor); sp->subsampling_convert_state=0; sp->bytes_per_line=sp->subsampling_convert_clinelenout*(sp->subsampling_ver*sp->subsampling_hor+2); sp->lines_per_strile=((sp->strile_length+sp->subsampling_ver-1)/sp->subsampling_ver); sp->subsampling_convert_log=1; } } else { sp->libjpeg_jpeg_decompress_struct.jpeg_color_space=JCS_UNKNOWN; sp->libjpeg_jpeg_decompress_struct.out_color_space=JCS_UNKNOWN; sp->libjpeg_jpeg_query_style=1; sp->bytes_per_line=sp->samples_per_pixel_per_plane*sp->strile_width; sp->lines_per_strile=sp->strile_length; } if (jpeg_start_decompress_encap(sp,&(sp->libjpeg_jpeg_decompress_struct))==0) return(0); sp->writeheader_done=1; return(1); } static void OJPEGLibjpegSessionAbort(TIFF* tif) { OJPEGState* sp=(OJPEGState*)tif->tif_data; assert(sp->libjpeg_session_active!=0); jpeg_destroy((jpeg_common_struct*)(&(sp->libjpeg_jpeg_decompress_struct))); sp->libjpeg_session_active=0; } static int OJPEGReadHeaderInfoSec(TIFF* tif) { static const char module[]="OJPEGReadHeaderInfoSec"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8 m; uint16 n; uint8 o; if (sp->file_size==0) sp->file_size=TIFFGetFileSize(tif); if (sp->jpeg_interchange_format!=0) { if (sp->jpeg_interchange_format>=sp->file_size) { sp->jpeg_interchange_format=0; sp->jpeg_interchange_format_length=0; } else { if ((sp->jpeg_interchange_format_length==0) || (sp->jpeg_interchange_format+sp->jpeg_interchange_format_length>sp->file_size)) sp->jpeg_interchange_format_length=sp->file_size-sp->jpeg_interchange_format; } } sp->in_buffer_source=osibsNotSetYet; sp->in_buffer_next_strile=0; sp->in_buffer_strile_count=tif->tif_dir.td_nstrips; sp->in_buffer_file_togo=0; sp->in_buffer_togo=0; do { if (OJPEGReadBytePeek(sp,&m)==0) return(0); if (m!=255) break; OJPEGReadByteAdvance(sp); do { if (OJPEGReadByte(sp,&m)==0) return(0); } while(m==255); switch(m) { case JPEG_MARKER_SOI: /* this type of marker has no data, and should be skipped */ break; case JPEG_MARKER_COM: case JPEG_MARKER_APP0: case JPEG_MARKER_APP0+1: case JPEG_MARKER_APP0+2: case JPEG_MARKER_APP0+3: case JPEG_MARKER_APP0+4: case JPEG_MARKER_APP0+5: case JPEG_MARKER_APP0+6: case JPEG_MARKER_APP0+7: case JPEG_MARKER_APP0+8: case JPEG_MARKER_APP0+9: case JPEG_MARKER_APP0+10: case JPEG_MARKER_APP0+11: case JPEG_MARKER_APP0+12: case JPEG_MARKER_APP0+13: case JPEG_MARKER_APP0+14: case JPEG_MARKER_APP0+15: /* this type of marker has data, but it has no use to us (and no place here) and should be skipped */ if (OJPEGReadWord(sp,&n)==0) return(0); if (n<2) { if (sp->subsamplingcorrect==0) TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JPEG data"); return(0); } if (n>2) OJPEGReadSkip(sp,n-2); break; case JPEG_MARKER_DRI: if (OJPEGReadHeaderInfoSecStreamDri(tif)==0) return(0); break; case JPEG_MARKER_DQT: if (OJPEGReadHeaderInfoSecStreamDqt(tif)==0) return(0); break; case JPEG_MARKER_DHT: if (OJPEGReadHeaderInfoSecStreamDht(tif)==0) return(0); break; case JPEG_MARKER_SOF0: case JPEG_MARKER_SOF1: case JPEG_MARKER_SOF3: if (OJPEGReadHeaderInfoSecStreamSof(tif,m)==0) return(0); if (sp->subsamplingcorrect!=0) return(1); break; case JPEG_MARKER_SOS: if (sp->subsamplingcorrect!=0) return(1); assert(sp->plane_sample_offset==0); if (OJPEGReadHeaderInfoSecStreamSos(tif)==0) return(0); break; default: TIFFErrorExt(tif->tif_clientdata,module,"Unknown marker type %d in JPEG data",m); return(0); } } while(m!=JPEG_MARKER_SOS); if (sp->subsamplingcorrect) return(1); if (sp->sof_log==0) { if (OJPEGReadHeaderInfoSecTablesQTable(tif)==0) return(0); sp->sof_marker_id=JPEG_MARKER_SOF0; for (o=0; o<sp->samples_per_pixel; o++) sp->sof_c[o]=o; sp->sof_hv[0]=((sp->subsampling_hor<<4)|sp->subsampling_ver); for (o=1; o<sp->samples_per_pixel; o++) sp->sof_hv[o]=17; sp->sof_x=sp->strile_width; sp->sof_y=sp->strile_length_total; sp->sof_log=1; if (OJPEGReadHeaderInfoSecTablesDcTable(tif)==0) return(0); if (OJPEGReadHeaderInfoSecTablesAcTable(tif)==0) return(0); for (o=1; o<sp->samples_per_pixel; o++) sp->sos_cs[o]=o; } return(1); } static int OJPEGReadHeaderInfoSecStreamDri(TIFF* tif) { /* This could easily cause trouble in some cases... but no such cases have occurred so far */ static const char module[]="OJPEGReadHeaderInfoSecStreamDri"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint16 m; if (OJPEGReadWord(sp,&m)==0) return(0); if (m!=4) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DRI marker in JPEG data"); return(0); } if (OJPEGReadWord(sp,&m)==0) return(0); sp->restart_interval=m; return(1); } static int OJPEGReadHeaderInfoSecStreamDqt(TIFF* tif) { /* this is a table marker, and it is to be saved as a whole for exact pushing on the jpeg stream later on */ static const char module[]="OJPEGReadHeaderInfoSecStreamDqt"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint16 m; uint32 na; uint8* nb; uint8 o; if (OJPEGReadWord(sp,&m)==0) return(0); if (m<=2) { if (sp->subsamplingcorrect==0) TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data"); return(0); } if (sp->subsamplingcorrect!=0) OJPEGReadSkip(sp,m-2); else { m-=2; do { if (m<65) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data"); return(0); } na=sizeof(uint32)+69; nb=_TIFFmalloc(na); if (nb==0) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } *(uint32*)nb=na; nb[sizeof(uint32)]=255; nb[sizeof(uint32)+1]=JPEG_MARKER_DQT; nb[sizeof(uint32)+2]=0; nb[sizeof(uint32)+3]=67; if (OJPEGReadBlock(sp,65,&nb[sizeof(uint32)+4])==0) { _TIFFfree(nb); return(0); } o=nb[sizeof(uint32)+4]&15; if (3<o) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data"); _TIFFfree(nb); return(0); } if (sp->qtable[o]!=0) _TIFFfree(sp->qtable[o]); sp->qtable[o]=nb; m-=65; } while(m>0); } return(1); } static int OJPEGReadHeaderInfoSecStreamDht(TIFF* tif) { /* this is a table marker, and it is to be saved as a whole for exact pushing on the jpeg stream later on */ /* TODO: the following assumes there is only one table in this marker... but i'm not quite sure that assumption is guaranteed correct */ static const char module[]="OJPEGReadHeaderInfoSecStreamDht"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint16 m; uint32 na; uint8* nb; uint8 o; if (OJPEGReadWord(sp,&m)==0) return(0); if (m<=2) { if (sp->subsamplingcorrect==0) TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data"); return(0); } if (sp->subsamplingcorrect!=0) { OJPEGReadSkip(sp,m-2); } else { na=sizeof(uint32)+2+m; nb=_TIFFmalloc(na); if (nb==0) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } *(uint32*)nb=na; nb[sizeof(uint32)]=255; nb[sizeof(uint32)+1]=JPEG_MARKER_DHT; nb[sizeof(uint32)+2]=(m>>8); nb[sizeof(uint32)+3]=(m&255); if (OJPEGReadBlock(sp,m-2,&nb[sizeof(uint32)+4])==0) { _TIFFfree(nb); return(0); } o=nb[sizeof(uint32)+4]; if ((o&240)==0) { if (3<o) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data"); _TIFFfree(nb); return(0); } if (sp->dctable[o]!=0) _TIFFfree(sp->dctable[o]); sp->dctable[o]=nb; } else { if ((o&240)!=16) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data"); _TIFFfree(nb); return(0); } o&=15; if (3<o) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data"); _TIFFfree(nb); return(0); } if (sp->actable[o]!=0) _TIFFfree(sp->actable[o]); sp->actable[o]=nb; } } return(1); } static int OJPEGReadHeaderInfoSecStreamSof(TIFF* tif, uint8 marker_id) { /* this marker needs to be checked, and part of its data needs to be saved for regeneration later on */ static const char module[]="OJPEGReadHeaderInfoSecStreamSof"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint16 m; uint16 n; uint8 o; uint16 p; uint16 q; if (sp->sof_log!=0) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JPEG data"); return(0); } if (sp->subsamplingcorrect==0) sp->sof_marker_id=marker_id; /* Lf: data length */ if (OJPEGReadWord(sp,&m)==0) return(0); if (m<11) { if (sp->subsamplingcorrect==0) TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data"); return(0); } m-=8; if (m%3!=0) { if (sp->subsamplingcorrect==0) TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data"); return(0); } n=m/3; if (sp->subsamplingcorrect==0) { if (n!=sp->samples_per_pixel) { TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected number of samples"); return(0); } } /* P: Sample precision */ if (OJPEGReadByte(sp,&o)==0) return(0); if (o!=8) { if (sp->subsamplingcorrect==0) TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected number of bits per sample"); return(0); } /* Y: Number of lines, X: Number of samples per line */ if (sp->subsamplingcorrect) OJPEGReadSkip(sp,4); else { /* Y: Number of lines */ if (OJPEGReadWord(sp,&p)==0) return(0); if (((uint32)p<sp->image_length) && ((uint32)p<sp->strile_length_total)) { TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected height"); return(0); } sp->sof_y=p; /* X: Number of samples per line */ if (OJPEGReadWord(sp,&p)==0) return(0); if (((uint32)p<sp->image_width) && ((uint32)p<sp->strile_width)) { TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected width"); return(0); } if ((uint32)p>sp->strile_width) { TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data image width exceeds expected image width"); return(0); } sp->sof_x=p; } /* Nf: Number of image components in frame */ if (OJPEGReadByte(sp,&o)==0) return(0); if (o!=n) { if (sp->subsamplingcorrect==0) TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data"); return(0); } /* per component stuff */ /* TODO: double-check that flow implies that n cannot be as big as to make us overflow sof_c, sof_hv and sof_tq arrays */ for (q=0; q<n; q++) { /* C: Component identifier */ if (OJPEGReadByte(sp,&o)==0) return(0); if (sp->subsamplingcorrect==0) sp->sof_c[q]=o; /* H: Horizontal sampling factor, and V: Vertical sampling factor */ if (OJPEGReadByte(sp,&o)==0) return(0); if (sp->subsamplingcorrect!=0) { if (q==0) { sp->subsampling_hor=(o>>4); sp->subsampling_ver=(o&15); if (((sp->subsampling_hor!=1) && (sp->subsampling_hor!=2) && (sp->subsampling_hor!=4)) || ((sp->subsampling_ver!=1) && (sp->subsampling_ver!=2) && (sp->subsampling_ver!=4))) sp->subsampling_force_desubsampling_inside_decompression=1; } else { if (o!=17) sp->subsampling_force_desubsampling_inside_decompression=1; } } else { sp->sof_hv[q]=o; if (sp->subsampling_force_desubsampling_inside_decompression==0) { if (q==0) { if (o!=((sp->subsampling_hor<<4)|sp->subsampling_ver)) { TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected subsampling values"); return(0); } } else { if (o!=17) { TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected subsampling values"); return(0); } } } } /* Tq: Quantization table destination selector */ if (OJPEGReadByte(sp,&o)==0) return(0); if (sp->subsamplingcorrect==0) sp->sof_tq[q]=o; } if (sp->subsamplingcorrect==0) sp->sof_log=1; return(1); } static int OJPEGReadHeaderInfoSecStreamSos(TIFF* tif) { /* this marker needs to be checked, and part of its data needs to be saved for regeneration later on */ static const char module[]="OJPEGReadHeaderInfoSecStreamSos"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint16 m; uint8 n; uint8 o; assert(sp->subsamplingcorrect==0); if (sp->sof_log==0) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data"); return(0); } /* Ls */ if (OJPEGReadWord(sp,&m)==0) return(0); if (m!=6+sp->samples_per_pixel_per_plane*2) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data"); return(0); } /* Ns */ if (OJPEGReadByte(sp,&n)==0) return(0); if (n!=sp->samples_per_pixel_per_plane) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data"); return(0); } /* Cs, Td, and Ta */ for (o=0; o<sp->samples_per_pixel_per_plane; o++) { /* Cs */ if (OJPEGReadByte(sp,&n)==0) return(0); sp->sos_cs[sp->plane_sample_offset+o]=n; /* Td and Ta */ if (OJPEGReadByte(sp,&n)==0) return(0); sp->sos_tda[sp->plane_sample_offset+o]=n; } /* skip Ss, Se, Ah, en Al -> no check, as per Tom Lane recommendation, as per LibJpeg source */ OJPEGReadSkip(sp,3); return(1); } static int OJPEGReadHeaderInfoSecTablesQTable(TIFF* tif) { static const char module[]="OJPEGReadHeaderInfoSecTablesQTable"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8 m; uint8 n; uint32 oa; uint8* ob; uint32 p; if (sp->qtable_offset[0]==0) { TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables"); return(0); } sp->in_buffer_file_pos_log=0; for (m=0; m<sp->samples_per_pixel; m++) { if ((sp->qtable_offset[m]!=0) && ((m==0) || (sp->qtable_offset[m]!=sp->qtable_offset[m-1]))) { for (n=0; n<m-1; n++) { if (sp->qtable_offset[m]==sp->qtable_offset[n]) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegQTables tag value"); return(0); } } oa=sizeof(uint32)+69; ob=_TIFFmalloc(oa); if (ob==0) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } *(uint32*)ob=oa; ob[sizeof(uint32)]=255; ob[sizeof(uint32)+1]=JPEG_MARKER_DQT; ob[sizeof(uint32)+2]=0; ob[sizeof(uint32)+3]=67; ob[sizeof(uint32)+4]=m; TIFFSeekFile(tif,sp->qtable_offset[m],SEEK_SET); p=(uint32)TIFFReadFile(tif,&ob[sizeof(uint32)+5],64); if (p!=64) return(0); sp->qtable[m]=ob; sp->sof_tq[m]=m; } else sp->sof_tq[m]=sp->sof_tq[m-1]; } return(1); } static int OJPEGReadHeaderInfoSecTablesDcTable(TIFF* tif) { static const char module[]="OJPEGReadHeaderInfoSecTablesDcTable"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8 m; uint8 n; uint8 o[16]; uint32 p; uint32 q; uint32 ra; uint8* rb; if (sp->dctable_offset[0]==0) { TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables"); return(0); } sp->in_buffer_file_pos_log=0; for (m=0; m<sp->samples_per_pixel; m++) { if ((sp->dctable_offset[m]!=0) && ((m==0) || (sp->dctable_offset[m]!=sp->dctable_offset[m-1]))) { for (n=0; n<m-1; n++) { if (sp->dctable_offset[m]==sp->dctable_offset[n]) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegDcTables tag value"); return(0); } } TIFFSeekFile(tif,sp->dctable_offset[m],SEEK_SET); p=(uint32)TIFFReadFile(tif,o,16); if (p!=16) return(0); q=0; for (n=0; n<16; n++) q+=o[n]; ra=sizeof(uint32)+21+q; rb=_TIFFmalloc(ra); if (rb==0) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } *(uint32*)rb=ra; rb[sizeof(uint32)]=255; rb[sizeof(uint32)+1]=JPEG_MARKER_DHT; rb[sizeof(uint32)+2]=(uint8)((19+q)>>8); rb[sizeof(uint32)+3]=((19+q)&255); rb[sizeof(uint32)+4]=m; for (n=0; n<16; n++) rb[sizeof(uint32)+5+n]=o[n]; p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q); if (p!=q) return(0); sp->dctable[m]=rb; sp->sos_tda[m]=(m<<4); } else sp->sos_tda[m]=sp->sos_tda[m-1]; } return(1); } static int OJPEGReadHeaderInfoSecTablesAcTable(TIFF* tif) { static const char module[]="OJPEGReadHeaderInfoSecTablesAcTable"; OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8 m; uint8 n; uint8 o[16]; uint32 p; uint32 q; uint32 ra; uint8* rb; if (sp->actable_offset[0]==0) { TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables"); return(0); } sp->in_buffer_file_pos_log=0; for (m=0; m<sp->samples_per_pixel; m++) { if ((sp->actable_offset[m]!=0) && ((m==0) || (sp->actable_offset[m]!=sp->actable_offset[m-1]))) { for (n=0; n<m-1; n++) { if (sp->actable_offset[m]==sp->actable_offset[n]) { TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegAcTables tag value"); return(0); } } TIFFSeekFile(tif,sp->actable_offset[m],SEEK_SET); p=(uint32)TIFFReadFile(tif,o,16); if (p!=16) return(0); q=0; for (n=0; n<16; n++) q+=o[n]; ra=sizeof(uint32)+21+q; rb=_TIFFmalloc(ra); if (rb==0) { TIFFErrorExt(tif->tif_clientdata,module,"Out of memory"); return(0); } *(uint32*)rb=ra; rb[sizeof(uint32)]=255; rb[sizeof(uint32)+1]=JPEG_MARKER_DHT; rb[sizeof(uint32)+2]=(uint8)((19+q)>>8); rb[sizeof(uint32)+3]=((19+q)&255); rb[sizeof(uint32)+4]=(16|m); for (n=0; n<16; n++) rb[sizeof(uint32)+5+n]=o[n]; p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q); if (p!=q) return(0); sp->actable[m]=rb; sp->sos_tda[m]=(sp->sos_tda[m]|m); } else sp->sos_tda[m]=(sp->sos_tda[m]|(sp->sos_tda[m-1]&15)); } return(1); } static int OJPEGReadBufferFill(OJPEGState* sp) { uint16 m; tmsize_t n; /* TODO: double-check: when subsamplingcorrect is set, no call to TIFFErrorExt or TIFFWarningExt should be made * in any other case, seek or read errors should be passed through */ do { if (sp->in_buffer_file_togo!=0) { if (sp->in_buffer_file_pos_log==0) { TIFFSeekFile(sp->tif,sp->in_buffer_file_pos,SEEK_SET); sp->in_buffer_file_pos_log=1; } m=OJPEG_BUFFER; if ((uint64)m>sp->in_buffer_file_togo) m=(uint16)sp->in_buffer_file_togo; n=TIFFReadFile(sp->tif,sp->in_buffer,(tmsize_t)m); if (n==0) return(0); assert(n>0); assert(n<=OJPEG_BUFFER); assert(n<65536); assert((uint64)n<=sp->in_buffer_file_togo); m=(uint16)n; sp->in_buffer_togo=m; sp->in_buffer_cur=sp->in_buffer; sp->in_buffer_file_togo-=m; sp->in_buffer_file_pos+=m; break; } sp->in_buffer_file_pos_log=0; switch(sp->in_buffer_source) { case osibsNotSetYet: if (sp->jpeg_interchange_format!=0) { sp->in_buffer_file_pos=sp->jpeg_interchange_format; sp->in_buffer_file_togo=sp->jpeg_interchange_format_length; } sp->in_buffer_source=osibsJpegInterchangeFormat; break; case osibsJpegInterchangeFormat: sp->in_buffer_source=osibsStrile; break; case osibsStrile: if (!_TIFFFillStriles( sp->tif ) || sp->tif->tif_dir.td_stripoffset == NULL || sp->tif->tif_dir.td_stripbytecount == NULL) return 0; if (sp->in_buffer_next_strile==sp->in_buffer_strile_count) sp->in_buffer_source=osibsEof; else { sp->in_buffer_file_pos=sp->tif->tif_dir.td_stripoffset[sp->in_buffer_next_strile]; if (sp->in_buffer_file_pos!=0) { if (sp->in_buffer_file_pos>=sp->file_size) sp->in_buffer_file_pos=0; else if (sp->tif->tif_dir.td_stripbytecount==NULL) sp->in_buffer_file_togo=sp->file_size-sp->in_buffer_file_pos; else { if (sp->tif->tif_dir.td_stripbytecount == 0) { TIFFErrorExt(sp->tif->tif_clientdata,sp->tif->tif_name,"Strip byte counts are missing"); return(0); } sp->in_buffer_file_togo=sp->tif->tif_dir.td_stripbytecount[sp->in_buffer_next_strile]; if (sp->in_buffer_file_togo==0) sp->in_buffer_file_pos=0; else if (sp->in_buffer_file_pos+sp->in_buffer_file_togo>sp->file_size) sp->in_buffer_file_togo=sp->file_size-sp->in_buffer_file_pos; } } sp->in_buffer_next_strile++; } break; default: return(0); } } while (1); return(1); } static int OJPEGReadByte(OJPEGState* sp, uint8* byte) { if (sp->in_buffer_togo==0) { if (OJPEGReadBufferFill(sp)==0) return(0); assert(sp->in_buffer_togo>0); } *byte=*(sp->in_buffer_cur); sp->in_buffer_cur++; sp->in_buffer_togo--; return(1); } static int OJPEGReadBytePeek(OJPEGState* sp, uint8* byte) { if (sp->in_buffer_togo==0) { if (OJPEGReadBufferFill(sp)==0) return(0); assert(sp->in_buffer_togo>0); } *byte=*(sp->in_buffer_cur); return(1); } static void OJPEGReadByteAdvance(OJPEGState* sp) { assert(sp->in_buffer_togo>0); sp->in_buffer_cur++; sp->in_buffer_togo--; } static int OJPEGReadWord(OJPEGState* sp, uint16* word) { uint8 m; if (OJPEGReadByte(sp,&m)==0) return(0); *word=(m<<8); if (OJPEGReadByte(sp,&m)==0) return(0); *word|=m; return(1); } static int OJPEGReadBlock(OJPEGState* sp, uint16 len, void* mem) { uint16 mlen; uint8* mmem; uint16 n; assert(len>0); mlen=len; mmem=mem; do { if (sp->in_buffer_togo==0) { if (OJPEGReadBufferFill(sp)==0) return(0); assert(sp->in_buffer_togo>0); } n=mlen; if (n>sp->in_buffer_togo) n=sp->in_buffer_togo; _TIFFmemcpy(mmem,sp->in_buffer_cur,n); sp->in_buffer_cur+=n; sp->in_buffer_togo-=n; mlen-=n; mmem+=n; } while(mlen>0); return(1); } static void OJPEGReadSkip(OJPEGState* sp, uint16 len) { uint16 m; uint16 n; m=len; n=m; if (n>sp->in_buffer_togo) n=sp->in_buffer_togo; sp->in_buffer_cur+=n; sp->in_buffer_togo-=n; m-=n; if (m>0) { assert(sp->in_buffer_togo==0); n=m; if ((uint64)n>sp->in_buffer_file_togo) n=(uint16)sp->in_buffer_file_togo; sp->in_buffer_file_pos+=n; sp->in_buffer_file_togo-=n; sp->in_buffer_file_pos_log=0; /* we don't skip past jpeginterchangeformat/strile block... * if that is asked from us, we're dealing with totally bazurk * data anyway, and we've not seen this happening on any * testfile, so we might as well likely cause some other * meaningless error to be passed at some later time */ } } static int OJPEGWriteStream(TIFF* tif, void** mem, uint32* len) { OJPEGState* sp=(OJPEGState*)tif->tif_data; *len=0; do { assert(sp->out_state<=ososEoi); switch(sp->out_state) { case ososSoi: OJPEGWriteStreamSoi(tif,mem,len); break; case ososQTable0: OJPEGWriteStreamQTable(tif,0,mem,len); break; case ososQTable1: OJPEGWriteStreamQTable(tif,1,mem,len); break; case ososQTable2: OJPEGWriteStreamQTable(tif,2,mem,len); break; case ososQTable3: OJPEGWriteStreamQTable(tif,3,mem,len); break; case ososDcTable0: OJPEGWriteStreamDcTable(tif,0,mem,len); break; case ososDcTable1: OJPEGWriteStreamDcTable(tif,1,mem,len); break; case ososDcTable2: OJPEGWriteStreamDcTable(tif,2,mem,len); break; case ososDcTable3: OJPEGWriteStreamDcTable(tif,3,mem,len); break; case ososAcTable0: OJPEGWriteStreamAcTable(tif,0,mem,len); break; case ososAcTable1: OJPEGWriteStreamAcTable(tif,1,mem,len); break; case ososAcTable2: OJPEGWriteStreamAcTable(tif,2,mem,len); break; case ososAcTable3: OJPEGWriteStreamAcTable(tif,3,mem,len); break; case ososDri: OJPEGWriteStreamDri(tif,mem,len); break; case ososSof: OJPEGWriteStreamSof(tif,mem,len); break; case ososSos: OJPEGWriteStreamSos(tif,mem,len); break; case ososCompressed: if (OJPEGWriteStreamCompressed(tif,mem,len)==0) return(0); break; case ososRst: OJPEGWriteStreamRst(tif,mem,len); break; case ososEoi: OJPEGWriteStreamEoi(tif,mem,len); break; } } while (*len==0); return(1); } static void OJPEGWriteStreamSoi(TIFF* tif, void** mem, uint32* len) { OJPEGState* sp=(OJPEGState*)tif->tif_data; assert(OJPEG_BUFFER>=2); sp->out_buffer[0]=255; sp->out_buffer[1]=JPEG_MARKER_SOI; *len=2; *mem=(void*)sp->out_buffer; sp->out_state++; } static void OJPEGWriteStreamQTable(TIFF* tif, uint8 table_index, void** mem, uint32* len) { OJPEGState* sp=(OJPEGState*)tif->tif_data; if (sp->qtable[table_index]!=0) { *mem=(void*)(sp->qtable[table_index]+sizeof(uint32)); *len=*((uint32*)sp->qtable[table_index])-sizeof(uint32); } sp->out_state++; } static void OJPEGWriteStreamDcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len) { OJPEGState* sp=(OJPEGState*)tif->tif_data; if (sp->dctable[table_index]!=0) { *mem=(void*)(sp->dctable[table_index]+sizeof(uint32)); *len=*((uint32*)sp->dctable[table_index])-sizeof(uint32); } sp->out_state++; } static void OJPEGWriteStreamAcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len) { OJPEGState* sp=(OJPEGState*)tif->tif_data; if (sp->actable[table_index]!=0) { *mem=(void*)(sp->actable[table_index]+sizeof(uint32)); *len=*((uint32*)sp->actable[table_index])-sizeof(uint32); } sp->out_state++; } static void OJPEGWriteStreamDri(TIFF* tif, void** mem, uint32* len) { OJPEGState* sp=(OJPEGState*)tif->tif_data; assert(OJPEG_BUFFER>=6); if (sp->restart_interval!=0) { sp->out_buffer[0]=255; sp->out_buffer[1]=JPEG_MARKER_DRI; sp->out_buffer[2]=0; sp->out_buffer[3]=4; sp->out_buffer[4]=(sp->restart_interval>>8); sp->out_buffer[5]=(sp->restart_interval&255); *len=6; *mem=(void*)sp->out_buffer; } sp->out_state++; } static void OJPEGWriteStreamSof(TIFF* tif, void** mem, uint32* len) { OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8 m; assert(OJPEG_BUFFER>=2+8+sp->samples_per_pixel_per_plane*3); assert(255>=8+sp->samples_per_pixel_per_plane*3); sp->out_buffer[0]=255; sp->out_buffer[1]=sp->sof_marker_id; /* Lf */ sp->out_buffer[2]=0; sp->out_buffer[3]=8+sp->samples_per_pixel_per_plane*3; /* P */ sp->out_buffer[4]=8; /* Y */ sp->out_buffer[5]=(uint8)(sp->sof_y>>8); sp->out_buffer[6]=(sp->sof_y&255); /* X */ sp->out_buffer[7]=(uint8)(sp->sof_x>>8); sp->out_buffer[8]=(sp->sof_x&255); /* Nf */ sp->out_buffer[9]=sp->samples_per_pixel_per_plane; for (m=0; m<sp->samples_per_pixel_per_plane; m++) { /* C */ sp->out_buffer[10+m*3]=sp->sof_c[sp->plane_sample_offset+m]; /* H and V */ sp->out_buffer[10+m*3+1]=sp->sof_hv[sp->plane_sample_offset+m]; /* Tq */ sp->out_buffer[10+m*3+2]=sp->sof_tq[sp->plane_sample_offset+m]; } *len=10+sp->samples_per_pixel_per_plane*3; *mem=(void*)sp->out_buffer; sp->out_state++; } static void OJPEGWriteStreamSos(TIFF* tif, void** mem, uint32* len) { OJPEGState* sp=(OJPEGState*)tif->tif_data; uint8 m; assert(OJPEG_BUFFER>=2+6+sp->samples_per_pixel_per_plane*2); assert(255>=6+sp->samples_per_pixel_per_plane*2); sp->out_buffer[0]=255; sp->out_buffer[1]=JPEG_MARKER_SOS; /* Ls */ sp->out_buffer[2]=0; sp->out_buffer[3]=6+sp->samples_per_pixel_per_plane*2; /* Ns */ sp->out_buffer[4]=sp->samples_per_pixel_per_plane; for (m=0; m<sp->samples_per_pixel_per_plane; m++) { /* Cs */ sp->out_buffer[5+m*2]=sp->sos_cs[sp->plane_sample_offset+m]; /* Td and Ta */ sp->out_buffer[5+m*2+1]=sp->sos_tda[sp->plane_sample_offset+m]; } /* Ss */ sp->out_buffer[5+sp->samples_per_pixel_per_plane*2]=0; /* Se */ sp->out_buffer[5+sp->samples_per_pixel_per_plane*2+1]=63; /* Ah and Al */ sp->out_buffer[5+sp->samples_per_pixel_per_plane*2+2]=0; *len=8+sp->samples_per_pixel_per_plane*2; *mem=(void*)sp->out_buffer; sp->out_state++; } static int OJPEGWriteStreamCompressed(TIFF* tif, void** mem, uint32* len) { OJPEGState* sp=(OJPEGState*)tif->tif_data; if (sp->in_buffer_togo==0) { if (OJPEGReadBufferFill(sp)==0) return(0); assert(sp->in_buffer_togo>0); } *len=sp->in_buffer_togo; *mem=(void*)sp->in_buffer_cur; sp->in_buffer_togo=0; if (sp->in_buffer_file_togo==0) { switch(sp->in_buffer_source) { case osibsStrile: if (sp->in_buffer_next_strile<sp->in_buffer_strile_count) sp->out_state=ososRst; else sp->out_state=ososEoi; break; case osibsEof: sp->out_state=ososEoi; break; default: break; } } return(1); } static void OJPEGWriteStreamRst(TIFF* tif, void** mem, uint32* len) { OJPEGState* sp=(OJPEGState*)tif->tif_data; assert(OJPEG_BUFFER>=2); sp->out_buffer[0]=255; sp->out_buffer[1]=JPEG_MARKER_RST0+sp->restart_index; sp->restart_index++; if (sp->restart_index==8) sp->restart_index=0; *len=2; *mem=(void*)sp->out_buffer; sp->out_state=ososCompressed; } static void OJPEGWriteStreamEoi(TIFF* tif, void** mem, uint32* len) { OJPEGState* sp=(OJPEGState*)tif->tif_data; assert(OJPEG_BUFFER>=2); sp->out_buffer[0]=255; sp->out_buffer[1]=JPEG_MARKER_EOI; *len=2; *mem=(void*)sp->out_buffer; } #ifndef LIBJPEG_ENCAP_EXTERNAL static int jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo) { if( SETJMP(sp->exit_jmpbuf) ) return 0; else { jpeg_create_decompress(cinfo); return 1; } } #endif #ifndef LIBJPEG_ENCAP_EXTERNAL static int jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image) { if( SETJMP(sp->exit_jmpbuf) ) return 0; else { jpeg_read_header(cinfo,require_image); return 1; } } #endif #ifndef LIBJPEG_ENCAP_EXTERNAL static int jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo) { if( SETJMP(sp->exit_jmpbuf) ) return 0; else { jpeg_start_decompress(cinfo); return 1; } } #endif #ifndef LIBJPEG_ENCAP_EXTERNAL static int jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines) { if( SETJMP(sp->exit_jmpbuf) ) return 0; else { jpeg_read_scanlines(cinfo,scanlines,max_lines); return 1; } } #endif #ifndef LIBJPEG_ENCAP_EXTERNAL static int jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines) { if( SETJMP(sp->exit_jmpbuf) ) return 0; else { jpeg_read_raw_data(cinfo,data,max_lines); return 1; } } #endif #ifndef LIBJPEG_ENCAP_EXTERNAL static void jpeg_encap_unwind(TIFF* tif) { OJPEGState* sp=(OJPEGState*)tif->tif_data; LONGJMP(sp->exit_jmpbuf,1); } #endif static void OJPEGLibjpegJpegErrorMgrOutputMessage(jpeg_common_struct* cinfo) { char buffer[JMSG_LENGTH_MAX]; (*cinfo->err->format_message)(cinfo,buffer); TIFFWarningExt(((TIFF*)(cinfo->client_data))->tif_clientdata,"LibJpeg","%s",buffer); } static void OJPEGLibjpegJpegErrorMgrErrorExit(jpeg_common_struct* cinfo) { char buffer[JMSG_LENGTH_MAX]; (*cinfo->err->format_message)(cinfo,buffer); TIFFErrorExt(((TIFF*)(cinfo->client_data))->tif_clientdata,"LibJpeg","%s",buffer); jpeg_encap_unwind((TIFF*)(cinfo->client_data)); } static void OJPEGLibjpegJpegSourceMgrInitSource(jpeg_decompress_struct* cinfo) { (void)cinfo; } static boolean OJPEGLibjpegJpegSourceMgrFillInputBuffer(jpeg_decompress_struct* cinfo) { TIFF* tif=(TIFF*)cinfo->client_data; OJPEGState* sp=(OJPEGState*)tif->tif_data; void* mem=0; uint32 len=0U; if (OJPEGWriteStream(tif,&mem,&len)==0) { TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Premature end of JPEG data"); jpeg_encap_unwind(tif); } sp->libjpeg_jpeg_source_mgr.bytes_in_buffer=len; sp->libjpeg_jpeg_source_mgr.next_input_byte=mem; return(1); } static void OJPEGLibjpegJpegSourceMgrSkipInputData(jpeg_decompress_struct* cinfo, long num_bytes) { TIFF* tif=(TIFF*)cinfo->client_data; (void)num_bytes; TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Unexpected error"); jpeg_encap_unwind(tif); } #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable : 4702 ) /* unreachable code */ #endif static boolean OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct* cinfo, int desired) { TIFF* tif=(TIFF*)cinfo->client_data; (void)desired; TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Unexpected error"); jpeg_encap_unwind(tif); return(0); } #ifdef _MSC_VER #pragma warning( pop ) #endif static void OJPEGLibjpegJpegSourceMgrTermSource(jpeg_decompress_struct* cinfo) { (void)cinfo; } #endif /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-369/c/bad_4854_1
crossvul-cpp_data_good_4413_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % L AAA Y Y EEEEE RRRR % % L A A Y Y E R R % % L AAAAA Y EEE RRRR % % L A A Y E R R % % LLLLL A A Y EEEEE R R % % % % MagickCore Image Layering Methods % % % % Software Design % % Cristy % % Anthony Thyssen % % January 2006 % % % % % % Copyright 1999-2020 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://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/artifact.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/composite.h" #include "MagickCore/effect.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/profile.h" #include "MagickCore/resource_.h" #include "MagickCore/resize.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l e a r B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClearBounds() Clear the area specified by the bounds in an image to % transparency. This typically used to handle Background Disposal for the % previous frame in an animation sequence. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % void ClearBounds(Image *image,RectangleInfo *bounds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to had the area cleared in % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static void ClearBounds(Image *image,RectangleInfo *bounds, ExceptionInfo *exception) { ssize_t y; if (bounds->x < 0) return; if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); for (y=0; y < (ssize_t) bounds->height; y++) { register ssize_t x; register Quantum *magick_restrict q; q=GetAuthenticPixels(image,bounds->x,bounds->y+y,bounds->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) bounds->width; x++) { SetPixelAlpha(image,TransparentAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s B o u n d s C l e a r e d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsBoundsCleared() tests whether any pixel in the bounds given, gets cleared % when going from the first image to the second image. This typically used % to check if a proposed disposal method will work successfully to generate % the second frame image from the first disposed form of the previous frame. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % MagickBooleanType IsBoundsCleared(const Image *image1, % const Image *image2,RectangleInfo bounds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image1, image 2: the images to check for cleared pixels % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsBoundsCleared(const Image *image1, const Image *image2,RectangleInfo *bounds,ExceptionInfo *exception) { register const Quantum *p, *q; register ssize_t x; ssize_t y; if (bounds->x < 0) return(MagickFalse); for (y=0; y < (ssize_t) bounds->height; y++) { p=GetVirtualPixels(image1,bounds->x,bounds->y+y,bounds->width,1,exception); q=GetVirtualPixels(image2,bounds->x,bounds->y+y,bounds->width,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) bounds->width; x++) { if ((GetPixelAlpha(image1,p) >= (Quantum) (QuantumRange/2)) && (GetPixelAlpha(image2,q) < (Quantum) (QuantumRange/2))) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) bounds->width) break; } return(y < (ssize_t) bounds->height ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o a l e s c e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CoalesceImages() composites a set of images while respecting any page % offsets and disposal methods. GIF, MIFF, and MNG animation sequences % typically start with an image background and each subsequent image % varies in size and offset. A new image sequence is returned with all % images the same size as the first images virtual canvas and composited % with the next image in the sequence. % % The format of the CoalesceImages method is: % % Image *CoalesceImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CoalesceImages(const Image *image,ExceptionInfo *exception) { Image *coalesce_image, *dispose_image, *previous; register Image *next; RectangleInfo bounds; /* Coalesce the image sequence. */ 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); next=GetFirstImageInList(image); bounds=next->page; if (bounds.width == 0) { bounds.width=next->columns; if (bounds.x > 0) bounds.width+=bounds.x; } if (bounds.height == 0) { bounds.height=next->rows; if (bounds.y > 0) bounds.height+=bounds.y; } bounds.x=0; bounds.y=0; coalesce_image=CloneImage(next,bounds.width,bounds.height,MagickTrue, exception); if (coalesce_image == (Image *) NULL) return((Image *) NULL); coalesce_image->background_color.alpha_trait=BlendPixelTrait; coalesce_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(coalesce_image,exception); coalesce_image->alpha_trait=next->alpha_trait; coalesce_image->page=bounds; coalesce_image->dispose=NoneDispose; /* Coalesce rest of the images. */ dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); if (dispose_image == (Image *) NULL) { coalesce_image=DestroyImage(coalesce_image); return((Image *) NULL); } dispose_image->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(coalesce_image,next,CopyCompositeOp,MagickTrue, next->page.x,next->page.y,exception); next=GetNextImageInList(next); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { const char *attribute; /* Determine the bounds that was overlaid in the previous image. */ previous=GetPreviousImageInList(next); bounds=previous->page; bounds.width=previous->columns; bounds.height=previous->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) coalesce_image->columns) bounds.width=coalesce_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) coalesce_image->rows) bounds.height=coalesce_image->rows-bounds.y; /* Replace the dispose image with the new coalesced image. */ if (GetPreviousImageInList(next)->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); if (dispose_image == (Image *) NULL) { coalesce_image=DestroyImageList(coalesce_image); return((Image *) NULL); } dispose_image->background_color.alpha_trait=BlendPixelTrait; } /* Clear the overlaid area of the coalesced bounds for background disposal */ if (next->previous->dispose == BackgroundDispose) ClearBounds(dispose_image,&bounds,exception); /* Next image is the dispose image, overlaid with next frame in sequence. */ coalesce_image->next=CloneImage(dispose_image,0,0,MagickTrue,exception); coalesce_image->next->previous=coalesce_image; previous=coalesce_image; coalesce_image=GetNextImageInList(coalesce_image); coalesce_image->background_color.alpha_trait=BlendPixelTrait; attribute=GetImageProperty(next,"webp:mux-blend",exception); if (attribute == (const char *) NULL) (void) CompositeImage(coalesce_image,next, next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp,MagickTrue,next->page.x,next->page.y,exception); else (void) CompositeImage(coalesce_image,next, LocaleCompare(attribute,"AtopBackgroundAlphaBlend") == 0 ? OverCompositeOp : CopyCompositeOp,MagickTrue,next->page.x,next->page.y, exception); (void) CloneImageProfiles(coalesce_image,next); (void) CloneImageProperties(coalesce_image,next); (void) CloneImageArtifacts(coalesce_image,next); coalesce_image->page=previous->page; /* If a pixel goes opaque to transparent, use background dispose. */ if (IsBoundsCleared(previous,coalesce_image,&bounds,exception) != MagickFalse) coalesce_image->dispose=BackgroundDispose; else coalesce_image->dispose=NoneDispose; previous->dispose=coalesce_image->dispose; } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(coalesce_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D i s p o s e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisposeImages() returns the coalesced frames of a GIF animation as it would % appear after the GIF dispose method of that frame has been applied. That is % it returned the appearance of each frame before the next is overlaid. % % The format of the DisposeImages method is: % % Image *DisposeImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *DisposeImages(const Image *images,ExceptionInfo *exception) { Image *dispose_image, *dispose_images; RectangleInfo bounds; register Image *image, *next; /* Run the image through the animation sequence */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(images); dispose_image=CloneImage(image,image->page.width,image->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return((Image *) NULL); dispose_image->page=image->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.alpha_trait=BlendPixelTrait; dispose_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(dispose_image,exception); dispose_images=NewImageList(); for (next=image; image != (Image *) NULL; image=GetNextImageInList(image)) { Image *current_image; /* Overlay this frame's image over the previous disposal image. */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } current_image->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(current_image,next, next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp, MagickTrue,next->page.x,next->page.y,exception); /* Handle Background dispose: image is displayed for the delay period. */ if (next->dispose == BackgroundDispose) { bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds,exception); } /* Select the appropriate previous/disposed image. */ if (next->dispose == PreviousDispose) current_image=DestroyImage(current_image); else { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; current_image=(Image *) NULL; } /* Save the dispose image just calculated for return. */ { Image *dispose; dispose=CloneImage(dispose_image,0,0,MagickTrue,exception); if (dispose == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } dispose_image->background_color.alpha_trait=BlendPixelTrait; (void) CloneImageProfiles(dispose,next); (void) CloneImageProperties(dispose,next); (void) CloneImageArtifacts(dispose,next); dispose->page.x=0; dispose->page.y=0; dispose->dispose=next->dispose; AppendImageToList(&dispose_images,dispose); } } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(dispose_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComparePixels() Compare the two pixels and return true if the pixels % differ according to the given LayerType comparision method. % % This currently only used internally by CompareImagesBounds(). It is % doubtful that this sub-routine will be useful outside this module. % % The format of the ComparePixels method is: % % MagickBooleanType *ComparePixels(const LayerMethod method, % const PixelInfo *p,const PixelInfo *q) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o p, q: the pixels to test for appropriate differences. % */ static MagickBooleanType ComparePixels(const LayerMethod method, const PixelInfo *p,const PixelInfo *q) { double o1, o2; /* Any change in pixel values */ if (method == CompareAnyLayer) return(IsFuzzyEquivalencePixelInfo(p,q) == MagickFalse ? MagickTrue : MagickFalse); o1 = (p->alpha_trait != UndefinedPixelTrait) ? p->alpha : OpaqueAlpha; o2 = (q->alpha_trait != UndefinedPixelTrait) ? q->alpha : OpaqueAlpha; /* Pixel goes from opaque to transprency. */ if (method == CompareClearLayer) return((MagickBooleanType) ( (o1 >= ((double) QuantumRange/2.0)) && (o2 < ((double) QuantumRange/2.0)) ) ); /* Overlay would change first pixel by second. */ if (method == CompareOverlayLayer) { if (o2 < ((double) QuantumRange/2.0)) return MagickFalse; return(IsFuzzyEquivalencePixelInfo(p,q) == MagickFalse ? MagickTrue : MagickFalse); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e I m a g e B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImagesBounds() Given two images return the smallest rectangular area % by which the two images differ, accourding to the given 'Compare...' % layer method. % % This currently only used internally in this module, but may eventually % be used by other modules. % % The format of the CompareImagesBounds method is: % % RectangleInfo *CompareImagesBounds(const LayerMethod method, % const Image *image1,const Image *image2,ExceptionInfo *exception) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of CompareAnyLayer, % CompareClearLayer, CompareOverlayLayer. % % o image1, image2: the two images to compare. % % o exception: return any errors or warnings in this structure. % */ static RectangleInfo CompareImagesBounds(const Image *image1, const Image *image2,const LayerMethod method,ExceptionInfo *exception) { RectangleInfo bounds; PixelInfo pixel1, pixel2; register const Quantum *p, *q; register ssize_t x; ssize_t y; /* Set bounding box of the differences between images. */ GetPixelInfo(image1,&pixel1); GetPixelInfo(image2,&pixel2); for (x=0; x < (ssize_t) image1->columns; x++) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (y=0; y < (ssize_t) image1->rows; y++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (y < (ssize_t) image1->rows) break; } if (x >= (ssize_t) image1->columns) { /* Images are identical, return a null image. */ bounds.x=-1; bounds.y=-1; bounds.width=1; bounds.height=1; return(bounds); } bounds.x=x; for (x=(ssize_t) image1->columns-1; x >= 0; x--) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (y=0; y < (ssize_t) image1->rows; y++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (y < (ssize_t) image1->rows) break; } bounds.width=(size_t) (x-bounds.x+1); for (y=0; y < (ssize_t) image1->rows; y++) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image1->columns; x++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) image1->columns) break; } bounds.y=y; for (y=(ssize_t) image1->rows-1; y >= 0; y--) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image1->columns; x++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) image1->columns) break; } bounds.height=(size_t) (y-bounds.y+1); return(bounds); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p a r e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImagesLayers() compares each image with the next in a sequence and % returns the minimum bounding region of all the pixel differences (of the % LayerMethod specified) it discovers. % % Images do NOT have to be the same size, though it is best that all the % images are 'coalesced' (images are all the same size, on a flattened % canvas, so as to represent exactly how an specific frame should look). % % No GIF dispose methods are applied, so GIF animations must be coalesced % before applying this image operator to find differences to them. % % The format of the CompareImagesLayers method is: % % Image *CompareImagesLayers(const Image *images, % const LayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers type to compare images with. Must be one of... % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CompareImagesLayers(const Image *image, const LayerMethod method,ExceptionInfo *exception) { Image *image_a, *image_b, *layers; RectangleInfo *bounds; register const Image *next; register ssize_t i; assert(image != (const 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); assert((method == CompareAnyLayer) || (method == CompareClearLayer) || (method == CompareOverlayLayer)); /* Allocate bounds memory. */ next=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(next),sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Set up first comparision images. */ image_a=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (image_a == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_a->background_color.alpha_trait=BlendPixelTrait; image_a->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(image_a,exception); image_a->page=next->page; image_a->page.x=0; image_a->page.y=0; (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); /* Compute the bounding box of changes for the later images */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { image_b=CloneImage(image_a,0,0,MagickTrue,exception); if (image_b == (Image *) NULL) { image_a=DestroyImage(image_a); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_b->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); bounds[i]=CompareImagesBounds(image_b,image_a,method,exception); image_b=DestroyImage(image_b); i++; } image_a=DestroyImage(image_a); /* Clone first image in sequence. */ next=GetFirstImageInList(image); layers=CloneImage(next,0,0,MagickTrue,exception); if (layers == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } layers->background_color.alpha_trait=BlendPixelTrait; /* Deconstruct the image sequence. */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { if ((bounds[i].x == -1) && (bounds[i].y == -1) && (bounds[i].width == 1) && (bounds[i].height == 1)) { /* An empty frame is returned from CompareImageBounds(), which means the current frame is identical to the previous frame. */ i++; continue; } image_a=CloneImage(next,0,0,MagickTrue,exception); if (image_a == (Image *) NULL) break; image_a->background_color.alpha_trait=BlendPixelTrait; image_b=CropImage(image_a,&bounds[i],exception); image_a=DestroyImage(image_a); if (image_b == (Image *) NULL) break; AppendImageToList(&layers,image_b); i++; } bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); if (next != (Image *) NULL) { layers=DestroyImageList(layers); return((Image *) NULL); } return(GetFirstImageInList(layers)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p t i m i z e L a y e r F r a m e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeLayerFrames() takes a coalesced GIF animation, and compares each % frame against the three different 'disposal' forms of the previous frame. % From this it then attempts to select the smallest cropped image and % disposal method needed to reproduce the resulting image. % % Note that this not easy, and may require the expansion of the bounds % of previous frame, simply clear pixels for the next animation frame to % transparency according to the selected dispose method. % % The format of the OptimizeLayerFrames method is: % % Image *OptimizeLayerFrames(const Image *image, % const LayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers technique to optimize with. Must be one of... % OptimizeImageLayer, or OptimizePlusLayer. The Plus form allows % the addition of extra 'zero delay' frames to clear pixels from % the previous frame, and the removal of frames that done change, % merging the delay times together. % % o exception: return any errors or warnings in this structure. % */ /* Define a 'fake' dispose method where the frame is duplicated, (for OptimizePlusLayer) with a extra zero time delay frame which does a BackgroundDisposal to clear the pixels that need to be cleared. */ #define DupDispose ((DisposeType)9) /* Another 'fake' dispose method used to removed frames that don't change. */ #define DelDispose ((DisposeType)8) #define DEBUG_OPT_FRAME 0 static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method, ExceptionInfo *exception) { ExceptionInfo *sans_exception; Image *prev_image, *dup_image, *bgnd_image, *optimized_image; RectangleInfo try_bounds, bgnd_bounds, dup_bounds, *bounds; MagickBooleanType add_frames, try_cleared, cleared; DisposeType *disposals; register const Image *curr; register ssize_t i; assert(image != (const 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); assert(method == OptimizeLayer || method == OptimizeImageLayer || method == OptimizePlusLayer); /* Are we allowed to add/remove frames from animation? */ add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse; /* Ensure all the images are the same size. */ curr=GetFirstImageInList(image); for (; curr != (Image *) NULL; curr=GetNextImageInList(curr)) { if ((curr->columns != image->columns) || (curr->rows != image->rows)) ThrowImageException(OptionError,"ImagesAreNotTheSameSize"); if ((curr->page.x != 0) || (curr->page.y != 0) || (curr->page.width != image->page.width) || (curr->page.height != image->page.height)) ThrowImageException(OptionError,"ImagePagesAreNotCoalesced"); } /* Allocate memory (times 2 if we allow the use of frame duplications) */ curr=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); disposals=(DisposeType *) AcquireQuantumMemory((size_t) GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*disposals)); if (disposals == (DisposeType *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialise Previous Image as fully transparent */ prev_image=CloneImage(curr,curr->columns,curr->rows,MagickTrue,exception); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */ prev_image->page.x=0; prev_image->page.y=0; prev_image->dispose=NoneDispose; prev_image->background_color.alpha_trait=BlendPixelTrait; prev_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(prev_image,exception); /* Figure out the area of overlay of the first frame No pixel could be cleared as all pixels are already cleared. */ #if DEBUG_OPT_FRAME i=0; (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif disposals[0]=NoneDispose; bounds[0]=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g\n\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); #endif /* Compute the bounding box of changes for each pair of images. */ i=1; bgnd_image=(Image *) NULL; dup_image=(Image *) NULL; dup_bounds.width=0; dup_bounds.height=0; dup_bounds.x=0; dup_bounds.y=0; curr=GetNextImageInList(curr); for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr)) { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif /* Assume none disposal is the best */ bounds[i]=CompareImagesBounds(curr->previous,curr,CompareAnyLayer,exception); cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception); disposals[i-1]=NoneDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g%s%s\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y, bounds[i].x < 0?" (unchanged)":"", cleared?" (pixels cleared)":""); #endif if ( bounds[i].x < 0 ) { /* Image frame is exactly the same as the previous frame! If not adding frames leave it to be cropped down to a null image. Otherwise mark previous image for deleted, transfering its crop bounds to the current image. */ if ( add_frames && i>=2 ) { disposals[i-1]=DelDispose; disposals[i]=NoneDispose; bounds[i]=bounds[i-1]; i++; continue; } } else { /* Compare a none disposal against a previous disposal */ try_bounds=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "test_prev: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels were cleared)":""); #endif if ( (!try_cleared && cleared ) || try_bounds.width * try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=try_cleared; bounds[i]=try_bounds; disposals[i-1]=PreviousDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"previous: accepted\n"); } else { (void) FormatLocaleFile(stderr,"previous: rejected\n"); #endif } /* If we are allowed lets try a complex frame duplication. It is useless if the previous image already clears pixels correctly. This method will always clear all the pixels that need to be cleared. */ dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */ if ( add_frames ) { dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (dup_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); return((Image *) NULL); } dup_image->background_color.alpha_trait=BlendPixelTrait; dup_bounds=CompareImagesBounds(dup_image,curr,CompareClearLayer,exception); ClearBounds(dup_image,&dup_bounds,exception); try_bounds=CompareImagesBounds(dup_image,curr,CompareAnyLayer,exception); if ( cleared || dup_bounds.width*dup_bounds.height +try_bounds.width*try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=MagickFalse; bounds[i]=try_bounds; disposals[i-1]=DupDispose; /* to be finalised later, if found to be optimial */ } else dup_bounds.width=dup_bounds.height=0; } /* Now compare against a simple background disposal */ bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (bgnd_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); return((Image *) NULL); } bgnd_image->background_color.alpha_trait=BlendPixelTrait; bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */ ClearBounds(bgnd_image,&bgnd_bounds,exception); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "background: %s\n", try_cleared?"(pixels cleared)":""); #endif if ( try_cleared ) { /* Straight background disposal failed to clear pixels needed! Lets try expanding the disposal area of the previous frame, to include the pixels that are cleared. This guaranteed to work, though may not be the most optimized solution. */ try_bounds=CompareImagesBounds(curr->previous,curr,CompareClearLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_clear: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_bounds.x<0?" (no expand nessary)":""); #endif if ( bgnd_bounds.x < 0 ) bgnd_bounds = try_bounds; else { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_bgnd: %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif if ( try_bounds.x < bgnd_bounds.x ) { bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; bgnd_bounds.x = try_bounds.x; } else { try_bounds.width += try_bounds.x - bgnd_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; } if ( try_bounds.y < bgnd_bounds.y ) { bgnd_bounds.height += bgnd_bounds.y - try_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; bgnd_bounds.y = try_bounds.y; } else { try_bounds.height += try_bounds.y - bgnd_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; } #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, " to : %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif } ClearBounds(bgnd_image,&bgnd_bounds,exception); #if DEBUG_OPT_FRAME /* Something strange is happening with a specific animation * CompareAnyLayers (normal method) and CompareClearLayers returns the whole * image, which is not posibly correct! As verified by previous tests. * Something changed beyond the bgnd_bounds clearing. But without being able * to see, or writet he image at this point it is hard to tell what is wrong! * Only CompareOverlay seemed to return something sensible. */ try_bounds=CompareImagesBounds(bgnd_image,curr,CompareClearLayer,exception); (void) FormatLocaleFile(stderr, "expand_ctst: %.20gx%.20g%+.20g%+.20g\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y ); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_any : %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif try_bounds=CompareImagesBounds(bgnd_image,curr,CompareOverlayLayer,exception); #if DEBUG_OPT_FRAME try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_test: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif } /* Test if this background dispose is smaller than any of the other methods we tryed before this (including duplicated frame) */ if ( cleared || bgnd_bounds.width*bgnd_bounds.height +try_bounds.width*try_bounds.height < bounds[i-1].width*bounds[i-1].height +dup_bounds.width*dup_bounds.height +bounds[i].width*bounds[i].height ) { cleared=MagickFalse; bounds[i-1]=bgnd_bounds; bounds[i]=try_bounds; if ( disposals[i-1] == DupDispose ) dup_image=DestroyImage(dup_image); disposals[i-1]=BackgroundDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"expand_bgnd: accepted\n"); } else { (void) FormatLocaleFile(stderr,"expand_bgnd: reject\n"); #endif } } /* Finalise choice of dispose, set new prev_image, and junk any extra images as appropriate, */ if ( disposals[i-1] == DupDispose ) { if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); prev_image=DestroyImage(prev_image); prev_image=dup_image, dup_image=(Image *) NULL; bounds[i+1]=bounds[i]; bounds[i]=dup_bounds; disposals[i-1]=DupDispose; disposals[i]=BackgroundDispose; i++; } else { if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); if ( disposals[i-1] != PreviousDispose ) prev_image=DestroyImage(prev_image); if ( disposals[i-1] == BackgroundDispose ) prev_image=bgnd_image, bgnd_image=(Image *) NULL; if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); if ( disposals[i-1] == NoneDispose ) { prev_image=ReferenceImage(curr->previous); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } } } assert(prev_image != (Image *) NULL); disposals[i]=disposals[i-1]; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "final %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i-1, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]), (double) bounds[i-1].width,(double) bounds[i-1].height, (double) bounds[i-1].x,(double) bounds[i-1].y ); #endif #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "interum %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]), (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); (void) FormatLocaleFile(stderr,"\n"); #endif i++; } prev_image=DestroyImage(prev_image); /* Optimize all images in sequence. */ sans_exception=AcquireExceptionInfo(); i=0; curr=GetFirstImageInList(image); optimized_image=NewImageList(); while ( curr != (const Image *) NULL ) { prev_image=CloneImage(curr,0,0,MagickTrue,exception); if (prev_image == (Image *) NULL) break; prev_image->background_color.alpha_trait=BlendPixelTrait; if ( disposals[i] == DelDispose ) { size_t time = 0; while ( disposals[i] == DelDispose ) { time +=(size_t) (curr->delay*1000* PerceptibleReciprocal((double) curr->ticks_per_second)); curr=GetNextImageInList(curr); i++; } time += (size_t)(curr->delay*1000* PerceptibleReciprocal((double) curr->ticks_per_second)); prev_image->ticks_per_second = 100L; prev_image->delay = time*prev_image->ticks_per_second/1000; } bgnd_image=CropImage(prev_image,&bounds[i],sans_exception); prev_image=DestroyImage(prev_image); if (bgnd_image == (Image *) NULL) break; bgnd_image->dispose=disposals[i]; if ( disposals[i] == DupDispose ) { bgnd_image->delay=0; bgnd_image->dispose=NoneDispose; } else curr=GetNextImageInList(curr); AppendImageToList(&optimized_image,bgnd_image); i++; } sans_exception=DestroyExceptionInfo(sans_exception); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); if (curr != (Image *) NULL) { optimized_image=DestroyImageList(optimized_image); return((Image *) NULL); } return(GetFirstImageInList(optimized_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageLayers() compares each image the GIF disposed forms of the % previous image in the sequence. From this it attempts to select the % smallest cropped image to replace each frame, while preserving the results % of the GIF animation. % % The format of the OptimizeImageLayers method is: % % Image *OptimizeImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizeImageLayers(const Image *image, ExceptionInfo *exception) { return(OptimizeLayerFrames(image,OptimizeImageLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e P l u s I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImagePlusLayers() is exactly as OptimizeImageLayers(), but may % also add or even remove extra frames in the animation, if it improves % the total number of pixels in the resulting GIF animation. % % The format of the OptimizePlusImageLayers method is: % % Image *OptimizePlusImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizePlusImageLayers(const Image *image, ExceptionInfo *exception) { return OptimizeLayerFrames(image,OptimizePlusLayer,exception); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e T r a n s p a r e n c y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageTransparency() takes a frame optimized GIF animation, and % compares the overlayed pixels against the disposal image resulting from all % the previous frames in the animation. Any pixel that does not change the % disposal image (and thus does not effect the outcome of an overlay) is made % transparent. % % WARNING: This modifies the current images directly, rather than generate % a new image sequence. % % The format of the OptimizeImageTransperency method is: % % void OptimizeImageTransperency(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence % % o exception: return any errors or warnings in this structure. % */ MagickExport void OptimizeImageTransparency(const Image *image, ExceptionInfo *exception) { Image *dispose_image; register Image *next; /* Run the image through the animation sequence */ 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); next=GetFirstImageInList(image); dispose_image=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return; dispose_image->page=next->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.alpha_trait=BlendPixelTrait; dispose_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(dispose_image,exception); while ( next != (Image *) NULL ) { Image *current_image; /* Overlay this frame's image over the previous disposal image */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_image=DestroyImage(dispose_image); return; } current_image->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(current_image,next,next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp,MagickTrue,next->page.x,next->page.y, exception); /* At this point the image would be displayed, for the delay period ** Work out the disposal of the previous image */ if (next->dispose == BackgroundDispose) { RectangleInfo bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds,exception); } if (next->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; } else current_image=DestroyImage(current_image); /* Optimize Transparency of the next frame (if present) */ next=GetNextImageInList(next); if (next != (Image *) NULL) { (void) CompositeImage(next,dispose_image,ChangeMaskCompositeOp, MagickTrue,-(next->page.x),-(next->page.y),exception); } } dispose_image=DestroyImage(dispose_image); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e D u p l i c a t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveDuplicateLayers() removes any image that is exactly the same as the % next image in the given image list. Image size and virtual canvas offset % must also match, though not the virtual canvas size itself. % % No check is made with regards to image disposal setting, though it is the % dispose setting of later image that is kept. Also any time delays are also % added together. As such coalesced image animations should still produce the % same result, though with duplicte frames merged into a single frame. % % The format of the RemoveDuplicateLayers method is: % % void RemoveDuplicateLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception) { RectangleInfo bounds; register Image *image, *next; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(*images); for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next) { if ((image->columns != next->columns) || (image->rows != next->rows) || (image->page.x != next->page.x) || (image->page.y != next->page.y)) continue; bounds=CompareImagesBounds(image,next,CompareAnyLayer,exception); if (bounds.x < 0) { /* Two images are the same, merge time delays and delete one. */ size_t time; time=(size_t) (1000.0*image->delay* PerceptibleReciprocal((double) image->ticks_per_second)); time+=(size_t) (1000.0*next->delay* PerceptibleReciprocal((double) next->ticks_per_second)); next->ticks_per_second=100L; next->delay=time*image->ticks_per_second/1000; next->iterations=image->iterations; *images=image; (void) DeleteImageFromList(images); } } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e Z e r o D e l a y L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveZeroDelayLayers() removes any image that as a zero delay time. Such % images generally represent intermediate or partial updates in GIF % animations used for file optimization. They are not ment to be displayed % to users of the animation. Viewable images in an animation should have a % time delay of 3 or more centi-seconds (hundredths of a second). % % However if all the frames have a zero time delay, then either the animation % is as yet incomplete, or it is not a GIF animation. This a non-sensible % situation, so no image will be removed and a 'Zero Time Animation' warning % (exception) given. % % No warning will be given if no image was removed because all images had an % appropriate non-zero time delay set. % % Due to the special requirements of GIF disposal handling, GIF animations % should be coalesced first, before calling this function, though that is not % a requirement. % % The format of the RemoveZeroDelayLayers method is: % % void RemoveZeroDelayLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveZeroDelayLayers(Image **images, ExceptionInfo *exception) { Image *i; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); i=GetFirstImageInList(*images); for ( ; i != (Image *) NULL; i=GetNextImageInList(i)) if ( i->delay != 0L ) break; if ( i == (Image *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ZeroTimeAnimation","`%s'",GetFirstImageInList(*images)->filename); return; } i=GetFirstImageInList(*images); while ( i != (Image *) NULL ) { if ( i->delay == 0L ) { (void) DeleteImageFromList(&i); *images=i; } else i=GetNextImageInList(i); } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeLayers() compose the source image sequence over the destination % image sequence, starting with the current image in both lists. % % Each layer from the two image lists are composted together until the end of % one of the image lists is reached. The offset of each composition is also % adjusted to match the virtual canvas offsets of each layer. As such the % given offset is relative to the virtual canvas, and not the actual image. % % Composition uses given x and y offsets, as the 'origin' location of the % source images virtual canvas (not the real image) allowing you to compose a % list of 'layer images' into the destiantioni images. This makes it well % sutiable for directly composing 'Clears Frame Animations' or 'Coaleased % Animations' onto a static or other 'Coaleased Animation' destination image % list. GIF disposal handling is not looked at. % % Special case:- If one of the image sequences is the last image (just a % single image remaining), that image is repeatally composed with all the % images in the other image list. Either the source or destination lists may % be the single image, for this situation. % % In the case of a single destination image (or last image given), that image % will ve cloned to match the number of images remaining in the source image % list. % % This is equivelent to the "-layer Composite" Shell API operator. % % % The format of the CompositeLayers method is: % % void CompositeLayers(Image *destination, const CompositeOperator % compose, Image *source, const ssize_t x_offset, const ssize_t y_offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o destination: the destination images and results % % o source: source image(s) for the layer composition % % o compose, x_offset, y_offset: arguments passed on to CompositeImages() % % o exception: return any errors or warnings in this structure. % */ static inline void CompositeCanvas(Image *destination, const CompositeOperator compose,Image *source,ssize_t x_offset, ssize_t y_offset,ExceptionInfo *exception) { const char *value; x_offset+=source->page.x-destination->page.x; y_offset+=source->page.y-destination->page.y; value=GetImageArtifact(source,"compose:outside-overlay"); (void) CompositeImage(destination,source,compose, (value != (const char *) NULL) && (IsStringTrue(value) != MagickFalse) ? MagickFalse : MagickTrue,x_offset,y_offset,exception); } MagickExport void CompositeLayers(Image *destination, const CompositeOperator compose, Image *source,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { assert(destination != (Image *) NULL); assert(destination->signature == MagickCoreSignature); assert(source != (Image *) NULL); assert(source->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (source->debug != MagickFalse || destination->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s - %s", source->filename,destination->filename); /* Overlay single source image over destation image/list */ if ( source->next == (Image *) NULL ) while ( destination != (Image *) NULL ) { CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); destination=GetNextImageInList(destination); } /* Overlay source image list over single destination. Multiple clones of destination image are created to match source list. Original Destination image becomes first image of generated list. As such the image list pointer does not require any change in caller. Some animation attributes however also needs coping in this case. */ else if ( destination->next == (Image *) NULL ) { Image *dest = CloneImage(destination,0,0,MagickTrue,exception); if (dest != (Image *) NULL) { dest->background_color.alpha_trait=BlendPixelTrait; CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); /* copy source image attributes ? */ if ( source->next != (Image *) NULL ) { destination->delay=source->delay; destination->iterations=source->iterations; } source=GetNextImageInList(source); while (source != (Image *) NULL) { AppendImageToList(&destination, CloneImage(dest,0,0,MagickTrue,exception)); destination->background_color.alpha_trait=BlendPixelTrait; destination=GetLastImageInList(destination); CompositeCanvas(destination,compose,source,x_offset,y_offset, exception); destination->delay=source->delay; destination->iterations=source->iterations; source=GetNextImageInList(source); } dest=DestroyImage(dest); } } /* Overlay a source image list over a destination image list until either list runs out of images. (Does not repeat) */ else while ( source != (Image *) NULL && destination != (Image *) NULL ) { CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); source=GetNextImageInList(source); destination=GetNextImageInList(destination); } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e r g e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MergeImageLayers() composes all the image layers from the current given % image onward to produce a single image of the merged layers. % % The inital canvas's size depends on the given LayerMethod, and is % initialized using the first images background color. The images % are then compositied onto that image in sequence using the given % composition that has been assigned to each individual image. % % The format of the MergeImageLayers is: % % Image *MergeImageLayers(Image *image,const LayerMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image list to be composited together % % o method: the method of selecting the size of the initial canvas. % % MergeLayer: Merge all layers onto a canvas just large enough % to hold all the actual images. The virtual canvas of the % first image is preserved but otherwise ignored. % % FlattenLayer: Use the virtual canvas size of first image. % Images which fall outside this canvas is clipped. % This can be used to 'fill out' a given virtual canvas. % % MosaicLayer: Start with the virtual canvas of the first image, % enlarging left and right edges to contain all images. % Images with negative offsets will be clipped. % % TrimBoundsLayer: Determine the overall bounds of all the image % layers just as in "MergeLayer", then adjust the canvas % and offsets to be relative to those bounds, without overlaying % the images. % % WARNING: a new image is not returned, the original image % sequence page data is modified instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MergeImageLayers(Image *image,const LayerMethod method, ExceptionInfo *exception) { #define MergeLayersTag "Merge/Layers" Image *canvas; MagickBooleanType proceed; RectangleInfo page; register const Image *next; size_t number_images, height, width; ssize_t scene; 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); /* Determine canvas image size, and its virtual canvas size and offset */ page=image->page; width=image->columns; height=image->rows; switch (method) { case TrimBoundsLayer: case MergeLayer: default: { next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (page.x > next->page.x) { width+=page.x-next->page.x; page.x=next->page.x; } if (page.y > next->page.y) { height+=page.y-next->page.y; page.y=next->page.y; } if ((ssize_t) width < (next->page.x+(ssize_t) next->columns-page.x)) width=(size_t) next->page.x+(ssize_t) next->columns-page.x; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows-page.y)) height=(size_t) next->page.y+(ssize_t) next->rows-page.y; } break; } case FlattenLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; page.x=0; page.y=0; break; } case MosaicLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { if (method == MosaicLayer) { page.x=next->page.x; page.y=next->page.y; if ((ssize_t) width < (next->page.x+(ssize_t) next->columns)) width=(size_t) next->page.x+next->columns; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows)) height=(size_t) next->page.y+next->rows; } } page.width=width; page.height=height; page.x=0; page.y=0; } break; } /* Set virtual canvas size if not defined. */ if (page.width == 0) page.width=page.x < 0 ? width : width+page.x; if (page.height == 0) page.height=page.y < 0 ? height : height+page.y; /* Handle "TrimBoundsLayer" method separately to normal 'layer merge'. */ if (method == TrimBoundsLayer) { number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { image->page.x-=page.x; image->page.y-=page.y; image->page.width=width; image->page.height=height; proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return((Image *) NULL); } /* Create canvas size of width and height, and background color. */ canvas=CloneImage(image,width,height,MagickTrue,exception); if (canvas == (Image *) NULL) return((Image *) NULL); canvas->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(canvas,exception); canvas->page=page; canvas->dispose=UndefinedDispose; /* Compose images onto canvas, with progress monitor */ number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { (void) CompositeImage(canvas,image,image->compose,MagickTrue,image->page.x- canvas->page.x,image->page.y-canvas->page.y,exception); proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return(canvas); }
./CrossVul/dataset_final_sorted/CWE-369/c/good_4413_0
crossvul-cpp_data_bad_5364_0
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2002 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") 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, 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: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * 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. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * JPEG-2000 Code Stream Library * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdlib.h> #include <assert.h> #include <ctype.h> #include "jasper/jas_malloc.h" #include "jasper/jas_debug.h" #include "jpc_cs.h" /******************************************************************************\ * Types. \******************************************************************************/ /* Marker segment table entry. */ typedef struct { int id; char *name; jpc_msops_t ops; } jpc_mstabent_t; /******************************************************************************\ * Local prototypes. \******************************************************************************/ static jpc_mstabent_t *jpc_mstab_lookup(int id); static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static void jpc_poc_destroyparms(jpc_ms_t *ms); static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in); static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out); static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out); static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out); static void jpc_siz_destroyparms(jpc_ms_t *ms); static void jpc_qcd_destroyparms(jpc_ms_t *ms); static void jpc_qcc_destroyparms(jpc_ms_t *ms); static void jpc_cod_destroyparms(jpc_ms_t *ms); static void jpc_coc_destroyparms(jpc_ms_t *ms); static void jpc_unk_destroyparms(jpc_ms_t *ms); static void jpc_ppm_destroyparms(jpc_ms_t *ms); static void jpc_ppt_destroyparms(jpc_ms_t *ms); static void jpc_crg_destroyparms(jpc_ms_t *ms); static void jpc_com_destroyparms(jpc_ms_t *ms); static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms); static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate, jas_stream_t *in, uint_fast16_t len); static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate, jas_stream_t *out); static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms); static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms); static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms); /******************************************************************************\ * Global data. \******************************************************************************/ static jpc_mstabent_t jpc_mstab[] = { {JPC_MS_SOC, "SOC", {0, 0, 0, 0}}, {JPC_MS_SOT, "SOT", {0, jpc_sot_getparms, jpc_sot_putparms, jpc_sot_dumpparms}}, {JPC_MS_SOD, "SOD", {0, 0, 0, 0}}, {JPC_MS_EOC, "EOC", {0, 0, 0, 0}}, {JPC_MS_SIZ, "SIZ", {jpc_siz_destroyparms, jpc_siz_getparms, jpc_siz_putparms, jpc_siz_dumpparms}}, {JPC_MS_COD, "COD", {jpc_cod_destroyparms, jpc_cod_getparms, jpc_cod_putparms, jpc_cod_dumpparms}}, {JPC_MS_COC, "COC", {jpc_coc_destroyparms, jpc_coc_getparms, jpc_coc_putparms, jpc_coc_dumpparms}}, {JPC_MS_RGN, "RGN", {0, jpc_rgn_getparms, jpc_rgn_putparms, jpc_rgn_dumpparms}}, {JPC_MS_QCD, "QCD", {jpc_qcd_destroyparms, jpc_qcd_getparms, jpc_qcd_putparms, jpc_qcd_dumpparms}}, {JPC_MS_QCC, "QCC", {jpc_qcc_destroyparms, jpc_qcc_getparms, jpc_qcc_putparms, jpc_qcc_dumpparms}}, {JPC_MS_POC, "POC", {jpc_poc_destroyparms, jpc_poc_getparms, jpc_poc_putparms, jpc_poc_dumpparms}}, {JPC_MS_TLM, "TLM", {0, jpc_unk_getparms, jpc_unk_putparms, 0}}, {JPC_MS_PLM, "PLM", {0, jpc_unk_getparms, jpc_unk_putparms, 0}}, {JPC_MS_PPM, "PPM", {jpc_ppm_destroyparms, jpc_ppm_getparms, jpc_ppm_putparms, jpc_ppm_dumpparms}}, {JPC_MS_PPT, "PPT", {jpc_ppt_destroyparms, jpc_ppt_getparms, jpc_ppt_putparms, jpc_ppt_dumpparms}}, {JPC_MS_SOP, "SOP", {0, jpc_sop_getparms, jpc_sop_putparms, jpc_sop_dumpparms}}, {JPC_MS_EPH, "EPH", {0, 0, 0, 0}}, {JPC_MS_CRG, "CRG", {0, jpc_crg_getparms, jpc_crg_putparms, jpc_crg_dumpparms}}, {JPC_MS_COM, "COM", {jpc_com_destroyparms, jpc_com_getparms, jpc_com_putparms, jpc_com_dumpparms}}, {-1, "UNKNOWN", {jpc_unk_destroyparms, jpc_unk_getparms, jpc_unk_putparms, jpc_unk_dumpparms}} }; /******************************************************************************\ * Code stream manipulation functions. \******************************************************************************/ /* Create a code stream state object. */ jpc_cstate_t *jpc_cstate_create() { jpc_cstate_t *cstate; if (!(cstate = jas_malloc(sizeof(jpc_cstate_t)))) { return 0; } cstate->numcomps = 0; return cstate; } /* Destroy a code stream state object. */ void jpc_cstate_destroy(jpc_cstate_t *cstate) { jas_free(cstate); } /* Read a marker segment from a stream. */ jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate) { jpc_ms_t *ms; jpc_mstabent_t *mstabent; jas_stream_t *tmpstream; if (!(ms = jpc_ms_create(0))) { return 0; } /* Get the marker type. */ if (jpc_getuint16(in, &ms->id) || ms->id < JPC_MS_MIN || ms->id > JPC_MS_MAX) { jpc_ms_destroy(ms); return 0; } mstabent = jpc_mstab_lookup(ms->id); ms->ops = &mstabent->ops; /* Get the marker segment length and parameters if present. */ /* Note: It is tacitly assumed that a marker segment cannot have parameters unless it has a length field. That is, there cannot be a parameters field without a length field and vice versa. */ if (JPC_MS_HASPARMS(ms->id)) { /* Get the length of the marker segment. */ if (jpc_getuint16(in, &ms->len) || ms->len < 3) { jpc_ms_destroy(ms); return 0; } /* Calculate the length of the marker segment parameters. */ ms->len -= 2; /* Create and prepare a temporary memory stream from which to read the marker segment parameters. */ /* Note: This approach provides a simple way of ensuring that we never read beyond the end of the marker segment (even if the marker segment length is errantly set too small). */ if (!(tmpstream = jas_stream_memopen(0, 0))) { jpc_ms_destroy(ms); return 0; } if (jas_stream_copy(tmpstream, in, ms->len) || jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) { jas_stream_close(tmpstream); jpc_ms_destroy(ms); return 0; } /* Get the marker segment parameters. */ if ((*ms->ops->getparms)(ms, cstate, tmpstream)) { ms->ops = 0; jpc_ms_destroy(ms); jas_stream_close(tmpstream); return 0; } if (jas_getdbglevel() > 0) { jpc_ms_dump(ms, stderr); } if (JAS_CAST(ulong, jas_stream_tell(tmpstream)) != ms->len) { jas_eprintf("warning: trailing garbage in marker segment (%ld bytes)\n", ms->len - jas_stream_tell(tmpstream)); } /* Close the temporary stream. */ jas_stream_close(tmpstream); } else { /* There are no marker segment parameters. */ ms->len = 0; if (jas_getdbglevel() > 0) { jpc_ms_dump(ms, stderr); } } /* Update the code stream state information based on the type of marker segment read. */ /* Note: This is a bit of a hack, but I'm not going to define another type of virtual function for this one special case. */ if (ms->id == JPC_MS_SIZ) { cstate->numcomps = ms->parms.siz.numcomps; } return ms; } /* Write a marker segment to a stream. */ int jpc_putms(jas_stream_t *out, jpc_cstate_t *cstate, jpc_ms_t *ms) { jas_stream_t *tmpstream; int len; /* Output the marker segment type. */ if (jpc_putuint16(out, ms->id)) { return -1; } /* Output the marker segment length and parameters if necessary. */ if (ms->ops->putparms) { /* Create a temporary stream in which to buffer the parameter data. */ if (!(tmpstream = jas_stream_memopen(0, 0))) { return -1; } if ((*ms->ops->putparms)(ms, cstate, tmpstream)) { jas_stream_close(tmpstream); return -1; } /* Get the number of bytes of parameter data written. */ if ((len = jas_stream_tell(tmpstream)) < 0) { jas_stream_close(tmpstream); return -1; } ms->len = len; /* Write the marker segment length and parameter data to the output stream. */ if (jas_stream_seek(tmpstream, 0, SEEK_SET) < 0 || jpc_putuint16(out, ms->len + 2) || jas_stream_copy(out, tmpstream, ms->len) < 0) { jas_stream_close(tmpstream); return -1; } /* Close the temporary stream. */ jas_stream_close(tmpstream); } /* This is a bit of a hack, but I'm not going to define another type of virtual function for this one special case. */ if (ms->id == JPC_MS_SIZ) { cstate->numcomps = ms->parms.siz.numcomps; } if (jas_getdbglevel() > 0) { jpc_ms_dump(ms, stderr); } return 0; } /******************************************************************************\ * Marker segment operations. \******************************************************************************/ /* Create a marker segment of the specified type. */ jpc_ms_t *jpc_ms_create(int type) { jpc_ms_t *ms; jpc_mstabent_t *mstabent; if (!(ms = jas_malloc(sizeof(jpc_ms_t)))) { return 0; } ms->id = type; ms->len = 0; mstabent = jpc_mstab_lookup(ms->id); ms->ops = &mstabent->ops; memset(&ms->parms, 0, sizeof(jpc_msparms_t)); return ms; } /* Destroy a marker segment. */ void jpc_ms_destroy(jpc_ms_t *ms) { if (ms->ops && ms->ops->destroyparms) { (*ms->ops->destroyparms)(ms); } jas_free(ms); } /* Dump a marker segment to a stream for debugging. */ void jpc_ms_dump(jpc_ms_t *ms, FILE *out) { jpc_mstabent_t *mstabent; mstabent = jpc_mstab_lookup(ms->id); fprintf(out, "type = 0x%04x (%s);", ms->id, mstabent->name); if (JPC_MS_HASPARMS(ms->id)) { fprintf(out, " len = %d;", ms->len + 2); if (ms->ops->dumpparms) { (*ms->ops->dumpparms)(ms, out); } else { fprintf(out, "\n"); } } else { fprintf(out, "\n"); } } /******************************************************************************\ * SOT marker segment operations. \******************************************************************************/ static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_sot_t *sot = &ms->parms.sot; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_getuint16(in, &sot->tileno) || jpc_getuint32(in, &sot->len) || jpc_getuint8(in, &sot->partno) || jpc_getuint8(in, &sot->numparts)) { return -1; } if (jas_stream_eof(in)) { return -1; } return 0; } static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_sot_t *sot = &ms->parms.sot; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_putuint16(out, sot->tileno) || jpc_putuint32(out, sot->len) || jpc_putuint8(out, sot->partno) || jpc_putuint8(out, sot->numparts)) { return -1; } return 0; } static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_sot_t *sot = &ms->parms.sot; fprintf(out, "tileno = %d; len = %d; partno = %d; numparts = %d\n", sot->tileno, sot->len, sot->partno, sot->numparts); return 0; } /******************************************************************************\ * SIZ marker segment operations. \******************************************************************************/ static void jpc_siz_destroyparms(jpc_ms_t *ms) { jpc_siz_t *siz = &ms->parms.siz; if (siz->comps) { jas_free(siz->comps); } } static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_siz_t *siz = &ms->parms.siz; unsigned int i; uint_fast8_t tmp; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_getuint16(in, &siz->caps) || jpc_getuint32(in, &siz->width) || jpc_getuint32(in, &siz->height) || jpc_getuint32(in, &siz->xoff) || jpc_getuint32(in, &siz->yoff) || jpc_getuint32(in, &siz->tilewidth) || jpc_getuint32(in, &siz->tileheight) || jpc_getuint32(in, &siz->tilexoff) || jpc_getuint32(in, &siz->tileyoff) || jpc_getuint16(in, &siz->numcomps)) { return -1; } if (!siz->width || !siz->height || !siz->tilewidth || !siz->tileheight || !siz->numcomps) { return -1; } if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) { return -1; } for (i = 0; i < siz->numcomps; ++i) { if (jpc_getuint8(in, &tmp) || jpc_getuint8(in, &siz->comps[i].hsamp) || jpc_getuint8(in, &siz->comps[i].vsamp)) { jas_free(siz->comps); return -1; } siz->comps[i].sgnd = (tmp >> 7) & 1; siz->comps[i].prec = (tmp & 0x7f) + 1; } if (jas_stream_eof(in)) { jas_free(siz->comps); return -1; } return 0; } static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_siz_t *siz = &ms->parms.siz; unsigned int i; /* Eliminate compiler warning about unused variables. */ cstate = 0; assert(siz->width && siz->height && siz->tilewidth && siz->tileheight && siz->numcomps); if (jpc_putuint16(out, siz->caps) || jpc_putuint32(out, siz->width) || jpc_putuint32(out, siz->height) || jpc_putuint32(out, siz->xoff) || jpc_putuint32(out, siz->yoff) || jpc_putuint32(out, siz->tilewidth) || jpc_putuint32(out, siz->tileheight) || jpc_putuint32(out, siz->tilexoff) || jpc_putuint32(out, siz->tileyoff) || jpc_putuint16(out, siz->numcomps)) { return -1; } for (i = 0; i < siz->numcomps; ++i) { if (jpc_putuint8(out, ((siz->comps[i].sgnd & 1) << 7) | ((siz->comps[i].prec - 1) & 0x7f)) || jpc_putuint8(out, siz->comps[i].hsamp) || jpc_putuint8(out, siz->comps[i].vsamp)) { return -1; } } return 0; } static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_siz_t *siz = &ms->parms.siz; unsigned int i; fprintf(out, "caps = 0x%02x;\n", siz->caps); fprintf(out, "width = %d; height = %d; xoff = %d; yoff = %d;\n", siz->width, siz->height, siz->xoff, siz->yoff); fprintf(out, "tilewidth = %d; tileheight = %d; tilexoff = %d; " "tileyoff = %d;\n", siz->tilewidth, siz->tileheight, siz->tilexoff, siz->tileyoff); for (i = 0; i < siz->numcomps; ++i) { fprintf(out, "prec[%d] = %d; sgnd[%d] = %d; hsamp[%d] = %d; " "vsamp[%d] = %d\n", i, siz->comps[i].prec, i, siz->comps[i].sgnd, i, siz->comps[i].hsamp, i, siz->comps[i].vsamp); } return 0; } /******************************************************************************\ * COD marker segment operations. \******************************************************************************/ static void jpc_cod_destroyparms(jpc_ms_t *ms) { jpc_cod_t *cod = &ms->parms.cod; jpc_cox_destroycompparms(&cod->compparms); } static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_cod_t *cod = &ms->parms.cod; if (jpc_getuint8(in, &cod->csty)) { return -1; } if (jpc_getuint8(in, &cod->prg) || jpc_getuint16(in, &cod->numlyrs) || jpc_getuint8(in, &cod->mctrans)) { return -1; } if (jpc_cox_getcompparms(ms, cstate, in, (cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) { return -1; } if (jas_stream_eof(in)) { jpc_cod_destroyparms(ms); return -1; } return 0; } static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_cod_t *cod = &ms->parms.cod; assert(cod->numlyrs > 0 && cod->compparms.numdlvls <= 32); assert(cod->compparms.numdlvls == cod->compparms.numrlvls - 1); if (jpc_putuint8(out, cod->compparms.csty) || jpc_putuint8(out, cod->prg) || jpc_putuint16(out, cod->numlyrs) || jpc_putuint8(out, cod->mctrans)) { return -1; } if (jpc_cox_putcompparms(ms, cstate, out, (cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) { return -1; } return 0; } static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_cod_t *cod = &ms->parms.cod; int i; fprintf(out, "csty = 0x%02x;\n", cod->compparms.csty); fprintf(out, "numdlvls = %d; qmfbid = %d; mctrans = %d\n", cod->compparms.numdlvls, cod->compparms.qmfbid, cod->mctrans); fprintf(out, "prg = %d; numlyrs = %d;\n", cod->prg, cod->numlyrs); fprintf(out, "cblkwidthval = %d; cblkheightval = %d; " "cblksty = 0x%02x;\n", cod->compparms.cblkwidthval, cod->compparms.cblkheightval, cod->compparms.cblksty); if (cod->csty & JPC_COX_PRT) { for (i = 0; i < cod->compparms.numrlvls; ++i) { jas_eprintf("prcwidth[%d] = %d, prcheight[%d] = %d\n", i, cod->compparms.rlvls[i].parwidthval, i, cod->compparms.rlvls[i].parheightval); } } return 0; } /******************************************************************************\ * COC marker segment operations. \******************************************************************************/ static void jpc_coc_destroyparms(jpc_ms_t *ms) { jpc_coc_t *coc = &ms->parms.coc; jpc_cox_destroycompparms(&coc->compparms); } static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_coc_t *coc = &ms->parms.coc; uint_fast8_t tmp; if (cstate->numcomps <= 256) { if (jpc_getuint8(in, &tmp)) { return -1; } coc->compno = tmp; } else { if (jpc_getuint16(in, &coc->compno)) { return -1; } } if (jpc_getuint8(in, &coc->compparms.csty)) { return -1; } if (jpc_cox_getcompparms(ms, cstate, in, (coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) { return -1; } if (jas_stream_eof(in)) { return -1; } return 0; } static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_coc_t *coc = &ms->parms.coc; assert(coc->compparms.numdlvls <= 32); if (cstate->numcomps <= 256) { if (jpc_putuint8(out, coc->compno)) { return -1; } } else { if (jpc_putuint16(out, coc->compno)) { return -1; } } if (jpc_putuint8(out, coc->compparms.csty)) { return -1; } if (jpc_cox_putcompparms(ms, cstate, out, (coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) { return -1; } return 0; } static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_coc_t *coc = &ms->parms.coc; fprintf(out, "compno = %d; csty = 0x%02x; numdlvls = %d;\n", coc->compno, coc->compparms.csty, coc->compparms.numdlvls); fprintf(out, "cblkwidthval = %d; cblkheightval = %d; " "cblksty = 0x%02x; qmfbid = %d;\n", coc->compparms.cblkwidthval, coc->compparms.cblkheightval, coc->compparms.cblksty, coc->compparms.qmfbid); return 0; } /******************************************************************************\ * COD/COC marker segment operation helper functions. \******************************************************************************/ static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms) { /* Eliminate compiler warning about unused variables. */ compparms = 0; } static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms) { uint_fast8_t tmp; int i; /* Eliminate compiler warning about unused variables. */ ms = 0; cstate = 0; if (jpc_getuint8(in, &compparms->numdlvls) || jpc_getuint8(in, &compparms->cblkwidthval) || jpc_getuint8(in, &compparms->cblkheightval) || jpc_getuint8(in, &compparms->cblksty) || jpc_getuint8(in, &compparms->qmfbid)) { return -1; } compparms->numrlvls = compparms->numdlvls + 1; if (prtflag) { for (i = 0; i < compparms->numrlvls; ++i) { if (jpc_getuint8(in, &tmp)) { jpc_cox_destroycompparms(compparms); return -1; } compparms->rlvls[i].parwidthval = tmp & 0xf; compparms->rlvls[i].parheightval = (tmp >> 4) & 0xf; } /* Sigh. This bit should be in the same field in both COC and COD mrk segs. */ compparms->csty |= JPC_COX_PRT; } else { } if (jas_stream_eof(in)) { jpc_cox_destroycompparms(compparms); return -1; } return 0; } static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms) { int i; assert(compparms->numdlvls <= 32); /* Eliminate compiler warning about unused variables. */ ms = 0; cstate = 0; if (jpc_putuint8(out, compparms->numdlvls) || jpc_putuint8(out, compparms->cblkwidthval) || jpc_putuint8(out, compparms->cblkheightval) || jpc_putuint8(out, compparms->cblksty) || jpc_putuint8(out, compparms->qmfbid)) { return -1; } if (prtflag) { for (i = 0; i < compparms->numrlvls; ++i) { if (jpc_putuint8(out, ((compparms->rlvls[i].parheightval & 0xf) << 4) | (compparms->rlvls[i].parwidthval & 0xf))) { return -1; } } } return 0; } /******************************************************************************\ * RGN marker segment operations. \******************************************************************************/ static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_rgn_t *rgn = &ms->parms.rgn; uint_fast8_t tmp; if (cstate->numcomps <= 256) { if (jpc_getuint8(in, &tmp)) { return -1; } rgn->compno = tmp; } else { if (jpc_getuint16(in, &rgn->compno)) { return -1; } } if (jpc_getuint8(in, &rgn->roisty) || jpc_getuint8(in, &rgn->roishift)) { return -1; } return 0; } static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_rgn_t *rgn = &ms->parms.rgn; if (cstate->numcomps <= 256) { if (jpc_putuint8(out, rgn->compno)) { return -1; } } else { if (jpc_putuint16(out, rgn->compno)) { return -1; } } if (jpc_putuint8(out, rgn->roisty) || jpc_putuint8(out, rgn->roishift)) { return -1; } return 0; } static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_rgn_t *rgn = &ms->parms.rgn; fprintf(out, "compno = %d; roisty = %d; roishift = %d\n", rgn->compno, rgn->roisty, rgn->roishift); return 0; } /******************************************************************************\ * QCD marker segment operations. \******************************************************************************/ static void jpc_qcd_destroyparms(jpc_ms_t *ms) { jpc_qcd_t *qcd = &ms->parms.qcd; jpc_qcx_destroycompparms(&qcd->compparms); } static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms; return jpc_qcx_getcompparms(compparms, cstate, in, ms->len); } static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms; return jpc_qcx_putcompparms(compparms, cstate, out); } static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_qcd_t *qcd = &ms->parms.qcd; int i; fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n", (int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes); for (i = 0; i < qcd->compparms.numstepsizes; ++i) { fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n", i, (unsigned) JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i]), i, (unsigned) JPC_QCX_GETMANT(qcd->compparms.stepsizes[i])); } return 0; } /******************************************************************************\ * QCC marker segment operations. \******************************************************************************/ static void jpc_qcc_destroyparms(jpc_ms_t *ms) { jpc_qcc_t *qcc = &ms->parms.qcc; jpc_qcx_destroycompparms(&qcc->compparms); } static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_qcc_t *qcc = &ms->parms.qcc; uint_fast8_t tmp; int len; len = ms->len; if (cstate->numcomps <= 256) { if (jpc_getuint8(in, &tmp)) { return -1; } qcc->compno = tmp; --len; } else { if (jpc_getuint16(in, &qcc->compno)) { return -1; } len -= 2; } if (jpc_qcx_getcompparms(&qcc->compparms, cstate, in, len)) { return -1; } if (jas_stream_eof(in)) { jpc_qcc_destroyparms(ms); return -1; } return 0; } static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_qcc_t *qcc = &ms->parms.qcc; if (cstate->numcomps <= 256) { if (jpc_putuint8(out, qcc->compno)) { return -1; } } else { if (jpc_putuint16(out, qcc->compno)) { return -1; } } if (jpc_qcx_putcompparms(&qcc->compparms, cstate, out)) { return -1; } return 0; } static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_qcc_t *qcc = &ms->parms.qcc; int i; fprintf(out, "compno = %d; qntsty = %d; numguard = %d; " "numstepsizes = %d\n", qcc->compno, qcc->compparms.qntsty, qcc->compparms.numguard, qcc->compparms.numstepsizes); for (i = 0; i < qcc->compparms.numstepsizes; ++i) { fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n", i, (unsigned) JPC_QCX_GETEXPN(qcc->compparms.stepsizes[i]), i, (unsigned) JPC_QCX_GETMANT(qcc->compparms.stepsizes[i])); } return 0; } /******************************************************************************\ * QCD/QCC marker segment helper functions. \******************************************************************************/ static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms) { if (compparms->stepsizes) { jas_free(compparms->stepsizes); } } static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate, jas_stream_t *in, uint_fast16_t len) { uint_fast8_t tmp; int n; int i; /* Eliminate compiler warning about unused variables. */ cstate = 0; n = 0; if (jpc_getuint8(in, &tmp)) { return -1; } ++n; compparms->qntsty = tmp & 0x1f; compparms->numguard = (tmp >> 5) & 7; switch (compparms->qntsty) { case JPC_QCX_SIQNT: compparms->numstepsizes = 1; break; case JPC_QCX_NOQNT: compparms->numstepsizes = (len - n); break; case JPC_QCX_SEQNT: /* XXX - this is a hack */ compparms->numstepsizes = (len - n) / 2; break; } if (compparms->numstepsizes > 0) { compparms->stepsizes = jas_alloc2(compparms->numstepsizes, sizeof(uint_fast16_t)); assert(compparms->stepsizes); for (i = 0; i < compparms->numstepsizes; ++i) { if (compparms->qntsty == JPC_QCX_NOQNT) { if (jpc_getuint8(in, &tmp)) { return -1; } compparms->stepsizes[i] = JPC_QCX_EXPN(tmp >> 3); } else { if (jpc_getuint16(in, &compparms->stepsizes[i])) { return -1; } } } } else { compparms->stepsizes = 0; } if (jas_stream_error(in) || jas_stream_eof(in)) { jpc_qcx_destroycompparms(compparms); return -1; } return 0; } static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate, jas_stream_t *out) { int i; /* Eliminate compiler warning about unused variables. */ cstate = 0; jpc_putuint8(out, ((compparms->numguard & 7) << 5) | compparms->qntsty); for (i = 0; i < compparms->numstepsizes; ++i) { if (compparms->qntsty == JPC_QCX_NOQNT) { if (jpc_putuint8(out, JPC_QCX_GETEXPN( compparms->stepsizes[i]) << 3)) { return -1; } } else { if (jpc_putuint16(out, compparms->stepsizes[i])) { return -1; } } } return 0; } /******************************************************************************\ * SOP marker segment operations. \******************************************************************************/ static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_sop_t *sop = &ms->parms.sop; /* Eliminate compiler warning about unused variable. */ cstate = 0; if (jpc_getuint16(in, &sop->seqno)) { return -1; } return 0; } static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_sop_t *sop = &ms->parms.sop; /* Eliminate compiler warning about unused variable. */ cstate = 0; if (jpc_putuint16(out, sop->seqno)) { return -1; } return 0; } static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_sop_t *sop = &ms->parms.sop; fprintf(out, "seqno = %d;\n", sop->seqno); return 0; } /******************************************************************************\ * PPM marker segment operations. \******************************************************************************/ static void jpc_ppm_destroyparms(jpc_ms_t *ms) { jpc_ppm_t *ppm = &ms->parms.ppm; if (ppm->data) { jas_free(ppm->data); } } static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_ppm_t *ppm = &ms->parms.ppm; /* Eliminate compiler warning about unused variables. */ cstate = 0; ppm->data = 0; if (ms->len < 1) { goto error; } if (jpc_getuint8(in, &ppm->ind)) { goto error; } ppm->len = ms->len - 1; if (ppm->len > 0) { if (!(ppm->data = jas_malloc(ppm->len))) { goto error; } if (JAS_CAST(uint, jas_stream_read(in, ppm->data, ppm->len)) != ppm->len) { goto error; } } else { ppm->data = 0; } return 0; error: jpc_ppm_destroyparms(ms); return -1; } static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_ppm_t *ppm = &ms->parms.ppm; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (JAS_CAST(uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) { return -1; } return 0; } static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_ppm_t *ppm = &ms->parms.ppm; fprintf(out, "ind=%d; len = %d;\n", ppm->ind, ppm->len); if (ppm->len > 0) { fprintf(out, "data =\n"); jas_memdump(out, ppm->data, ppm->len); } return 0; } /******************************************************************************\ * PPT marker segment operations. \******************************************************************************/ static void jpc_ppt_destroyparms(jpc_ms_t *ms) { jpc_ppt_t *ppt = &ms->parms.ppt; if (ppt->data) { jas_free(ppt->data); } } static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_ppt_t *ppt = &ms->parms.ppt; /* Eliminate compiler warning about unused variables. */ cstate = 0; ppt->data = 0; if (ms->len < 1) { goto error; } if (jpc_getuint8(in, &ppt->ind)) { goto error; } ppt->len = ms->len - 1; if (ppt->len > 0) { if (!(ppt->data = jas_malloc(ppt->len))) { goto error; } if (jas_stream_read(in, (char *) ppt->data, ppt->len) != JAS_CAST(int, ppt->len)) { goto error; } } else { ppt->data = 0; } return 0; error: jpc_ppt_destroyparms(ms); return -1; } static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_ppt_t *ppt = &ms->parms.ppt; /* Eliminate compiler warning about unused variable. */ cstate = 0; if (jpc_putuint8(out, ppt->ind)) { return -1; } if (jas_stream_write(out, (char *) ppt->data, ppt->len) != JAS_CAST(int, ppt->len)) { return -1; } return 0; } static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_ppt_t *ppt = &ms->parms.ppt; fprintf(out, "ind=%d; len = %d;\n", ppt->ind, ppt->len); if (ppt->len > 0) { fprintf(out, "data =\n"); jas_memdump(out, ppt->data, ppt->len); } return 0; } /******************************************************************************\ * POC marker segment operations. \******************************************************************************/ static void jpc_poc_destroyparms(jpc_ms_t *ms) { jpc_poc_t *poc = &ms->parms.poc; if (poc->pchgs) { jas_free(poc->pchgs); } } static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_poc_t *poc = &ms->parms.poc; jpc_pocpchg_t *pchg; int pchgno; uint_fast8_t tmp; poc->numpchgs = (cstate->numcomps > 256) ? (ms->len / 9) : (ms->len / 7); if (!(poc->pchgs = jas_alloc2(poc->numpchgs, sizeof(jpc_pocpchg_t)))) { goto error; } for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno, ++pchg) { if (jpc_getuint8(in, &pchg->rlvlnostart)) { goto error; } if (cstate->numcomps > 256) { if (jpc_getuint16(in, &pchg->compnostart)) { goto error; } } else { if (jpc_getuint8(in, &tmp)) { goto error; }; pchg->compnostart = tmp; } if (jpc_getuint16(in, &pchg->lyrnoend) || jpc_getuint8(in, &pchg->rlvlnoend)) { goto error; } if (cstate->numcomps > 256) { if (jpc_getuint16(in, &pchg->compnoend)) { goto error; } } else { if (jpc_getuint8(in, &tmp)) { goto error; } pchg->compnoend = tmp; } if (jpc_getuint8(in, &pchg->prgord)) { goto error; } if (pchg->rlvlnostart > pchg->rlvlnoend || pchg->compnostart > pchg->compnoend) { goto error; } } return 0; error: jpc_poc_destroyparms(ms); return -1; } static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_poc_t *poc = &ms->parms.poc; jpc_pocpchg_t *pchg; int pchgno; for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno, ++pchg) { if (jpc_putuint8(out, pchg->rlvlnostart) || ((cstate->numcomps > 256) ? jpc_putuint16(out, pchg->compnostart) : jpc_putuint8(out, pchg->compnostart)) || jpc_putuint16(out, pchg->lyrnoend) || jpc_putuint8(out, pchg->rlvlnoend) || ((cstate->numcomps > 256) ? jpc_putuint16(out, pchg->compnoend) : jpc_putuint8(out, pchg->compnoend)) || jpc_putuint8(out, pchg->prgord)) { return -1; } } return 0; } static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_poc_t *poc = &ms->parms.poc; jpc_pocpchg_t *pchg; int pchgno; for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno, ++pchg) { fprintf(out, "po[%d] = %d; ", pchgno, pchg->prgord); fprintf(out, "cs[%d] = %d; ce[%d] = %d; ", pchgno, pchg->compnostart, pchgno, pchg->compnoend); fprintf(out, "rs[%d] = %d; re[%d] = %d; ", pchgno, pchg->rlvlnostart, pchgno, pchg->rlvlnoend); fprintf(out, "le[%d] = %d\n", pchgno, pchg->lyrnoend); } return 0; } /******************************************************************************\ * CRG marker segment operations. \******************************************************************************/ static void jpc_crg_destroyparms(jpc_ms_t *ms) { jpc_crg_t *crg = &ms->parms.crg; if (crg->comps) { jas_free(crg->comps); } } static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_crg_t *crg = &ms->parms.crg; jpc_crgcomp_t *comp; uint_fast16_t compno; crg->numcomps = cstate->numcomps; if (!(crg->comps = jas_alloc2(cstate->numcomps, sizeof(uint_fast16_t)))) { return -1; } for (compno = 0, comp = crg->comps; compno < cstate->numcomps; ++compno, ++comp) { if (jpc_getuint16(in, &comp->hoff) || jpc_getuint16(in, &comp->voff)) { jpc_crg_destroyparms(ms); return -1; } } return 0; } static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_crg_t *crg = &ms->parms.crg; int compno; jpc_crgcomp_t *comp; /* Eliminate compiler warning about unused variables. */ cstate = 0; for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno, ++comp) { if (jpc_putuint16(out, comp->hoff) || jpc_putuint16(out, comp->voff)) { return -1; } } return 0; } static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_crg_t *crg = &ms->parms.crg; int compno; jpc_crgcomp_t *comp; for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno, ++comp) { fprintf(out, "hoff[%d] = %d; voff[%d] = %d\n", compno, comp->hoff, compno, comp->voff); } return 0; } /******************************************************************************\ * Operations for COM marker segment. \******************************************************************************/ static void jpc_com_destroyparms(jpc_ms_t *ms) { jpc_com_t *com = &ms->parms.com; if (com->data) { jas_free(com->data); } } static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_com_t *com = &ms->parms.com; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_getuint16(in, &com->regid)) { return -1; } com->len = ms->len - 2; if (com->len > 0) { if (!(com->data = jas_malloc(com->len))) { return -1; } if (jas_stream_read(in, com->data, com->len) != JAS_CAST(int, com->len)) { return -1; } } else { com->data = 0; } return 0; } static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { jpc_com_t *com = &ms->parms.com; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (jpc_putuint16(out, com->regid)) { return -1; } if (jas_stream_write(out, com->data, com->len) != JAS_CAST(int, com->len)) { return -1; } return 0; } static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_com_t *com = &ms->parms.com; unsigned int i; int printable; fprintf(out, "regid = %d;\n", com->regid); printable = 1; for (i = 0; i < com->len; ++i) { if (!isprint(com->data[i])) { printable = 0; break; } } if (printable) { fprintf(out, "data = "); fwrite(com->data, sizeof(char), com->len, out); fprintf(out, "\n"); } return 0; } /******************************************************************************\ * Operations for unknown types of marker segments. \******************************************************************************/ static void jpc_unk_destroyparms(jpc_ms_t *ms) { jpc_unk_t *unk = &ms->parms.unk; if (unk->data) { jas_free(unk->data); } } static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in) { jpc_unk_t *unk = &ms->parms.unk; /* Eliminate compiler warning about unused variables. */ cstate = 0; if (ms->len > 0) { if (!(unk->data = jas_alloc2(ms->len, sizeof(unsigned char)))) { return -1; } if (jas_stream_read(in, (char *) unk->data, ms->len) != JAS_CAST(int, ms->len)) { jas_free(unk->data); return -1; } unk->len = ms->len; } else { unk->data = 0; unk->len = 0; } return 0; } static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out) { /* Eliminate compiler warning about unused variables. */ cstate = 0; ms = 0; out = 0; /* If this function is called, we are trying to write an unsupported type of marker segment. Return with an error indication. */ return -1; } static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out) { unsigned int i; jpc_unk_t *unk = &ms->parms.unk; for (i = 0; i < unk->len; ++i) { fprintf(out, "%02x ", unk->data[i]); } return 0; } /******************************************************************************\ * Primitive I/O operations. \******************************************************************************/ int jpc_getuint8(jas_stream_t *in, uint_fast8_t *val) { int c; if ((c = jas_stream_getc(in)) == EOF) { return -1; } if (val) { *val = c; } return 0; } int jpc_putuint8(jas_stream_t *out, uint_fast8_t val) { if (jas_stream_putc(out, val & 0xff) == EOF) { return -1; } return 0; } int jpc_getuint16(jas_stream_t *in, uint_fast16_t *val) { uint_fast16_t v; int c; if ((c = jas_stream_getc(in)) == EOF) { return -1; } v = c; if ((c = jas_stream_getc(in)) == EOF) { return -1; } v = (v << 8) | c; if (val) { *val = v; } return 0; } int jpc_putuint16(jas_stream_t *out, uint_fast16_t val) { if (jas_stream_putc(out, (val >> 8) & 0xff) == EOF || jas_stream_putc(out, val & 0xff) == EOF) { return -1; } return 0; } int jpc_getuint32(jas_stream_t *in, uint_fast32_t *val) { uint_fast32_t v; int c; if ((c = jas_stream_getc(in)) == EOF) { return -1; } v = c; if ((c = jas_stream_getc(in)) == EOF) { return -1; } v = (v << 8) | c; if ((c = jas_stream_getc(in)) == EOF) { return -1; } v = (v << 8) | c; if ((c = jas_stream_getc(in)) == EOF) { return -1; } v = (v << 8) | c; if (val) { *val = v; } return 0; } int jpc_putuint32(jas_stream_t *out, uint_fast32_t val) { if (jas_stream_putc(out, (val >> 24) & 0xff) == EOF || jas_stream_putc(out, (val >> 16) & 0xff) == EOF || jas_stream_putc(out, (val >> 8) & 0xff) == EOF || jas_stream_putc(out, val & 0xff) == EOF) { return -1; } return 0; } /******************************************************************************\ * Miscellany \******************************************************************************/ static jpc_mstabent_t *jpc_mstab_lookup(int id) { jpc_mstabent_t *mstabent; for (mstabent = jpc_mstab;; ++mstabent) { if (mstabent->id == id || mstabent->id < 0) { return mstabent; } } assert(0); return 0; } int jpc_validate(jas_stream_t *in) { int n; int i; unsigned char buf[2]; assert(JAS_STREAM_MAXPUTBACK >= 2); if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) { return -1; } for (i = n - 1; i >= 0; --i) { if (jas_stream_ungetc(in, buf[i]) == EOF) { return -1; } } if (n < 2) { return -1; } if (buf[0] == (JPC_MS_SOC >> 8) && buf[1] == (JPC_MS_SOC & 0xff)) { return 0; } return -1; } int jpc_getdata(jas_stream_t *in, jas_stream_t *out, long len) { return jas_stream_copy(out, in, len); } int jpc_putdata(jas_stream_t *out, jas_stream_t *in, long len) { return jas_stream_copy(out, in, len); }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_5364_0
crossvul-cpp_data_bad_3308_0
// imagew-gif.c // Part of ImageWorsener, Copyright (c) 2011 by Jason Summers. // For more information, see the readme.txt file. // This is a self-contained GIF image decoder. // It supports a single image only, so it does not support animated GIFs, // or any GIF where the main image is constructed from multiple sub-images. #include "imagew-config.h" #include <stdlib.h> #include <string.h> #define IW_INCLUDE_UTIL_FUNCTIONS #include "imagew.h" struct iwgifrcontext { struct iw_iodescr *iodescr; struct iw_context *ctx; struct iw_image *img; struct iw_csdescr csdescr; int page; // Page to read. 1=first int screen_width, screen_height; // Same as .img->width, .img->height int image_width, image_height; int image_left, image_top; int include_screen; // Do we paint the image onto the "screen", or just extract it? int screen_initialized; int pages_seen; int interlaced; int bytes_per_pixel; int has_transparency; int has_bg_color; int bg_color_index; int trans_color_index; size_t pixels_set; // Number of pixels decoded so far size_t total_npixels; // Total number of pixels in the "image" (not the "screen") iw_byte **row_pointers; struct iw_palette colortable; // A buffer used when reading the GIF file. // The largest block we need to read is a 256-color palette. iw_byte rbuf[768]; }; static int iwgif_read(struct iwgifrcontext *rctx, iw_byte *buf, size_t buflen) { int ret; size_t bytesread = 0; ret = (*rctx->iodescr->read_fn)(rctx->ctx,rctx->iodescr, buf,buflen,&bytesread); if(!ret || bytesread!=buflen) { return 0; } return 1; } static int iwgif_read_file_header(struct iwgifrcontext *rctx) { if(!iwgif_read(rctx,rctx->rbuf,6)) return 0; if(rctx->rbuf[0]!='G' || rctx->rbuf[1]!='I' || rctx->rbuf[2]!='F') { iw_set_error(rctx->ctx,"Not a GIF file"); return 0; } return 1; } static int iwgif_read_screen_descriptor(struct iwgifrcontext *rctx) { int has_global_ct; int global_ct_size; int aspect_ratio_code; // The screen descriptor is always 7 bytes in size. if(!iwgif_read(rctx,rctx->rbuf,7)) return 0; rctx->screen_width = (int)iw_get_ui16le(&rctx->rbuf[0]); rctx->screen_height = (int)iw_get_ui16le(&rctx->rbuf[2]); // screen_width and _height may be updated in iwgif_init_screen(). has_global_ct = (int)((rctx->rbuf[4]>>7)&0x01); if(has_global_ct) { // Size of global color table global_ct_size = (int)(rctx->rbuf[4]&0x07); rctx->colortable.num_entries = 1<<(1+global_ct_size); // Background color rctx->bg_color_index = (int)rctx->rbuf[5]; if(rctx->bg_color_index < rctx->colortable.num_entries) rctx->has_bg_color = 1; } aspect_ratio_code = (int)rctx->rbuf[6]; if(aspect_ratio_code!=0) { // [aspect ratio = (pixel width)/(pixel height)] rctx->img->density_code = IW_DENSITY_UNITS_UNKNOWN; rctx->img->density_x = 64000.0/(double)(aspect_ratio_code + 15); rctx->img->density_y = 1000.0; } return 1; } // Read a global or local palette into memory. // ct->num_entries must be set by caller static int iwgif_read_color_table(struct iwgifrcontext *rctx, struct iw_palette *ct) { int i; if(ct->num_entries<1) return 1; if(!iwgif_read(rctx,rctx->rbuf,3*ct->num_entries)) return 0; for(i=0;i<ct->num_entries;i++) { ct->entry[i].r = rctx->rbuf[3*i+0]; ct->entry[i].g = rctx->rbuf[3*i+1]; ct->entry[i].b = rctx->rbuf[3*i+2]; } return 1; } static int iwgif_skip_subblocks(struct iwgifrcontext *rctx) { iw_byte subblock_size; while(1) { // Read the subblock size if(!iwgif_read(rctx,rctx->rbuf,1)) return 0; subblock_size = rctx->rbuf[0]; // A size of 0 marks the end of the subblocks. if(subblock_size==0) return 1; // Read the subblock's data if(!iwgif_read(rctx,rctx->rbuf,(size_t)subblock_size)) return 0; } } // We need transparency information, so we have to process graphic control // extensions. static int iwgif_read_graphic_control_ext(struct iwgifrcontext *rctx) { int retval; // Read 6 bytes: // The first is the subblock size, which must be 4. // The last is the block terminator. // The middle 4 contain the actual data. if(!iwgif_read(rctx,rctx->rbuf,6)) goto done; if(rctx->rbuf[0]!=4) goto done; if(rctx->rbuf[5]!=0) goto done; rctx->has_transparency = (int)((rctx->rbuf[1])&0x01); if(rctx->has_transparency) { rctx->trans_color_index = (int)rctx->rbuf[4]; } retval=1; done: return retval; } static int iwgif_read_extension(struct iwgifrcontext *rctx) { int retval=0; iw_byte ext_type; if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; ext_type=rctx->rbuf[0]; switch(ext_type) { case 0xf9: if(rctx->page == rctx->pages_seen+1) { if(!iwgif_read_graphic_control_ext(rctx)) goto done; } else { // This extension's scope does not include the image we're // processing, so ignore it. if(!iwgif_skip_subblocks(rctx)) goto done; } break; default: if(!iwgif_skip_subblocks(rctx)) goto done; } retval=1; done: return retval; } // Set the (rctx->pixels_set + offset)th pixel in the logical image to the // color represented by palette entry #coloridx. static void iwgif_record_pixel(struct iwgifrcontext *rctx, unsigned int coloridx, int offset) { struct iw_image *img; unsigned int r,g,b,a; size_t pixnum; size_t xi,yi; // position in image coordinates size_t xs,ys; // position in screen coordinates iw_byte *ptr; img = rctx->img; // Figure out which pixel to set. pixnum = rctx->pixels_set + offset; xi = pixnum%rctx->image_width; yi = pixnum/rctx->image_width; xs = rctx->image_left + xi; ys = rctx->image_top + yi; // Make sure the coordinate is within the image, and on the screen. if(yi>=(size_t)rctx->image_height) return; if(xs>=(size_t)rctx->screen_width) return; if(ys>=(size_t)rctx->screen_height) return; // Because of how we de-interlace, it's not obvious whether the Y coordinate // is on the screen. The easiest way is to check if the row pointer is NULL. if(rctx->row_pointers[yi]==NULL) return; // Figure out what color to set the pixel to. if(coloridx<(unsigned int)rctx->colortable.num_entries) { r=rctx->colortable.entry[coloridx].r; g=rctx->colortable.entry[coloridx].g; b=rctx->colortable.entry[coloridx].b; a=rctx->colortable.entry[coloridx].a; } else { return; // Illegal palette index } // Set the pixel. ptr = &rctx->row_pointers[yi][rctx->bytes_per_pixel*xi]; ptr[0]=r; ptr[1]=g; ptr[2]=b; if(img->imgtype==IW_IMGTYPE_RGBA) { ptr[3]=a; } } //////////////////////////////////////////////////////// // LZW decoder //////////////////////////////////////////////////////// struct lzw_tableentry { iw_uint16 parent; // pointer to previous table entry (if not a root code) iw_uint16 length; iw_byte firstchar; iw_byte lastchar; }; struct lzwdeccontext { unsigned int root_codesize; unsigned int current_codesize; int eoi_flag; unsigned int oldcode; unsigned int pending_code; unsigned int bits_in_pending_code; unsigned int num_root_codes; int ncodes_since_clear; unsigned int clear_code; unsigned int eoi_code; unsigned int last_code_added; unsigned int ct_used; // Number of items used in the code table struct lzw_tableentry ct[4096]; // Code table }; static void lzw_init(struct lzwdeccontext *d, unsigned int root_codesize) { unsigned int i; iw_zeromem(d,sizeof(struct lzwdeccontext)); d->root_codesize = root_codesize; d->num_root_codes = 1<<d->root_codesize; d->clear_code = d->num_root_codes; d->eoi_code = d->num_root_codes+1; for(i=0;i<d->num_root_codes;i++) { d->ct[i].parent = 0; d->ct[i].length = 1; d->ct[i].lastchar = (iw_byte)i; d->ct[i].firstchar = (iw_byte)i; } } static void lzw_clear(struct lzwdeccontext *d) { d->ct_used = d->num_root_codes+2; d->current_codesize = d->root_codesize+1; d->ncodes_since_clear=0; d->oldcode=0; } // Decode an LZW code to one or more pixels, and record it in the image. static void lzw_emit_code(struct iwgifrcontext *rctx, struct lzwdeccontext *d, unsigned int first_code) { unsigned int code; code = first_code; // An LZW code may decode to more than one pixel. Note that the pixels for // an LZW code are decoded in reverse order (right to left). while(1) { iwgif_record_pixel(rctx, (unsigned int)d->ct[code].lastchar, (int)(d->ct[code].length-1)); if(d->ct[code].length<=1) break; // The codes are structured as a "forest" (multiple trees). // Go to the parent code, which will have a length 1 less than this one. code = (unsigned int)d->ct[code].parent; } // Track the total number of pixels decoded in this image. rctx->pixels_set += d->ct[first_code].length; } // Add a code to the dictionary. // Sets d->last_code_added to the position where it was added. // Returns 1 if successful, 0 if table is full. static int lzw_add_to_dict(struct lzwdeccontext *d, unsigned int oldcode, iw_byte val) { static const unsigned int last_code_of_size[] = { // The first 3 values are unused. 0,0,0,7,15,31,63,127,255,511,1023,2047,4095 }; unsigned int newpos; if(d->ct_used>=4096) { d->last_code_added = 0; return 0; } newpos = d->ct_used; d->ct_used++; d->ct[newpos].parent = (iw_uint16)oldcode; d->ct[newpos].length = d->ct[oldcode].length + 1; d->ct[newpos].firstchar = d->ct[oldcode].firstchar; d->ct[newpos].lastchar = val; // If we've used the last code of this size, we need to increase the codesize. if(newpos == last_code_of_size[d->current_codesize]) { if(d->current_codesize<12) { d->current_codesize++; } } d->last_code_added = newpos; return 1; } // Process a single LZW code that was read from the input stream. static int lzw_process_code(struct iwgifrcontext *rctx, struct lzwdeccontext *d, unsigned int code) { if(code==d->eoi_code) { d->eoi_flag=1; return 1; } if(code==d->clear_code) { lzw_clear(d); return 1; } d->ncodes_since_clear++; if(d->ncodes_since_clear==1) { // Special case for the first code. lzw_emit_code(rctx,d,code); d->oldcode = code; return 1; } // Is code in code table? if(code < d->ct_used) { // Yes, code is in table. lzw_emit_code(rctx,d,code); // Let k = the first character of the translation of the code. // Add <oldcode>k to the dictionary. lzw_add_to_dict(d,d->oldcode,d->ct[code].firstchar); } else { // No, code is not in table. if(d->oldcode>=d->ct_used) { iw_set_error(rctx->ctx,"GIF decoding error"); return 0; } // Let k = the first char of the translation of oldcode. // Add <oldcode>k to the dictionary. if(lzw_add_to_dict(d,d->oldcode,d->ct[d->oldcode].firstchar)) { // Write <oldcode>k to the output stream. lzw_emit_code(rctx,d,d->last_code_added); } } d->oldcode = code; return 1; } // Decode as much as possible of the provided LZW-encoded data. // Any unfinished business is recorded, to be continued the next time // this function is called. static int lzw_process_bytes(struct iwgifrcontext *rctx, struct lzwdeccontext *d, iw_byte *data, size_t data_size) { size_t i; int b; int retval=0; for(i=0;i<data_size;i++) { // Look at the bits one at a time. for(b=0;b<8;b++) { if(d->eoi_flag) { // Stop if we've seen an EOI (end of image) code. retval=1; goto done; } if(data[i]&(1<<b)) d->pending_code |= 1<<d->bits_in_pending_code; d->bits_in_pending_code++; // When we get enough bits to form a complete LZW code, process it. if(d->bits_in_pending_code >= d->current_codesize) { if(!lzw_process_code(rctx,d,d->pending_code)) goto done; d->pending_code=0; d->bits_in_pending_code=0; } } } retval=1; done: return retval; } //////////////////////////////////////////////////////// // Allocate and set up the global "screen". static int iwgif_init_screen(struct iwgifrcontext *rctx) { struct iw_image *img; int bg_visible=0; int retval=0; if(rctx->screen_initialized) return 1; rctx->screen_initialized = 1; img = rctx->img; if(!rctx->include_screen) { // If ->include_screen is disabled, pretend the screen is the same size as // the GIF image, and pretend the GIF image is positioned at (0,0). rctx->screen_width = rctx->image_width; rctx->screen_height = rctx->image_height; rctx->image_left = 0; rctx->image_top = 0; } img->width = rctx->screen_width; img->height = rctx->screen_height; if(!iw_check_image_dimensions(rctx->ctx,img->width,img->height)) { return 0; } if(rctx->image_left>0 || rctx->image_top>0 || (rctx->image_left+rctx->image_width < rctx->screen_width) || (rctx->image_top+rctx->image_height < rctx->screen_height) ) { // Image does not cover the entire "screen". We'll make the exposed // regions of the screen transparent, so set a flag to let us know we // need an image type that supports transparency. bg_visible = 1; } // Allocate IW image if(rctx->has_transparency || bg_visible) { rctx->bytes_per_pixel=4; img->imgtype = IW_IMGTYPE_RGBA; } else { rctx->bytes_per_pixel=3; img->imgtype = IW_IMGTYPE_RGB; } img->bit_depth = 8; img->bpr = rctx->bytes_per_pixel * img->width; img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx, img->bpr, img->height); if(!img->pixels) goto done; // Start by clearing the screen to black, or transparent black. iw_zeromem(img->pixels,img->bpr*img->height); retval=1; done: return retval; } // Make an array of pointers into the global screen, which point to the // start of each row in the local image. This will be useful for // de-interlacing. static int iwgif_make_row_pointers(struct iwgifrcontext *rctx) { struct iw_image *img; int pass; int startrow, rowskip; int rowcount; int row; if(rctx->row_pointers) iw_free(rctx->ctx,rctx->row_pointers); rctx->row_pointers = (iw_byte**)iw_malloc(rctx->ctx, sizeof(iw_byte*)*rctx->image_height); if(!rctx->row_pointers) return 0; img = rctx->img; if(rctx->interlaced) { // Image is interlaced. Rearrange the row pointers, so that it will be // de-interlaced as it is decoded. rowcount=0; for(pass=1;pass<=4;pass++) { if(pass==1) { startrow=0; rowskip=8; } else if(pass==2) { startrow=4; rowskip=8; } else if(pass==3) { startrow=2; rowskip=4; } else { startrow=1; rowskip=2; } for(row=startrow;row<rctx->image_height;row+=rowskip) { if(rctx->image_top+row < rctx->screen_height) { rctx->row_pointers[rowcount] = &img->pixels[(rctx->image_top+row)*img->bpr + (rctx->image_left)*rctx->bytes_per_pixel]; } else { rctx->row_pointers[rowcount] = NULL; } rowcount++; } } } else { // Image is not interlaced. for(row=0;row<rctx->image_height;row++) { if(rctx->image_top+row < rctx->screen_height) { rctx->row_pointers[row] = &img->pixels[(rctx->image_top+row)*img->bpr + (rctx->image_left)*rctx->bytes_per_pixel]; } else { rctx->row_pointers[row] = NULL; } } } return 1; } static int iwgif_skip_image(struct iwgifrcontext *rctx) { int has_local_ct; int local_ct_size; int ct_num_entries; int retval=0; // Read image header information if(!iwgif_read(rctx,rctx->rbuf,9)) goto done; has_local_ct = (int)((rctx->rbuf[8]>>7)&0x01); if(has_local_ct) { local_ct_size = (int)(rctx->rbuf[8]&0x07); ct_num_entries = 1<<(1+local_ct_size); } // Skip the local color table if(has_local_ct) { if(!iwgif_read(rctx,rctx->rbuf,3*ct_num_entries)) goto done; } // Skip the LZW code size if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; // Skip the image pixels if(!iwgif_skip_subblocks(rctx)) goto done; // Reset anything that might have been set by a graphic control extension. // Their scope is the first image that follows them. rctx->has_transparency = 0; retval=1; done: return retval; } static int iwgif_read_image(struct iwgifrcontext *rctx) { int retval=0; struct lzwdeccontext d; size_t subblocksize; int has_local_ct; int local_ct_size; unsigned int root_codesize; // Read image header information if(!iwgif_read(rctx,rctx->rbuf,9)) goto done; rctx->image_left = (int)iw_get_ui16le(&rctx->rbuf[0]); rctx->image_top = (int)iw_get_ui16le(&rctx->rbuf[2]); // image_left and _top may be updated in iwgif_init_screen(). rctx->image_width = (int)iw_get_ui16le(&rctx->rbuf[4]); rctx->image_height = (int)iw_get_ui16le(&rctx->rbuf[6]); rctx->interlaced = (int)((rctx->rbuf[8]>>6)&0x01); has_local_ct = (int)((rctx->rbuf[8]>>7)&0x01); if(has_local_ct) { local_ct_size = (int)(rctx->rbuf[8]&0x07); rctx->colortable.num_entries = 1<<(1+local_ct_size); } if(has_local_ct) { // We only support one image, so we don't need to keep both a global and a // local color table. If an image has both, the local table will overwrite // the global one. if(!iwgif_read_color_table(rctx,&rctx->colortable)) goto done; } // Make the transparent color transparent. if(rctx->has_transparency) { rctx->colortable.entry[rctx->trans_color_index].a = 0; } // Read LZW code size if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; root_codesize = (unsigned int)rctx->rbuf[0]; // The spec does not allow the "minimum code size" to be less than 2. // Sizes >=12 are impossible to support. // There's no reason for the size to be larger than 8, but the spec // does not seem to forbid it. if(root_codesize<2 || root_codesize>11) { iw_set_error(rctx->ctx,"Invalid LZW minimum code size"); goto done; } // The creation of the global "screen" was deferred until now, to wait until // we know whether the image has transparency. // (And if !rctx->include_screen, to wait until we know the size of the image.) if(!iwgif_init_screen(rctx)) goto done; rctx->total_npixels = (size_t)rctx->image_width * (size_t)rctx->image_height; if(!iwgif_make_row_pointers(rctx)) goto done; lzw_init(&d,root_codesize); lzw_clear(&d); while(1) { // Read size of next subblock if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; subblocksize = (size_t)rctx->rbuf[0]; if(subblocksize==0) break; // Read next subblock if(!iwgif_read(rctx,rctx->rbuf,subblocksize)) goto done; if(!lzw_process_bytes(rctx,&d,rctx->rbuf,subblocksize)) goto done; if(d.eoi_flag) break; // Stop if we reached the end of the image. We don't care if we've read an // EOI code or not. if(rctx->pixels_set >= rctx->total_npixels) break; } retval=1; done: return retval; } static int iwgif_read_main(struct iwgifrcontext *rctx) { int retval=0; int i; int image_found=0; // Make all colors opaque by default. for(i=0;i<256;i++) { rctx->colortable.entry[i].a=255; } if(!iwgif_read_file_header(rctx)) goto done; if(!iwgif_read_screen_descriptor(rctx)) goto done; // Read global color table if(!iwgif_read_color_table(rctx,&rctx->colortable)) goto done; // Tell IW the background color. if(rctx->has_bg_color) { iw_set_input_bkgd_label(rctx->ctx, ((double)rctx->colortable.entry[rctx->bg_color_index].r)/255.0, ((double)rctx->colortable.entry[rctx->bg_color_index].g)/255.0, ((double)rctx->colortable.entry[rctx->bg_color_index].b)/255.0); } // The remainder of the file consists of blocks whose type is indicated by // their initial byte. while(!image_found) { // Read block type if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; switch(rctx->rbuf[0]) { case 0x21: // extension if(!iwgif_read_extension(rctx)) goto done; break; case 0x2c: // image rctx->pages_seen++; if(rctx->page == rctx->pages_seen) { if(!iwgif_read_image(rctx)) goto done; image_found=1; } else { if(!iwgif_skip_image(rctx)) goto done; } break; case 0x3b: // file trailer // We stop after we decode an image, so if we ever see a file // trailer, something's wrong. if(rctx->pages_seen==0) iw_set_error(rctx->ctx,"No image in file"); else iw_set_error(rctx->ctx,"Image not found"); goto done; default: iw_set_error(rctx->ctx,"Invalid or unsupported GIF file"); goto done; } } retval=1; done: return retval; } IW_IMPL(int) iw_read_gif_file(struct iw_context *ctx, struct iw_iodescr *iodescr) { struct iw_image img; struct iwgifrcontext *rctx = NULL; int retval=0; iw_zeromem(&img,sizeof(struct iw_image)); rctx = iw_mallocz(ctx,sizeof(struct iwgifrcontext)); if(!rctx) goto done; rctx->ctx = ctx; rctx->iodescr = iodescr; rctx->img = &img; // Assume GIF images are sRGB. iw_make_srgb_csdescr_2(&rctx->csdescr); rctx->page = iw_get_value(ctx,IW_VAL_PAGE_TO_READ); if(rctx->page<1) rctx->page = 1; rctx->include_screen = iw_get_value(ctx,IW_VAL_INCLUDE_SCREEN); if(!iwgif_read_main(rctx)) goto done; iw_set_input_image(ctx, &img); iw_set_input_colorspace(ctx,&rctx->csdescr); retval = 1; done: if(!retval) { iw_set_error(ctx,"Failed to read GIF file"); } if(rctx) { if(rctx->row_pointers) iw_free(ctx,rctx->row_pointers); iw_free(ctx,rctx); } return retval; }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_3308_0
crossvul-cpp_data_bad_5311_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT U U M M % % Q Q U U A A NN N T U U MM MM % % Q Q U U AAAAA N N N T U U M M M % % Q QQ U U A A N NN T U U M M % % QQQQ UUU A A N N T UUU M M % % % % MagicCore Methods to Acquire / Destroy Quantum Pixels % % % % Software Design % % Cristy % % October 1998 % % % % % % Copyright 1999-2016 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 "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/color-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/delegate.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/statistic.h" #include "MagickCore/stream.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/utility.h" /* Define declarations. */ #define QuantumSignature 0xab /* Forward declarations. */ static void DestroyQuantumPixels(QuantumInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumInfo() allocates the QuantumInfo structure. % % The format of the AcquireQuantumInfo method is: % % QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ MagickExport QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info, Image *image) { MagickBooleanType status; QuantumInfo *quantum_info; quantum_info=(QuantumInfo *) AcquireMagickMemory(sizeof(*quantum_info)); if (quantum_info == (QuantumInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); quantum_info->signature=MagickCoreSignature; GetQuantumInfo(image_info,quantum_info); if (image == (const Image *) NULL) return(quantum_info); status=SetQuantumDepth(image,quantum_info,image->depth); quantum_info->endian=image->endian; if (status == MagickFalse) quantum_info=DestroyQuantumInfo(quantum_info); return(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumPixels() allocates the pixel staging areas. % % The format of the AcquireQuantumPixels method is: % % MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info, % const size_t extent) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o extent: the quantum info. % */ static MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info, const size_t extent) { register ssize_t i; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); quantum_info->pixels=(unsigned char **) AcquireQuantumMemory( quantum_info->number_threads,sizeof(*quantum_info->pixels)); if (quantum_info->pixels == (unsigned char **) NULL) return(MagickFalse); quantum_info->extent=extent; (void) ResetMagickMemory(quantum_info->pixels,0,quantum_info->number_threads* sizeof(*quantum_info->pixels)); for (i=0; i < (ssize_t) quantum_info->number_threads; i++) { quantum_info->pixels[i]=(unsigned char *) AcquireQuantumMemory(extent+1, sizeof(**quantum_info->pixels)); if (quantum_info->pixels[i] == (unsigned char *) NULL) { while (--i >= 0) quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory( quantum_info->pixels[i]); return(MagickFalse); } (void) ResetMagickMemory(quantum_info->pixels[i],0,(extent+1)* sizeof(**quantum_info->pixels)); quantum_info->pixels[i][extent]=QuantumSignature; } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantumInfo() deallocates memory associated with the QuantumInfo % structure. % % The format of the DestroyQuantumInfo method is: % % QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); if (quantum_info->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&quantum_info->semaphore); quantum_info->signature=(~MagickCoreSignature); quantum_info=(QuantumInfo *) RelinquishMagickMemory(quantum_info); return(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantumPixels() destroys the quantum pixels. % % The format of the DestroyQuantumPixels() method is: % % void DestroyQuantumPixels(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ static void DestroyQuantumPixels(QuantumInfo *quantum_info) { register ssize_t i; ssize_t extent; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); assert(quantum_info->pixels != (unsigned char **) NULL); extent=(ssize_t) quantum_info->extent; for (i=0; i < (ssize_t) quantum_info->number_threads; i++) if (quantum_info->pixels[i] != (unsigned char *) NULL) { /* Did we overrun our quantum buffer? */ assert(quantum_info->pixels[i][extent] == QuantumSignature); quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory( quantum_info->pixels[i]); } quantum_info->pixels=(unsigned char **) RelinquishMagickMemory( quantum_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumExtent() returns the quantum pixel buffer extent. % % The format of the GetQuantumExtent method is: % % size_t GetQuantumExtent(Image *image,const QuantumInfo *quantum_info, % const QuantumType quantum_type) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o quantum_type: Declare which pixel components to transfer (red, green, % blue, opacity, RGB, or RGBA). % */ MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t packet_size; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); packet_size=1; switch (quantum_type) { case GrayAlphaQuantum: packet_size=2; break; case IndexAlphaQuantum: packet_size=2; break; case RGBQuantum: packet_size=3; break; case BGRQuantum: packet_size=3; break; case RGBAQuantum: packet_size=4; break; case RGBOQuantum: packet_size=4; break; case BGRAQuantum: packet_size=4; break; case CMYKQuantum: packet_size=4; break; case CMYKAQuantum: packet_size=5; break; default: break; } if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*image->columns*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*image->columns*quantum_info->depth+7)/8)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m E n d i a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumEndian() returns the quantum endian of the image. % % The endian of the GetQuantumEndian method is: % % EndianType GetQuantumEndian(const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport EndianType GetQuantumEndian(const QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); return(quantum_info->endian); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumFormat() returns the quantum format of the image. % % The format of the GetQuantumFormat method is: % % QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); return(quantum_info->format); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumInfo() initializes the QuantumInfo structure to default values. % % The format of the GetQuantumInfo method is: % % GetQuantumInfo(const ImageInfo *image_info,QuantumInfo *quantum_info) % % A description of each parameter follows: % % o image_info: the image info. % % o quantum_info: the quantum info. % */ MagickExport void GetQuantumInfo(const ImageInfo *image_info, QuantumInfo *quantum_info) { const char *option; assert(quantum_info != (QuantumInfo *) NULL); (void) ResetMagickMemory(quantum_info,0,sizeof(*quantum_info)); quantum_info->quantum=8; quantum_info->maximum=1.0; quantum_info->scale=QuantumRange; quantum_info->pack=MagickTrue; quantum_info->semaphore=AcquireSemaphoreInfo(); quantum_info->signature=MagickCoreSignature; if (image_info == (const ImageInfo *) NULL) return; option=GetImageOption(image_info,"quantum:format"); if (option != (char *) NULL) quantum_info->format=(QuantumFormatType) ParseCommandOption( MagickQuantumFormatOptions,MagickFalse,option); option=GetImageOption(image_info,"quantum:minimum"); if (option != (char *) NULL) quantum_info->minimum=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"quantum:maximum"); if (option != (char *) NULL) quantum_info->maximum=StringToDouble(option,(char **) NULL); if ((quantum_info->minimum == 0.0) && (quantum_info->maximum == 0.0)) quantum_info->scale=0.0; else if (quantum_info->minimum == quantum_info->maximum) { quantum_info->scale=(double) QuantumRange/quantum_info->minimum; quantum_info->minimum=0.0; } else quantum_info->scale=(double) QuantumRange/(quantum_info->maximum- quantum_info->minimum); option=GetImageOption(image_info,"quantum:scale"); if (option != (char *) NULL) quantum_info->scale=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"quantum:polarity"); if (option != (char *) NULL) quantum_info->min_is_white=LocaleCompare(option,"min-is-white") == 0 ? MagickTrue : MagickFalse; quantum_info->endian=image_info->endian; ResetQuantumState(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumPixels() returns the quantum pixels. % % The format of the GetQuantumPixels method is: % % unsigned char *QuantumPixels GetQuantumPixels( % const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o image: the image. % */ MagickExport unsigned char *GetQuantumPixels(const QuantumInfo *quantum_info) { const int id = GetOpenMPThreadId(); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); return(quantum_info->pixels[id]); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumType() returns the quantum type of the image. % % The format of the GetQuantumType method is: % % QuantumType GetQuantumType(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport QuantumType GetQuantumType(Image *image,ExceptionInfo *exception) { QuantumType quantum_type; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); (void) exception; quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=CMYKAQuantum; } if (IsGrayColorspace(image->colorspace) != MagickFalse) { quantum_type=GrayQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=GrayAlphaQuantum; } if (image->storage_class == PseudoClass) { quantum_type=IndexQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=IndexAlphaQuantum; } return(quantum_type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t Q u a n t u m S t a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetQuantumState() resets the quantum state. % % The format of the ResetQuantumState method is: % % void ResetQuantumState(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickPrivate void ResetQuantumState(QuantumInfo *quantum_info) { static const unsigned int mask[32] = { 0x00000000U, 0x00000001U, 0x00000003U, 0x00000007U, 0x0000000fU, 0x0000001fU, 0x0000003fU, 0x0000007fU, 0x000000ffU, 0x000001ffU, 0x000003ffU, 0x000007ffU, 0x00000fffU, 0x00001fffU, 0x00003fffU, 0x00007fffU, 0x0000ffffU, 0x0001ffffU, 0x0003ffffU, 0x0007ffffU, 0x000fffffU, 0x001fffffU, 0x003fffffU, 0x007fffffU, 0x00ffffffU, 0x01ffffffU, 0x03ffffffU, 0x07ffffffU, 0x0fffffffU, 0x1fffffffU, 0x3fffffffU, 0x7fffffffU }; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->state.inverse_scale=1.0; if (fabs(quantum_info->scale) >= MagickEpsilon) quantum_info->state.inverse_scale/=quantum_info->scale; quantum_info->state.pixel=0U; quantum_info->state.bits=0U; quantum_info->state.mask=mask; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumAlphaType() sets the quantum format. % % The format of the SetQuantumAlphaType method is: % % void SetQuantumAlphaType(QuantumInfo *quantum_info, % const QuantumAlphaType type) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o type: the alpha type (e.g. associate). % */ MagickExport void SetQuantumAlphaType(QuantumInfo *quantum_info, const QuantumAlphaType type) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->alpha_type=type; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumDepth() sets the quantum depth. % % The format of the SetQuantumDepth method is: % % MagickBooleanType SetQuantumDepth(const Image *image, % QuantumInfo *quantum_info,const size_t depth) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o depth: the quantum depth. % */ MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=image->columns*quantum; if ((image->columns != 0) && (quantum != (extent/image->columns))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m E n d i a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumEndian() sets the quantum endian. % % The endian of the SetQuantumEndian method is: % % MagickBooleanType SetQuantumEndian(const Image *image, % QuantumInfo *quantum_info,const EndianType endian) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o endian: the quantum endian. % */ MagickExport MagickBooleanType SetQuantumEndian(const Image *image, QuantumInfo *quantum_info,const EndianType endian) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->endian=endian; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumFormat() sets the quantum format. % % The format of the SetQuantumFormat method is: % % MagickBooleanType SetQuantumFormat(const Image *image, % QuantumInfo *quantum_info,const QuantumFormatType format) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o format: the quantum format. % */ MagickExport MagickBooleanType SetQuantumFormat(const Image *image, QuantumInfo *quantum_info,const QuantumFormatType format) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->format=format; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m I m a g e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumImageType() sets the image type based on the quantum type. % % The format of the SetQuantumImageType method is: % % void ImageType SetQuantumImageType(Image *image, % const QuantumType quantum_type) % % A description of each parameter follows: % % o image: the image. % % o quantum_type: Declare which pixel components to transfer (red, green, % blue, opacity, RGB, or RGBA). % */ MagickExport void SetQuantumImageType(Image *image, const QuantumType quantum_type) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); switch (quantum_type) { case IndexQuantum: case IndexAlphaQuantum: { image->type=PaletteType; break; } case GrayQuantum: case GrayAlphaQuantum: { image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; break; } case CyanQuantum: case MagentaQuantum: case YellowQuantum: case BlackQuantum: case CMYKQuantum: case CMYKAQuantum: { image->type=ColorSeparationType; break; } default: { image->type=TrueColorType; break; } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m P a c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumPack() sets the quantum pack flag. % % The format of the SetQuantumPack method is: % % void SetQuantumPack(QuantumInfo *quantum_info, % const MagickBooleanType pack) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o pack: the pack flag. % */ MagickExport void SetQuantumPack(QuantumInfo *quantum_info, const MagickBooleanType pack) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->pack=pack; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m P a d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumPad() sets the quantum pad. % % The format of the SetQuantumPad method is: % % MagickBooleanType SetQuantumPad(const Image *image, % QuantumInfo *quantum_info,const size_t pad) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o pad: the quantum pad. % */ MagickExport MagickBooleanType SetQuantumPad(const Image *image, QuantumInfo *quantum_info,const size_t pad) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->pad=pad; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m M i n I s W h i t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumMinIsWhite() sets the quantum min-is-white flag. % % The format of the SetQuantumMinIsWhite method is: % % void SetQuantumMinIsWhite(QuantumInfo *quantum_info, % const MagickBooleanType min_is_white) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o min_is_white: the min-is-white flag. % */ MagickExport void SetQuantumMinIsWhite(QuantumInfo *quantum_info, const MagickBooleanType min_is_white) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->min_is_white=min_is_white; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m Q u a n t u m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumQuantum() sets the quantum quantum. % % The format of the SetQuantumQuantum method is: % % void SetQuantumQuantum(QuantumInfo *quantum_info, % const size_t quantum) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o quantum: the quantum quantum. % */ MagickExport void SetQuantumQuantum(QuantumInfo *quantum_info, const size_t quantum) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->quantum=quantum; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m S c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumScale() sets the quantum scale. % % The format of the SetQuantumScale method is: % % void SetQuantumScale(QuantumInfo *quantum_info,const double scale) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o scale: the quantum scale. % */ MagickExport void SetQuantumScale(QuantumInfo *quantum_info,const double scale) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); quantum_info->scale=scale; }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_5311_0
crossvul-cpp_data_good_4866_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /** @defgroup PI PI - Implementation of a packet iterator */ /*@{*/ /** @name Local static functions */ /*@{*/ /** Get next packet in layer-resolution-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-layer-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-precinct-component-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi); /** Get next packet in precinct-component-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi); /** Get next packet in component-precinct-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi); /** * Updates the coding parameters if the encoding is used with Progression order changes and final (or cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_poc_and_final(opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Updates the coding parameters if the encoding is not used with Progression order changes and final (and cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_num_comps the number of components * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_not_poc(opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the minimum dy of all the components of all the resolutions for the tile. */ static void opj_get_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * The precinct widths, heights, dx and dy for each component at each resolution will be stored as well. * the last parameter of the function should be an array of pointers of size nb components, each pointer leading * to an area of size 4 * max_res. The data is stored inside this area with the following pattern : * dx_compi_res0 , dy_compi_res0 , w_compi_res0, h_compi_res0 , dx_compi_res1 , dy_compi_res1 , w_compi_res1, h_compi_res1 , ... * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the minimum dy of all the components of all the resolutions for the tile. * @param p_resolutions pointer to an area corresponding to the one described above. */ static void opj_get_all_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions); /** * Allocates memory for a packet iterator. Data and data sizes are set by this operation. * No other data is set. The include section of the packet iterator is not allocated. * * @param p_image the image used to initialize the packet iterator (in fact only the number of components is relevant. * @param p_cp the coding parameters. * @param tileno the index of the tile from which creating the packet iterator. */ static opj_pi_iterator_t * opj_pi_create(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno); /** * FIXME DOC */ static void opj_pi_update_decode_not_poc(opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ static void opj_pi_update_decode_poc(opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ static OPJ_BOOL opj_pi_check_next_level(OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog); /*@}*/ /*@}*/ /* ========================================================== local functions ========================================================== */ static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ /* in below tests */ /* Fixes reading id:000026,sig:08,src:002419,op:int32,pos:60,val:+32 */ /* of https://github.com/uclouvain/openjpeg/issues/938 */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } /* See ISO-15441. B.12.1.3 Resolution level-position-component-layer progression */ if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ /* in below tests */ /* Relates to id:000019,sig:08,src:001098,op:flip1,pos:49 */ /* of https://github.com/uclouvain/openjpeg/issues/938 */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } /* See ISO-15441. B.12.1.4 Position-component-resolution level-layer progression */ if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ /* in below tests */ /* Fixes reading id:000019,sig:08,src:001098,op:flip1,pos:49 */ /* of https://github.com/uclouvain/openjpeg/issues/938 */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } /* See ISO-15441. B.12.1.5 Component-position-resolution level-layer progression */ if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static void opj_get_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res) { /* loop */ OPJ_UINT32 compno, resno; /* pointers */ const opj_tcp_t *l_tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* position in x and y of tile */ OPJ_UINT32 p, q; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps [p_tileno]; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ p = p_tileno % p_cp->tw; q = p_tileno / p_cp->tw; /* find extent of tile */ *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); /* max precision is 0 (can only grow) */ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min */ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* arithmetic variables to calculate */ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_pw, l_ph; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts */ for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); /* take the minimum size for dx for each comp and resolution */ *p_dx_min = opj_uint_min(*p_dx_min, l_dx); *p_dy_min = opj_uint_min(*p_dy_min, l_dy); /* various calculations of extents */ l_level_no = l_tccp->numresolutions - 1 - resno; l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy); l_product = l_pw * l_ph; /* update precision */ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_img_comp; ++l_tccp; } } static void opj_get_all_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions) { /* loop*/ OPJ_UINT32 compno, resno; /* pointers*/ const opj_tcp_t *tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* to store l_dx, l_dy, w and h for each resolution and component.*/ OPJ_UINT32 * lResolutionPtr; /* position in x and y of tile*/ OPJ_UINT32 p, q; /* non-corrected (in regard to image offset) tile offset */ OPJ_UINT32 l_tx0, l_ty0; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(tileno < p_cp->tw * p_cp->th); /* initializations*/ tcp = &p_cp->tcps [tileno]; l_tccp = tcp->tccps; l_img_comp = p_image->comps; /* position in x and y of tile*/ p = tileno % p_cp->tw; q = tileno / p_cp->tw; /* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */ l_tx0 = p_cp->tx0 + p * p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */ *p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0); *p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1); l_ty0 = p_cp->ty0 + q * p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */ *p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0); *p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1); /* max precision and resolution is 0 (can only grow)*/ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min*/ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* aritmetic variables to calculate*/ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; OPJ_UINT32 l_pdx, l_pdy, l_pw, l_ph; lResolutionPtr = p_resolutions[compno]; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts*/ l_level_no = l_tccp->numresolutions; for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; --l_level_no; /* precinct width and height*/ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; *lResolutionPtr++ = l_pdx; *lResolutionPtr++ = l_pdy; l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no)); /* take the minimum size for l_dx for each comp and resolution*/ *p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32) * p_dx_min, (OPJ_INT32)l_dx); *p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32) * p_dy_min, (OPJ_INT32)l_dy); /* various calculations of extents*/ l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy); *lResolutionPtr++ = l_pw; *lResolutionPtr++ = l_ph; l_product = l_pw * l_ph; /* update precision*/ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_tccp; ++l_img_comp; } } static opj_pi_iterator_t * opj_pi_create(const opj_image_t *image, const opj_cp_t *cp, OPJ_UINT32 tileno) { /* loop*/ OPJ_UINT32 pino, compno; /* number of poc in the p_pi*/ OPJ_UINT32 l_poc_bound; /* pointers to tile coding parameters and components.*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *tcp = 00; const opj_tccp_t *tccp = 00; /* current packet iterator being allocated*/ opj_pi_iterator_t *l_current_pi = 00; /* preconditions in debug*/ assert(cp != 00); assert(image != 00); assert(tileno < cp->tw * cp->th); /* initializations*/ tcp = &cp->tcps[tileno]; l_poc_bound = tcp->numpocs + 1; /* memory allocations*/ l_pi = (opj_pi_iterator_t*) opj_calloc((l_poc_bound), sizeof(opj_pi_iterator_t)); if (!l_pi) { return NULL; } l_current_pi = l_pi; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_pi->comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (! l_current_pi->comps) { opj_pi_destroy(l_pi, l_poc_bound); return NULL; } l_current_pi->numcomps = image->numcomps; for (compno = 0; compno < image->numcomps; ++compno) { opj_pi_comp_t *comp = &l_current_pi->comps[compno]; tccp = &tcp->tccps[compno]; comp->resolutions = (opj_pi_resolution_t*) opj_calloc(tccp->numresolutions, sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { opj_pi_destroy(l_pi, l_poc_bound); return 00; } comp->numresolutions = tccp->numresolutions; } ++l_current_pi; } return l_pi; } static void opj_pi_update_encode_poc_and_final(opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs + 1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE = l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; /* special treatment for the first element*/ l_current_poc->layS = 0; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; for (pino = 1; pino < l_poc_bound ; ++pino) { l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE = l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; /* special treatment here different from the first element*/ l_current_poc->layS = (l_current_poc->layE > (l_current_poc - 1)->layE) ? l_current_poc->layE : 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } static void opj_pi_update_encode_not_poc(opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs + 1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_poc->compS = 0; l_current_poc->compE = p_num_comps;/*p_image->numcomps;*/ l_current_poc->resS = 0; l_current_poc->resE = p_max_res; l_current_poc->layS = 0; l_current_poc->layE = l_tcp->numlayers; l_current_poc->prg = l_tcp->prg; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } static void opj_pi_update_decode_poc(opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; opj_poc_t* l_current_poc = 0; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_pi != 00); assert(p_tcp != 00); /* initializations*/ l_bound = p_tcp->numpocs + 1; l_current_pi = p_pi; l_current_poc = p_tcp->pocs; for (pino = 0; pino < l_bound; ++pino) { l_current_pi->poc.prg = l_current_poc->prg; /* Progression Order #0 */ l_current_pi->first = 1; l_current_pi->poc.resno0 = l_current_poc->resno0; /* Resolution Level Index #0 (Start) */ l_current_pi->poc.compno0 = l_current_poc->compno0; /* Component Index #0 (Start) */ l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = l_current_poc->resno1; /* Resolution Level Index #0 (End) */ l_current_pi->poc.compno1 = l_current_poc->compno1; /* Component Index #0 (End) */ l_current_pi->poc.layno1 = l_current_poc->layno1; /* Layer Index #0 (End) */ l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; ++l_current_poc; } } static void opj_pi_update_decode_not_poc(opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; /* preconditions in debug*/ assert(p_tcp != 00); assert(p_pi != 00); /* initializations*/ l_bound = p_tcp->numpocs + 1; l_current_pi = p_pi; for (pino = 0; pino < l_bound; ++pino) { l_current_pi->poc.prg = p_tcp->prg; l_current_pi->first = 1; l_current_pi->poc.resno0 = 0; l_current_pi->poc.compno0 = 0; l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = p_max_res; l_current_pi->poc.compno1 = l_current_pi->numcomps; l_current_pi->poc.layno1 = p_tcp->numlayers; l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; } } static OPJ_BOOL opj_pi_check_next_level(OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog) { OPJ_INT32 i; opj_tcp_t *tcps = &cp->tcps[tileno]; opj_poc_t *tcp = &tcps->pocs[pino]; if (pos >= 0) { for (i = pos; pos >= 0; i--) { switch (prog[i]) { case 'R': if (tcp->res_t == tcp->resE) { if (opj_pi_check_next_level(pos - 1, cp, tileno, pino, prog)) { return OPJ_TRUE; } else { return OPJ_FALSE; } } else { return OPJ_TRUE; } break; case 'C': if (tcp->comp_t == tcp->compE) { if (opj_pi_check_next_level(pos - 1, cp, tileno, pino, prog)) { return OPJ_TRUE; } else { return OPJ_FALSE; } } else { return OPJ_TRUE; } break; case 'L': if (tcp->lay_t == tcp->layE) { if (opj_pi_check_next_level(pos - 1, cp, tileno, pino, prog)) { return OPJ_TRUE; } else { return OPJ_FALSE; } } else { return OPJ_TRUE; } break; case 'P': switch (tcp->prg) { case OPJ_LRCP: /* fall through */ case OPJ_RLCP: if (tcp->prc_t == tcp->prcE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { return OPJ_TRUE; } else { return OPJ_FALSE; } } else { return OPJ_TRUE; } break; default: if (tcp->tx0_t == tcp->txE) { /*TY*/ if (tcp->ty0_t == tcp->tyE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { return OPJ_TRUE; } else { return OPJ_FALSE; } } else { return OPJ_TRUE; }/*TY*/ } else { return OPJ_TRUE; } break; }/*end case P*/ }/*end switch*/ }/*end for*/ }/*end if*/ return OPJ_FALSE; } /* ========================================================== Packet iterator interface ========================================================== */ opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0, l_tx1, l_ty0, l_ty1; OPJ_UINT32 l_dx_min, l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p, l_step_c, l_step_r, l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs + 1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image, p_cp, p_tile_no, &l_tx0, &l_tx1, &l_ty0, &l_ty1, &l_dx_min, &l_dy_min, &l_max_prec, &l_max_res, l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ /* prevent an integer overflow issue */ /* 0 < l_tcp->numlayers < 65536 c.f. opj_j2k_read_cod in j2k.c */ l_current_pi->include = 00; if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U))) { l_current_pi->include = (OPJ_INT16*) opj_calloc((size_t)( l_tcp->numlayers + 1U) * l_step_l, sizeof(OPJ_INT16)); } if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino < l_bound ; ++pino) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi - 1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc(l_pi, l_tcp, l_max_prec, l_max_res); } else { opj_pi_update_decode_not_poc(l_pi, l_tcp, l_max_prec, l_max_res); } return l_pi; } opj_pi_iterator_t *opj_pi_initialise_encode(const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no, J2K_T2_MODE p_t2_mode) { /* loop*/ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions*/ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set*/ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0, l_tx1, l_ty0, l_ty1; OPJ_UINT32 l_dx_min, l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p, l_step_c, l_step_r, l_step_l ; OPJ_UINT32 l_data_stride; /* pointers*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs + 1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi*/ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array*/ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters*/ opj_get_all_encoding_parameters(p_image, p_cp, p_tile_no, &l_tx0, &l_tx1, &l_ty0, &l_ty1, &l_dx_min, &l_dy_min, &l_max_prec, &l_max_res, l_tmp_ptr); /* step calculations*/ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator*/ l_pi->tp_on = (OPJ_BYTE)p_cp->m_specific_param.m_enc.m_tp_on; l_current_pi = l_pi; /* memory allocation for include*/ l_current_pi->include = (OPJ_INT16*) opj_calloc(l_tcp->numlayers * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator*/ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino < l_bound ; ++pino) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi - 1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC && (OPJ_IS_CINEMA(p_cp->rsiz) || p_t2_mode == FINAL_PASS)) { opj_pi_update_encode_poc_and_final(p_cp, p_tile_no, l_tx0, l_tx1, l_ty0, l_ty1, l_max_prec, l_max_res, l_dx_min, l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp, p_image->numcomps, p_tile_no, l_tx0, l_tx1, l_ty0, l_ty1, l_max_prec, l_max_res, l_dx_min, l_dy_min); } return l_pi; } void opj_pi_create_encode(opj_pi_iterator_t *pi, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, OPJ_UINT32 tpnum, OPJ_INT32 tppos, J2K_T2_MODE t2_mode) { const OPJ_CHAR *prog; OPJ_INT32 i; OPJ_UINT32 incr_top = 1, resetX = 0; opj_tcp_t *tcps = &cp->tcps[tileno]; opj_poc_t *tcp = &tcps->pocs[pino]; prog = opj_j2k_convert_progression_order(tcp->prg); pi[pino].first = 1; pi[pino].poc.prg = tcp->prg; if (!(cp->m_specific_param.m_enc.m_tp_on && ((!OPJ_IS_CINEMA(cp->rsiz) && (t2_mode == FINAL_PASS)) || OPJ_IS_CINEMA(cp->rsiz)))) { pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; } else { for (i = tppos + 1; i < 4; i++) { switch (prog[i]) { case 'R': pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; break; case 'C': pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; break; case 'L': pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; break; case 'P': switch (tcp->prg) { case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; break; default: pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; break; } break; } } if (tpnum == 0) { for (i = tppos; i >= 0; i--) { switch (prog[i]) { case 'C': tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; break; case 'R': tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; break; case 'L': tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; break; case 'P': switch (tcp->prg) { case OPJ_LRCP: case OPJ_RLCP: tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; break; default: tcp->tx0_t = tcp->txS; tcp->ty0_t = tcp->tyS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; break; } break; } } incr_top = 1; } else { for (i = tppos; i >= 0; i--) { switch (prog[i]) { case 'C': pi[pino].poc.compno0 = tcp->comp_t - 1; pi[pino].poc.compno1 = tcp->comp_t; break; case 'R': pi[pino].poc.resno0 = tcp->res_t - 1; pi[pino].poc.resno1 = tcp->res_t; break; case 'L': pi[pino].poc.layno0 = tcp->lay_t - 1; pi[pino].poc.layno1 = tcp->lay_t; break; case 'P': switch (tcp->prg) { case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prc_t - 1; pi[pino].poc.precno1 = tcp->prc_t; break; default: pi[pino].poc.tx0 = (OPJ_INT32)(tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.tx1 = (OPJ_INT32)tcp->tx0_t ; pi[pino].poc.ty0 = (OPJ_INT32)(tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy)); pi[pino].poc.ty1 = (OPJ_INT32)tcp->ty0_t ; break; } break; } if (incr_top == 1) { switch (prog[i]) { case 'R': if (tcp->res_t == tcp->resE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; incr_top = 1; } else { incr_top = 0; } } else { pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; incr_top = 0; } break; case 'C': if (tcp->comp_t == tcp->compE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; incr_top = 1; } else { incr_top = 0; } } else { pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; incr_top = 0; } break; case 'L': if (tcp->lay_t == tcp->layE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; incr_top = 1; } else { incr_top = 0; } } else { pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; incr_top = 0; } break; case 'P': switch (tcp->prg) { case OPJ_LRCP: case OPJ_RLCP: if (tcp->prc_t == tcp->prcE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; incr_top = 1; } else { incr_top = 0; } } else { pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; incr_top = 0; } break; default: if (tcp->tx0_t >= tcp->txE) { if (tcp->ty0_t >= tcp->tyE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { tcp->ty0_t = tcp->tyS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top = 1; resetX = 1; } else { incr_top = 0; resetX = 0; } } else { pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top = 0; resetX = 1; } if (resetX == 1) { tcp->tx0_t = tcp->txS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; } } else { pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; incr_top = 0; } break; } break; } } } } } } void opj_pi_destroy(opj_pi_iterator_t *p_pi, OPJ_UINT32 p_nb_elements) { OPJ_UINT32 compno, pino; opj_pi_iterator_t *l_current_pi = p_pi; if (p_pi) { if (p_pi->include) { opj_free(p_pi->include); p_pi->include = 00; } for (pino = 0; pino < p_nb_elements; ++pino) { if (l_current_pi->comps) { opj_pi_comp_t *l_current_component = l_current_pi->comps; for (compno = 0; compno < l_current_pi->numcomps; compno++) { if (l_current_component->resolutions) { opj_free(l_current_component->resolutions); l_current_component->resolutions = 00; } ++l_current_component; } opj_free(l_current_pi->comps); l_current_pi->comps = 0; } ++l_current_pi; } opj_free(p_pi); } } void opj_pi_update_encoding_parameters(const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* encoding parameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0, l_tx1, l_ty0, l_ty1; OPJ_UINT32 l_dx_min, l_dy_min; /* pointers */ opj_tcp_t *l_tcp = 00; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); l_tcp = &(p_cp->tcps[p_tile_no]); /* get encoding parameters */ opj_get_encoding_parameters(p_image, p_cp, p_tile_no, &l_tx0, &l_tx1, &l_ty0, &l_ty1, &l_dx_min, &l_dy_min, &l_max_prec, &l_max_res); if (l_tcp->POC) { opj_pi_update_encode_poc_and_final(p_cp, p_tile_no, l_tx0, l_tx1, l_ty0, l_ty1, l_max_prec, l_max_res, l_dx_min, l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp, p_image->numcomps, p_tile_no, l_tx0, l_tx1, l_ty0, l_ty1, l_max_prec, l_max_res, l_dx_min, l_dy_min); } } OPJ_BOOL opj_pi_next(opj_pi_iterator_t * pi) { switch (pi->poc.prg) { case OPJ_LRCP: return opj_pi_next_lrcp(pi); case OPJ_RLCP: return opj_pi_next_rlcp(pi); case OPJ_RPCL: return opj_pi_next_rpcl(pi); case OPJ_PCRL: return opj_pi_next_pcrl(pi); case OPJ_CPRL: return opj_pi_next_cprl(pi); case OPJ_PROG_UNKNOWN: return OPJ_FALSE; } return OPJ_FALSE; }
./CrossVul/dataset_final_sorted/CWE-369/c/good_4866_0
crossvul-cpp_data_good_2768_0
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Implementation of the Transmission Control Protocol(TCP). * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Mark Evans, <evansmp@uhura.aston.ac.uk> * Corey Minyard <wf-rch!minyard@relay.EU.net> * Florian La Roche, <flla@stud.uni-sb.de> * Charles Hedrick, <hedrick@klinzhai.rutgers.edu> * Linus Torvalds, <torvalds@cs.helsinki.fi> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Matthew Dillon, <dillon@apollo.west.oic.com> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Jorge Cwik, <jorge@laser.satlink.net> * * Fixes: * Alan Cox : Numerous verify_area() calls * Alan Cox : Set the ACK bit on a reset * Alan Cox : Stopped it crashing if it closed while * sk->inuse=1 and was trying to connect * (tcp_err()). * Alan Cox : All icmp error handling was broken * pointers passed where wrong and the * socket was looked up backwards. Nobody * tested any icmp error code obviously. * Alan Cox : tcp_err() now handled properly. It * wakes people on errors. poll * behaves and the icmp error race * has gone by moving it into sock.c * Alan Cox : tcp_send_reset() fixed to work for * everything not just packets for * unknown sockets. * Alan Cox : tcp option processing. * Alan Cox : Reset tweaked (still not 100%) [Had * syn rule wrong] * Herp Rosmanith : More reset fixes * Alan Cox : No longer acks invalid rst frames. * Acking any kind of RST is right out. * Alan Cox : Sets an ignore me flag on an rst * receive otherwise odd bits of prattle * escape still * Alan Cox : Fixed another acking RST frame bug. * Should stop LAN workplace lockups. * Alan Cox : Some tidyups using the new skb list * facilities * Alan Cox : sk->keepopen now seems to work * Alan Cox : Pulls options out correctly on accepts * Alan Cox : Fixed assorted sk->rqueue->next errors * Alan Cox : PSH doesn't end a TCP read. Switched a * bit to skb ops. * Alan Cox : Tidied tcp_data to avoid a potential * nasty. * Alan Cox : Added some better commenting, as the * tcp is hard to follow * Alan Cox : Removed incorrect check for 20 * psh * Michael O'Reilly : ack < copied bug fix. * Johannes Stille : Misc tcp fixes (not all in yet). * Alan Cox : FIN with no memory -> CRASH * Alan Cox : Added socket option proto entries. * Also added awareness of them to accept. * Alan Cox : Added TCP options (SOL_TCP) * Alan Cox : Switched wakeup calls to callbacks, * so the kernel can layer network * sockets. * Alan Cox : Use ip_tos/ip_ttl settings. * Alan Cox : Handle FIN (more) properly (we hope). * Alan Cox : RST frames sent on unsynchronised * state ack error. * Alan Cox : Put in missing check for SYN bit. * Alan Cox : Added tcp_select_window() aka NET2E * window non shrink trick. * Alan Cox : Added a couple of small NET2E timer * fixes * Charles Hedrick : TCP fixes * Toomas Tamm : TCP window fixes * Alan Cox : Small URG fix to rlogin ^C ack fight * Charles Hedrick : Rewrote most of it to actually work * Linus : Rewrote tcp_read() and URG handling * completely * Gerhard Koerting: Fixed some missing timer handling * Matthew Dillon : Reworked TCP machine states as per RFC * Gerhard Koerting: PC/TCP workarounds * Adam Caldwell : Assorted timer/timing errors * Matthew Dillon : Fixed another RST bug * Alan Cox : Move to kernel side addressing changes. * Alan Cox : Beginning work on TCP fastpathing * (not yet usable) * Arnt Gulbrandsen: Turbocharged tcp_check() routine. * Alan Cox : TCP fast path debugging * Alan Cox : Window clamping * Michael Riepe : Bug in tcp_check() * Matt Dillon : More TCP improvements and RST bug fixes * Matt Dillon : Yet more small nasties remove from the * TCP code (Be very nice to this man if * tcp finally works 100%) 8) * Alan Cox : BSD accept semantics. * Alan Cox : Reset on closedown bug. * Peter De Schrijver : ENOTCONN check missing in tcp_sendto(). * Michael Pall : Handle poll() after URG properly in * all cases. * Michael Pall : Undo the last fix in tcp_read_urg() * (multi URG PUSH broke rlogin). * Michael Pall : Fix the multi URG PUSH problem in * tcp_readable(), poll() after URG * works now. * Michael Pall : recv(...,MSG_OOB) never blocks in the * BSD api. * Alan Cox : Changed the semantics of sk->socket to * fix a race and a signal problem with * accept() and async I/O. * Alan Cox : Relaxed the rules on tcp_sendto(). * Yury Shevchuk : Really fixed accept() blocking problem. * Craig I. Hagan : Allow for BSD compatible TIME_WAIT for * clients/servers which listen in on * fixed ports. * Alan Cox : Cleaned the above up and shrank it to * a sensible code size. * Alan Cox : Self connect lockup fix. * Alan Cox : No connect to multicast. * Ross Biro : Close unaccepted children on master * socket close. * Alan Cox : Reset tracing code. * Alan Cox : Spurious resets on shutdown. * Alan Cox : Giant 15 minute/60 second timer error * Alan Cox : Small whoops in polling before an * accept. * Alan Cox : Kept the state trace facility since * it's handy for debugging. * Alan Cox : More reset handler fixes. * Alan Cox : Started rewriting the code based on * the RFC's for other useful protocol * references see: Comer, KA9Q NOS, and * for a reference on the difference * between specifications and how BSD * works see the 4.4lite source. * A.N.Kuznetsov : Don't time wait on completion of tidy * close. * Linus Torvalds : Fin/Shutdown & copied_seq changes. * Linus Torvalds : Fixed BSD port reuse to work first syn * Alan Cox : Reimplemented timers as per the RFC * and using multiple timers for sanity. * Alan Cox : Small bug fixes, and a lot of new * comments. * Alan Cox : Fixed dual reader crash by locking * the buffers (much like datagram.c) * Alan Cox : Fixed stuck sockets in probe. A probe * now gets fed up of retrying without * (even a no space) answer. * Alan Cox : Extracted closing code better * Alan Cox : Fixed the closing state machine to * resemble the RFC. * Alan Cox : More 'per spec' fixes. * Jorge Cwik : Even faster checksumming. * Alan Cox : tcp_data() doesn't ack illegal PSH * only frames. At least one pc tcp stack * generates them. * Alan Cox : Cache last socket. * Alan Cox : Per route irtt. * Matt Day : poll()->select() match BSD precisely on error * Alan Cox : New buffers * Marc Tamsky : Various sk->prot->retransmits and * sk->retransmits misupdating fixed. * Fixed tcp_write_timeout: stuck close, * and TCP syn retries gets used now. * Mark Yarvis : In tcp_read_wakeup(), don't send an * ack if state is TCP_CLOSED. * Alan Cox : Look up device on a retransmit - routes may * change. Doesn't yet cope with MSS shrink right * but it's a start! * Marc Tamsky : Closing in closing fixes. * Mike Shaver : RFC1122 verifications. * Alan Cox : rcv_saddr errors. * Alan Cox : Block double connect(). * Alan Cox : Small hooks for enSKIP. * Alexey Kuznetsov: Path MTU discovery. * Alan Cox : Support soft errors. * Alan Cox : Fix MTU discovery pathological case * when the remote claims no mtu! * Marc Tamsky : TCP_CLOSE fix. * Colin (G3TNE) : Send a reset on syn ack replies in * window but wrong (fixes NT lpd problems) * Pedro Roque : Better TCP window handling, delayed ack. * Joerg Reuter : No modification of locked buffers in * tcp_do_retransmit() * Eric Schenk : Changed receiver side silly window * avoidance algorithm to BSD style * algorithm. This doubles throughput * against machines running Solaris, * and seems to result in general * improvement. * Stefan Magdalinski : adjusted tcp_readable() to fix FIONREAD * Willy Konynenberg : Transparent proxying support. * Mike McLagan : Routing by source * Keith Owens : Do proper merging with partial SKB's in * tcp_do_sendmsg to avoid burstiness. * Eric Schenk : Fix fast close down bug with * shutdown() followed by close(). * Andi Kleen : Make poll agree with SIGIO * Salvatore Sanfilippo : Support SO_LINGER with linger == 1 and * lingertime == 0 (RFC 793 ABORT Call) * Hirokazu Takahashi : Use copy_from_user() instead of * csum_and_copy_from_user() if possible. * * 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. * * Description of States: * * TCP_SYN_SENT sent a connection request, waiting for ack * * TCP_SYN_RECV received a connection request, sent ack, * waiting for final ack in three-way handshake. * * TCP_ESTABLISHED connection established * * TCP_FIN_WAIT1 our side has shutdown, waiting to complete * transmission of remaining buffered data * * TCP_FIN_WAIT2 all buffered data sent, waiting for remote * to shutdown * * TCP_CLOSING both sides have shutdown but we still have * data we have to finish sending * * TCP_TIME_WAIT timeout to catch resent junk before entering * closed, can only be entered from FIN_WAIT2 * or CLOSING. Required because the other end * may not have gotten our last ACK causing it * to retransmit the data packet (which we ignore) * * TCP_CLOSE_WAIT remote side has shutdown and is waiting for * us to finish writing our data and to shutdown * (we have to close() to move on to LAST_ACK) * * TCP_LAST_ACK out side has shutdown after remote has * shutdown. There may still be data in our * buffer that we have to finish sending * * TCP_CLOSE socket is finished */ #define pr_fmt(fmt) "TCP: " fmt #include <crypto/hash.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/poll.h> #include <linux/inet_diag.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/skbuff.h> #include <linux/scatterlist.h> #include <linux/splice.h> #include <linux/net.h> #include <linux/socket.h> #include <linux/random.h> #include <linux/bootmem.h> #include <linux/highmem.h> #include <linux/swap.h> #include <linux/cache.h> #include <linux/err.h> #include <linux/time.h> #include <linux/slab.h> #include <net/icmp.h> #include <net/inet_common.h> #include <net/tcp.h> #include <net/xfrm.h> #include <net/ip.h> #include <net/sock.h> #include <linux/uaccess.h> #include <asm/ioctls.h> #include <net/busy_poll.h> int sysctl_tcp_min_tso_segs __read_mostly = 2; int sysctl_tcp_autocorking __read_mostly = 1; struct percpu_counter tcp_orphan_count; EXPORT_SYMBOL_GPL(tcp_orphan_count); long sysctl_tcp_mem[3] __read_mostly; int sysctl_tcp_wmem[3] __read_mostly; int sysctl_tcp_rmem[3] __read_mostly; EXPORT_SYMBOL(sysctl_tcp_mem); EXPORT_SYMBOL(sysctl_tcp_rmem); EXPORT_SYMBOL(sysctl_tcp_wmem); atomic_long_t tcp_memory_allocated; /* Current allocated memory. */ EXPORT_SYMBOL(tcp_memory_allocated); /* * Current number of TCP sockets. */ struct percpu_counter tcp_sockets_allocated; EXPORT_SYMBOL(tcp_sockets_allocated); /* * TCP splice context */ struct tcp_splice_state { struct pipe_inode_info *pipe; size_t len; unsigned int flags; }; /* * Pressure flag: try to collapse. * Technical note: it is used by multiple contexts non atomically. * All the __sk_mem_schedule() is of this nature: accounting * is strict, actions are advisory and have some latency. */ int tcp_memory_pressure __read_mostly; EXPORT_SYMBOL(tcp_memory_pressure); void tcp_enter_memory_pressure(struct sock *sk) { if (!tcp_memory_pressure) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES); tcp_memory_pressure = 1; } } EXPORT_SYMBOL(tcp_enter_memory_pressure); /* Convert seconds to retransmits based on initial and max timeout */ static u8 secs_to_retrans(int seconds, int timeout, int rto_max) { u8 res = 0; if (seconds > 0) { int period = timeout; res = 1; while (seconds > period && res < 255) { res++; timeout <<= 1; if (timeout > rto_max) timeout = rto_max; period += timeout; } } return res; } /* Convert retransmits to seconds based on initial and max timeout */ static int retrans_to_secs(u8 retrans, int timeout, int rto_max) { int period = 0; if (retrans > 0) { period = timeout; while (--retrans) { timeout <<= 1; if (timeout > rto_max) timeout = rto_max; period += timeout; } } return period; } /* Address-family independent initialization for a tcp_sock. * * NOTE: A lot of things set to zero explicitly by call to * sk_alloc() so need not be done here. */ void tcp_init_sock(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); tp->out_of_order_queue = RB_ROOT; tcp_init_xmit_timers(sk); tcp_prequeue_init(tp); INIT_LIST_HEAD(&tp->tsq_node); icsk->icsk_rto = TCP_TIMEOUT_INIT; tp->mdev_us = jiffies_to_usecs(TCP_TIMEOUT_INIT); minmax_reset(&tp->rtt_min, tcp_time_stamp, ~0U); /* So many TCP implementations out there (incorrectly) count the * initial SYN frame in their delayed-ACK and congestion control * algorithms that we must have the following bandaid to talk * efficiently to them. -DaveM */ tp->snd_cwnd = TCP_INIT_CWND; /* There's a bubble in the pipe until at least the first ACK. */ tp->app_limited = ~0U; /* See draft-stevens-tcpca-spec-01 for discussion of the * initialization of these values. */ tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; tp->snd_cwnd_clamp = ~0; tp->mss_cache = TCP_MSS_DEFAULT; tp->reordering = sock_net(sk)->ipv4.sysctl_tcp_reordering; tcp_assign_congestion_control(sk); tp->tsoffset = 0; sk->sk_state = TCP_CLOSE; sk->sk_write_space = sk_stream_write_space; sock_set_flag(sk, SOCK_USE_WRITE_QUEUE); icsk->icsk_sync_mss = tcp_sync_mss; sk->sk_sndbuf = sysctl_tcp_wmem[1]; sk->sk_rcvbuf = sysctl_tcp_rmem[1]; sk_sockets_allocated_inc(sk); } EXPORT_SYMBOL(tcp_init_sock); static void tcp_tx_timestamp(struct sock *sk, u16 tsflags, struct sk_buff *skb) { if (tsflags && skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); sock_tx_timestamp(sk, tsflags, &shinfo->tx_flags); if (tsflags & SOF_TIMESTAMPING_TX_ACK) tcb->txstamp_ack = 1; if (tsflags & SOF_TIMESTAMPING_TX_RECORD_MASK) shinfo->tskey = TCP_SKB_CB(skb)->seq + skb->len - 1; } } /* * Wait for a TCP event. * * Note that we don't need to lock the socket, as the upper poll layers * take care of normal races (between the test and the event) and we don't * go look at any of the socket buffers directly. */ unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait) { unsigned int mask; struct sock *sk = sock->sk; const struct tcp_sock *tp = tcp_sk(sk); int state; sock_rps_record_flow(sk); sock_poll_wait(file, sk_sleep(sk), wait); state = sk_state_load(sk); if (state == TCP_LISTEN) return inet_csk_listen_poll(sk); /* Socket is not locked. We are protected from async events * by poll logic and correct handling of state changes * made by other threads is impossible in any case. */ mask = 0; /* * POLLHUP is certainly not done right. But poll() doesn't * have a notion of HUP in just one direction, and for a * socket the read side is more interesting. * * Some poll() documentation says that POLLHUP is incompatible * with the POLLOUT/POLLWR flags, so somebody should check this * all. But careful, it tends to be safer to return too many * bits than too few, and you can easily break real applications * if you don't tell them that something has hung up! * * Check-me. * * Check number 1. POLLHUP is _UNMASKABLE_ event (see UNIX98 and * our fs/select.c). It means that after we received EOF, * poll always returns immediately, making impossible poll() on write() * in state CLOSE_WAIT. One solution is evident --- to set POLLHUP * if and only if shutdown has been made in both directions. * Actually, it is interesting to look how Solaris and DUX * solve this dilemma. I would prefer, if POLLHUP were maskable, * then we could set it on SND_SHUTDOWN. BTW examples given * in Stevens' books assume exactly this behaviour, it explains * why POLLHUP is incompatible with POLLOUT. --ANK * * NOTE. Check for TCP_CLOSE is added. The goal is to prevent * blocking on fresh not-connected or disconnected socket. --ANK */ if (sk->sk_shutdown == SHUTDOWN_MASK || state == TCP_CLOSE) mask |= POLLHUP; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLIN | POLLRDNORM | POLLRDHUP; /* Connected or passive Fast Open socket? */ if (state != TCP_SYN_SENT && (state != TCP_SYN_RECV || tp->fastopen_rsk)) { int target = sock_rcvlowat(sk, 0, INT_MAX); if (tp->urg_seq == tp->copied_seq && !sock_flag(sk, SOCK_URGINLINE) && tp->urg_data) target++; if (tp->rcv_nxt - tp->copied_seq >= target) mask |= POLLIN | POLLRDNORM; if (!(sk->sk_shutdown & SEND_SHUTDOWN)) { if (sk_stream_is_writeable(sk)) { mask |= POLLOUT | POLLWRNORM; } else { /* send SIGIO later */ sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); /* Race breaker. If space is freed after * wspace test but before the flags are set, * IO signal will be lost. Memory barrier * pairs with the input side. */ smp_mb__after_atomic(); if (sk_stream_is_writeable(sk)) mask |= POLLOUT | POLLWRNORM; } } else mask |= POLLOUT | POLLWRNORM; if (tp->urg_data & TCP_URG_VALID) mask |= POLLPRI; } else if (state == TCP_SYN_SENT && inet_sk(sk)->defer_connect) { /* Active TCP fastopen socket with defer_connect * Return POLLOUT so application can call write() * in order for kernel to generate SYN+data */ mask |= POLLOUT | POLLWRNORM; } /* This barrier is coupled with smp_wmb() in tcp_reset() */ smp_rmb(); if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR; return mask; } EXPORT_SYMBOL(tcp_poll); int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg) { struct tcp_sock *tp = tcp_sk(sk); int answ; bool slow; switch (cmd) { case SIOCINQ: if (sk->sk_state == TCP_LISTEN) return -EINVAL; slow = lock_sock_fast(sk); answ = tcp_inq(sk); unlock_sock_fast(sk, slow); break; case SIOCATMARK: answ = tp->urg_data && tp->urg_seq == tp->copied_seq; break; case SIOCOUTQ: if (sk->sk_state == TCP_LISTEN) return -EINVAL; if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) answ = 0; else answ = tp->write_seq - tp->snd_una; break; case SIOCOUTQNSD: if (sk->sk_state == TCP_LISTEN) return -EINVAL; if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) answ = 0; else answ = tp->write_seq - tp->snd_nxt; break; default: return -ENOIOCTLCMD; } return put_user(answ, (int __user *)arg); } EXPORT_SYMBOL(tcp_ioctl); static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb) { TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH; tp->pushed_seq = tp->write_seq; } static inline bool forced_push(const struct tcp_sock *tp) { return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1)); } static void skb_entail(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); skb->csum = 0; tcb->seq = tcb->end_seq = tp->write_seq; tcb->tcp_flags = TCPHDR_ACK; tcb->sacked = 0; __skb_header_release(skb); tcp_add_write_queue_tail(sk, skb); sk->sk_wmem_queued += skb->truesize; sk_mem_charge(sk, skb->truesize); if (tp->nonagle & TCP_NAGLE_PUSH) tp->nonagle &= ~TCP_NAGLE_PUSH; tcp_slow_start_after_idle_check(sk); } static inline void tcp_mark_urg(struct tcp_sock *tp, int flags) { if (flags & MSG_OOB) tp->snd_up = tp->write_seq; } /* If a not yet filled skb is pushed, do not send it if * we have data packets in Qdisc or NIC queues : * Because TX completion will happen shortly, it gives a chance * to coalesce future sendmsg() payload into this skb, without * need for a timer, and with no latency trade off. * As packets containing data payload have a bigger truesize * than pure acks (dataless) packets, the last checks prevent * autocorking if we only have an ACK in Qdisc/NIC queues, * or if TX completion was delayed after we processed ACK packet. */ static bool tcp_should_autocork(struct sock *sk, struct sk_buff *skb, int size_goal) { return skb->len < size_goal && sysctl_tcp_autocorking && skb != tcp_write_queue_head(sk) && atomic_read(&sk->sk_wmem_alloc) > skb->truesize; } static void tcp_push(struct sock *sk, int flags, int mss_now, int nonagle, int size_goal) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; if (!tcp_send_head(sk)) return; skb = tcp_write_queue_tail(sk); if (!(flags & MSG_MORE) || forced_push(tp)) tcp_mark_push(tp, skb); tcp_mark_urg(tp, flags); if (tcp_should_autocork(sk, skb, size_goal)) { /* avoid atomic op if TSQ_THROTTLED bit is already set */ if (!test_bit(TSQ_THROTTLED, &sk->sk_tsq_flags)) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPAUTOCORKING); set_bit(TSQ_THROTTLED, &sk->sk_tsq_flags); } /* It is possible TX completion already happened * before we set TSQ_THROTTLED. */ if (atomic_read(&sk->sk_wmem_alloc) > skb->truesize) return; } if (flags & MSG_MORE) nonagle = TCP_NAGLE_CORK; __tcp_push_pending_frames(sk, mss_now, nonagle); } static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb, unsigned int offset, size_t len) { struct tcp_splice_state *tss = rd_desc->arg.data; int ret; ret = skb_splice_bits(skb, skb->sk, offset, tss->pipe, min(rd_desc->count, len), tss->flags); if (ret > 0) rd_desc->count -= ret; return ret; } static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss) { /* Store TCP splice context information in read_descriptor_t. */ read_descriptor_t rd_desc = { .arg.data = tss, .count = tss->len, }; return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv); } /** * tcp_splice_read - splice data from TCP socket to a pipe * @sock: socket to splice from * @ppos: position (not valid) * @pipe: pipe to splice to * @len: number of bytes to splice * @flags: splice modifier flags * * Description: * Will read pages from given socket and fill them into a pipe. * **/ ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct sock *sk = sock->sk; struct tcp_splice_state tss = { .pipe = pipe, .len = len, .flags = flags, }; long timeo; ssize_t spliced; int ret; sock_rps_record_flow(sk); /* * We can't seek on a socket input */ if (unlikely(*ppos)) return -ESPIPE; ret = spliced = 0; lock_sock(sk); timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK); while (tss.len) { ret = __tcp_splice_read(sk, &tss); if (ret < 0) break; else if (!ret) { if (spliced) break; if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { ret = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_state == TCP_CLOSE) { /* * This occurs when user tries to read * from never connected socket. */ if (!sock_flag(sk, SOCK_DONE)) ret = -ENOTCONN; break; } if (!timeo) { ret = -EAGAIN; break; } /* if __tcp_splice_read() got nothing while we have * an skb in receive queue, we do not want to loop. * This might happen with URG data. */ if (!skb_queue_empty(&sk->sk_receive_queue)) break; sk_wait_data(sk, &timeo, NULL); if (signal_pending(current)) { ret = sock_intr_errno(timeo); break; } continue; } tss.len -= ret; spliced += ret; if (!timeo) break; release_sock(sk); lock_sock(sk); if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || signal_pending(current)) break; } release_sock(sk); if (spliced) return spliced; return ret; } EXPORT_SYMBOL(tcp_splice_read); struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp, bool force_schedule) { struct sk_buff *skb; /* The TCP header must be at least 32-bit aligned. */ size = ALIGN(size, 4); if (unlikely(tcp_under_memory_pressure(sk))) sk_mem_reclaim_partial(sk); skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp); if (likely(skb)) { bool mem_scheduled; if (force_schedule) { mem_scheduled = true; sk_forced_mem_schedule(sk, skb->truesize); } else { mem_scheduled = sk_wmem_schedule(sk, skb->truesize); } if (likely(mem_scheduled)) { skb_reserve(skb, sk->sk_prot->max_header); /* * Make sure that we have exactly size bytes * available to the caller, no more, no less. */ skb->reserved_tailroom = skb->end - skb->tail - size; return skb; } __kfree_skb(skb); } else { sk->sk_prot->enter_memory_pressure(sk); sk_stream_moderate_sndbuf(sk); } return NULL; } static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now, int large_allowed) { struct tcp_sock *tp = tcp_sk(sk); u32 new_size_goal, size_goal; if (!large_allowed || !sk_can_gso(sk)) return mss_now; /* Note : tcp_tso_autosize() will eventually split this later */ new_size_goal = sk->sk_gso_max_size - 1 - MAX_TCP_HEADER; new_size_goal = tcp_bound_to_half_wnd(tp, new_size_goal); /* We try hard to avoid divides here */ size_goal = tp->gso_segs * mss_now; if (unlikely(new_size_goal < size_goal || new_size_goal >= size_goal + mss_now)) { tp->gso_segs = min_t(u16, new_size_goal / mss_now, sk->sk_gso_max_segs); size_goal = tp->gso_segs * mss_now; } return max(size_goal, mss_now); } static int tcp_send_mss(struct sock *sk, int *size_goal, int flags) { int mss_now; mss_now = tcp_current_mss(sk); *size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB)); return mss_now; } static ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset, size_t size, int flags) { struct tcp_sock *tp = tcp_sk(sk); int mss_now, size_goal; int err; ssize_t copied; long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT); /* Wait for a connection to finish. One exception is TCP Fast Open * (passive side) where data is allowed to be sent before a connection * is fully established. */ if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) && !tcp_passive_fastopen(sk)) { err = sk_stream_wait_connect(sk, &timeo); if (err != 0) goto out_err; } sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); mss_now = tcp_send_mss(sk, &size_goal, flags); copied = 0; err = -EPIPE; if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) goto out_err; while (size > 0) { struct sk_buff *skb = tcp_write_queue_tail(sk); int copy, i; bool can_coalesce; if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0 || !tcp_skb_can_collapse_to(skb)) { new_segment: if (!sk_stream_memory_free(sk)) goto wait_for_sndbuf; skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation, skb_queue_empty(&sk->sk_write_queue)); if (!skb) goto wait_for_memory; skb_entail(sk, skb); copy = size_goal; } if (copy > size) copy = size; i = skb_shinfo(skb)->nr_frags; can_coalesce = skb_can_coalesce(skb, i, page, offset); if (!can_coalesce && i >= sysctl_max_skb_frags) { tcp_mark_push(tp, skb); goto new_segment; } if (!sk_wmem_schedule(sk, copy)) goto wait_for_memory; if (can_coalesce) { skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); } else { get_page(page); skb_fill_page_desc(skb, i, page, offset, copy); } skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG; skb->len += copy; skb->data_len += copy; skb->truesize += copy; sk->sk_wmem_queued += copy; sk_mem_charge(sk, copy); skb->ip_summed = CHECKSUM_PARTIAL; tp->write_seq += copy; TCP_SKB_CB(skb)->end_seq += copy; tcp_skb_pcount_set(skb, 0); if (!copied) TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH; copied += copy; offset += copy; size -= copy; if (!size) goto out; if (skb->len < size_goal || (flags & MSG_OOB)) continue; if (forced_push(tp)) { tcp_mark_push(tp, skb); __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH); } else if (skb == tcp_send_head(sk)) tcp_push_one(sk, mss_now); continue; wait_for_sndbuf: set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); wait_for_memory: tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH, size_goal); err = sk_stream_wait_memory(sk, &timeo); if (err != 0) goto do_error; mss_now = tcp_send_mss(sk, &size_goal, flags); } out: if (copied) { tcp_tx_timestamp(sk, sk->sk_tsflags, tcp_write_queue_tail(sk)); if (!(flags & MSG_SENDPAGE_NOTLAST)) tcp_push(sk, flags, mss_now, tp->nonagle, size_goal); } return copied; do_error: if (copied) goto out; out_err: /* make sure we wake any epoll edge trigger waiter */ if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 && err == -EAGAIN)) { sk->sk_write_space(sk); tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED); } return sk_stream_error(sk, flags, err); } int tcp_sendpage(struct sock *sk, struct page *page, int offset, size_t size, int flags) { ssize_t res; if (!(sk->sk_route_caps & NETIF_F_SG) || !sk_check_csum_caps(sk)) return sock_no_sendpage(sk->sk_socket, page, offset, size, flags); lock_sock(sk); tcp_rate_check_app_limited(sk); /* is sending application-limited? */ res = do_tcp_sendpages(sk, page, offset, size, flags); release_sock(sk); return res; } EXPORT_SYMBOL(tcp_sendpage); /* Do not bother using a page frag for very small frames. * But use this heuristic only for the first skb in write queue. * * Having no payload in skb->head allows better SACK shifting * in tcp_shift_skb_data(), reducing sack/rack overhead, because * write queue has less skbs. * Each skb can hold up to MAX_SKB_FRAGS * 32Kbytes, or ~0.5 MB. * This also speeds up tso_fragment(), since it wont fallback * to tcp_fragment(). */ static int linear_payload_sz(bool first_skb) { if (first_skb) return SKB_WITH_OVERHEAD(2048 - MAX_TCP_HEADER); return 0; } static int select_size(const struct sock *sk, bool sg, bool first_skb) { const struct tcp_sock *tp = tcp_sk(sk); int tmp = tp->mss_cache; if (sg) { if (sk_can_gso(sk)) { tmp = linear_payload_sz(first_skb); } else { int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER); if (tmp >= pgbreak && tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE) tmp = pgbreak; } } return tmp; } void tcp_free_fastopen_req(struct tcp_sock *tp) { if (tp->fastopen_req) { kfree(tp->fastopen_req); tp->fastopen_req = NULL; } } static int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, int *copied, size_t size) { struct tcp_sock *tp = tcp_sk(sk); struct inet_sock *inet = inet_sk(sk); int err, flags; if (!(sysctl_tcp_fastopen & TFO_CLIENT_ENABLE)) return -EOPNOTSUPP; if (tp->fastopen_req) return -EALREADY; /* Another Fast Open is in progress */ tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request), sk->sk_allocation); if (unlikely(!tp->fastopen_req)) return -ENOBUFS; tp->fastopen_req->data = msg; tp->fastopen_req->size = size; if (inet->defer_connect) { err = tcp_connect(sk); /* Same failure procedure as in tcp_v4/6_connect */ if (err) { tcp_set_state(sk, TCP_CLOSE); inet->inet_dport = 0; sk->sk_route_caps = 0; } } flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0; err = __inet_stream_connect(sk->sk_socket, msg->msg_name, msg->msg_namelen, flags, 1); /* fastopen_req could already be freed in __inet_stream_connect * if the connection times out or gets rst */ if (tp->fastopen_req) { *copied = tp->fastopen_req->copied; tcp_free_fastopen_req(tp); inet->defer_connect = 0; } return err; } int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; struct sockcm_cookie sockc; int flags, err, copied = 0; int mss_now = 0, size_goal, copied_syn = 0; bool process_backlog = false; bool sg; long timeo; lock_sock(sk); flags = msg->msg_flags; if (unlikely(flags & MSG_FASTOPEN || inet_sk(sk)->defer_connect)) { err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size); if (err == -EINPROGRESS && copied_syn > 0) goto out; else if (err) goto out_err; } timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT); tcp_rate_check_app_limited(sk); /* is sending application-limited? */ /* Wait for a connection to finish. One exception is TCP Fast Open * (passive side) where data is allowed to be sent before a connection * is fully established. */ if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) && !tcp_passive_fastopen(sk)) { err = sk_stream_wait_connect(sk, &timeo); if (err != 0) goto do_error; } if (unlikely(tp->repair)) { if (tp->repair_queue == TCP_RECV_QUEUE) { copied = tcp_send_rcvq(sk, msg, size); goto out_nopush; } err = -EINVAL; if (tp->repair_queue == TCP_NO_QUEUE) goto out_err; /* 'common' sending to sendq */ } sockc.tsflags = sk->sk_tsflags; if (msg->msg_controllen) { err = sock_cmsg_send(sk, msg, &sockc); if (unlikely(err)) { err = -EINVAL; goto out_err; } } /* This should be in poll */ sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); /* Ok commence sending. */ copied = 0; restart: mss_now = tcp_send_mss(sk, &size_goal, flags); err = -EPIPE; if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) goto do_error; sg = !!(sk->sk_route_caps & NETIF_F_SG); while (msg_data_left(msg)) { int copy = 0; int max = size_goal; skb = tcp_write_queue_tail(sk); if (tcp_send_head(sk)) { if (skb->ip_summed == CHECKSUM_NONE) max = mss_now; copy = max - skb->len; } if (copy <= 0 || !tcp_skb_can_collapse_to(skb)) { bool first_skb; new_segment: /* Allocate new segment. If the interface is SG, * allocate skb fitting to single page. */ if (!sk_stream_memory_free(sk)) goto wait_for_sndbuf; if (process_backlog && sk_flush_backlog(sk)) { process_backlog = false; goto restart; } first_skb = skb_queue_empty(&sk->sk_write_queue); skb = sk_stream_alloc_skb(sk, select_size(sk, sg, first_skb), sk->sk_allocation, first_skb); if (!skb) goto wait_for_memory; process_backlog = true; /* * Check whether we can use HW checksum. */ if (sk_check_csum_caps(sk)) skb->ip_summed = CHECKSUM_PARTIAL; skb_entail(sk, skb); copy = size_goal; max = size_goal; /* All packets are restored as if they have * already been sent. skb_mstamp isn't set to * avoid wrong rtt estimation. */ if (tp->repair) TCP_SKB_CB(skb)->sacked |= TCPCB_REPAIRED; } /* Try to append data to the end of skb. */ if (copy > msg_data_left(msg)) copy = msg_data_left(msg); /* Where to copy to? */ if (skb_availroom(skb) > 0) { /* We have some space in skb head. Superb! */ copy = min_t(int, copy, skb_availroom(skb)); err = skb_add_data_nocache(sk, skb, &msg->msg_iter, copy); if (err) goto do_fault; } else { bool merge = true; int i = skb_shinfo(skb)->nr_frags; struct page_frag *pfrag = sk_page_frag(sk); if (!sk_page_frag_refill(sk, pfrag)) goto wait_for_memory; if (!skb_can_coalesce(skb, i, pfrag->page, pfrag->offset)) { if (i >= sysctl_max_skb_frags || !sg) { tcp_mark_push(tp, skb); goto new_segment; } merge = false; } copy = min_t(int, copy, pfrag->size - pfrag->offset); if (!sk_wmem_schedule(sk, copy)) goto wait_for_memory; err = skb_copy_to_page_nocache(sk, &msg->msg_iter, skb, pfrag->page, pfrag->offset, copy); if (err) goto do_error; /* Update the skb. */ if (merge) { skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); } else { skb_fill_page_desc(skb, i, pfrag->page, pfrag->offset, copy); page_ref_inc(pfrag->page); } pfrag->offset += copy; } if (!copied) TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH; tp->write_seq += copy; TCP_SKB_CB(skb)->end_seq += copy; tcp_skb_pcount_set(skb, 0); copied += copy; if (!msg_data_left(msg)) { if (unlikely(flags & MSG_EOR)) TCP_SKB_CB(skb)->eor = 1; goto out; } if (skb->len < max || (flags & MSG_OOB) || unlikely(tp->repair)) continue; if (forced_push(tp)) { tcp_mark_push(tp, skb); __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH); } else if (skb == tcp_send_head(sk)) tcp_push_one(sk, mss_now); continue; wait_for_sndbuf: set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); wait_for_memory: if (copied) tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH, size_goal); err = sk_stream_wait_memory(sk, &timeo); if (err != 0) goto do_error; mss_now = tcp_send_mss(sk, &size_goal, flags); } out: if (copied) { tcp_tx_timestamp(sk, sockc.tsflags, tcp_write_queue_tail(sk)); tcp_push(sk, flags, mss_now, tp->nonagle, size_goal); } out_nopush: release_sock(sk); return copied + copied_syn; do_fault: if (!skb->len) { tcp_unlink_write_queue(skb, sk); /* It is the one place in all of TCP, except connection * reset, where we can be unlinking the send_head. */ tcp_check_send_head(sk, skb); sk_wmem_free_skb(sk, skb); } do_error: if (copied + copied_syn) goto out; out_err: err = sk_stream_error(sk, flags, err); /* make sure we wake any epoll edge trigger waiter */ if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 && err == -EAGAIN)) { sk->sk_write_space(sk); tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED); } release_sock(sk); return err; } EXPORT_SYMBOL(tcp_sendmsg); /* * Handle reading urgent data. BSD has very simple semantics for * this, no blocking and very strange errors 8) */ static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags) { struct tcp_sock *tp = tcp_sk(sk); /* No URG data to read. */ if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data || tp->urg_data == TCP_URG_READ) return -EINVAL; /* Yes this is right ! */ if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE)) return -ENOTCONN; if (tp->urg_data & TCP_URG_VALID) { int err = 0; char c = tp->urg_data; if (!(flags & MSG_PEEK)) tp->urg_data = TCP_URG_READ; /* Read urgent data. */ msg->msg_flags |= MSG_OOB; if (len > 0) { if (!(flags & MSG_TRUNC)) err = memcpy_to_msg(msg, &c, 1); len = 1; } else msg->msg_flags |= MSG_TRUNC; return err ? -EFAULT : len; } if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN)) return 0; /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and * the available implementations agree in this case: * this call should never block, independent of the * blocking state of the socket. * Mike <pall@rz.uni-karlsruhe.de> */ return -EAGAIN; } static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len) { struct sk_buff *skb; int copied = 0, err = 0; /* XXX -- need to support SO_PEEK_OFF */ skb_queue_walk(&sk->sk_write_queue, skb) { err = skb_copy_datagram_msg(skb, 0, msg, skb->len); if (err) break; copied += skb->len; } return err ?: copied; } /* Clean up the receive buffer for full frames taken by the user, * then send an ACK if necessary. COPIED is the number of bytes * tcp_recvmsg has given to the user so far, it speeds up the * calculation of whether or not we must ACK for the sake of * a window update. */ static void tcp_cleanup_rbuf(struct sock *sk, int copied) { struct tcp_sock *tp = tcp_sk(sk); bool time_to_ack = false; struct sk_buff *skb = skb_peek(&sk->sk_receive_queue); WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq), "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n", tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt); if (inet_csk_ack_scheduled(sk)) { const struct inet_connection_sock *icsk = inet_csk(sk); /* Delayed ACKs frequently hit locked sockets during bulk * receive. */ if (icsk->icsk_ack.blocked || /* Once-per-two-segments ACK was not sent by tcp_input.c */ tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss || /* * If this read emptied read buffer, we send ACK, if * connection is not bidirectional, user drained * receive buffer and there was a small segment * in queue. */ (copied > 0 && ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) || ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) && !icsk->icsk_ack.pingpong)) && !atomic_read(&sk->sk_rmem_alloc))) time_to_ack = true; } /* We send an ACK if we can now advertise a non-zero window * which has been raised "significantly". * * Even if window raised up to infinity, do not send window open ACK * in states, where we will not receive more. It is useless. */ if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) { __u32 rcv_window_now = tcp_receive_window(tp); /* Optimize, __tcp_select_window() is not cheap. */ if (2*rcv_window_now <= tp->window_clamp) { __u32 new_window = __tcp_select_window(sk); /* Send ACK now, if this read freed lots of space * in our buffer. Certainly, new_window is new window. * We can advertise it now, if it is not less than current one. * "Lots" means "at least twice" here. */ if (new_window && new_window >= 2 * rcv_window_now) time_to_ack = true; } } if (time_to_ack) tcp_send_ack(sk); } static void tcp_prequeue_process(struct sock *sk) { struct sk_buff *skb; struct tcp_sock *tp = tcp_sk(sk); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPREQUEUED); while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL) sk_backlog_rcv(sk, skb); /* Clear memory counter. */ tp->ucopy.memory = 0; } static struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off) { struct sk_buff *skb; u32 offset; while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) { offset = seq - TCP_SKB_CB(skb)->seq; if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) { pr_err_once("%s: found a SYN, please report !\n", __func__); offset--; } if (offset < skb->len || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN)) { *off = offset; return skb; } /* This looks weird, but this can happen if TCP collapsing * splitted a fat GRO packet, while we released socket lock * in skb_splice_bits() */ sk_eat_skb(sk, skb); } return NULL; } /* * This routine provides an alternative to tcp_recvmsg() for routines * that would like to handle copying from skbuffs directly in 'sendfile' * fashion. * Note: * - It is assumed that the socket was locked by the caller. * - The routine does not block. * - At present, there is no support for reading OOB data * or for 'peeking' the socket using this routine * (although both would be easy to implement). */ int tcp_read_sock(struct sock *sk, read_descriptor_t *desc, sk_read_actor_t recv_actor) { struct sk_buff *skb; struct tcp_sock *tp = tcp_sk(sk); u32 seq = tp->copied_seq; u32 offset; int copied = 0; if (sk->sk_state == TCP_LISTEN) return -ENOTCONN; while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) { if (offset < skb->len) { int used; size_t len; len = skb->len - offset; /* Stop reading if we hit a patch of urgent data */ if (tp->urg_data) { u32 urg_offset = tp->urg_seq - seq; if (urg_offset < len) len = urg_offset; if (!len) break; } used = recv_actor(desc, skb, offset, len); if (used <= 0) { if (!copied) copied = used; break; } else if (used <= len) { seq += used; copied += used; offset += used; } /* If recv_actor drops the lock (e.g. TCP splice * receive) the skb pointer might be invalid when * getting here: tcp_collapse might have deleted it * while aggregating skbs from the socket queue. */ skb = tcp_recv_skb(sk, seq - 1, &offset); if (!skb) break; /* TCP coalescing might have appended data to the skb. * Try to splice more frags */ if (offset + 1 != skb->len) continue; } if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) { sk_eat_skb(sk, skb); ++seq; break; } sk_eat_skb(sk, skb); if (!desc->count) break; tp->copied_seq = seq; } tp->copied_seq = seq; tcp_rcv_space_adjust(sk); /* Clean up data we have read: This will do ACK frames. */ if (copied > 0) { tcp_recv_skb(sk, seq, &offset); tcp_cleanup_rbuf(sk, copied); } return copied; } EXPORT_SYMBOL(tcp_read_sock); int tcp_peek_len(struct socket *sock) { return tcp_inq(sock->sk); } EXPORT_SYMBOL(tcp_peek_len); /* * This routine copies from a sock struct into the user buffer. * * Technical note: in 2.3 we work on _locked_ socket, so that * tricks with *seq access order and skb->users are not required. * Probably, code can be easily improved even more. */ int tcp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int nonblock, int flags, int *addr_len) { struct tcp_sock *tp = tcp_sk(sk); int copied = 0; u32 peek_seq; u32 *seq; unsigned long used; int err; int target; /* Read at least this many bytes */ long timeo; struct task_struct *user_recv = NULL; struct sk_buff *skb, *last; u32 urg_hole = 0; if (unlikely(flags & MSG_ERRQUEUE)) return inet_recv_error(sk, msg, len, addr_len); if (sk_can_busy_loop(sk) && skb_queue_empty(&sk->sk_receive_queue) && (sk->sk_state == TCP_ESTABLISHED)) sk_busy_loop(sk, nonblock); lock_sock(sk); err = -ENOTCONN; if (sk->sk_state == TCP_LISTEN) goto out; timeo = sock_rcvtimeo(sk, nonblock); /* Urgent data needs to be handled specially. */ if (flags & MSG_OOB) goto recv_urg; if (unlikely(tp->repair)) { err = -EPERM; if (!(flags & MSG_PEEK)) goto out; if (tp->repair_queue == TCP_SEND_QUEUE) goto recv_sndq; err = -EINVAL; if (tp->repair_queue == TCP_NO_QUEUE) goto out; /* 'common' recv queue MSG_PEEK-ing */ } seq = &tp->copied_seq; if (flags & MSG_PEEK) { peek_seq = tp->copied_seq; seq = &peek_seq; } target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); do { u32 offset; /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */ if (tp->urg_data && tp->urg_seq == *seq) { if (copied) break; if (signal_pending(current)) { copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; break; } } /* Next get a buffer. */ last = skb_peek_tail(&sk->sk_receive_queue); skb_queue_walk(&sk->sk_receive_queue, skb) { last = skb; /* Now that we have two receive queues this * shouldn't happen. */ if (WARN(before(*seq, TCP_SKB_CB(skb)->seq), "recvmsg bug: copied %X seq %X rcvnxt %X fl %X\n", *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags)) break; offset = *seq - TCP_SKB_CB(skb)->seq; if (unlikely(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) { pr_err_once("%s: found a SYN, please report !\n", __func__); offset--; } if (offset < skb->len) goto found_ok_skb; if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) goto found_fin_ok; WARN(!(flags & MSG_PEEK), "recvmsg bug 2: copied %X seq %X rcvnxt %X fl %X\n", *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags); } /* Well, if we have backlog, try to process it now yet. */ if (copied >= target && !sk->sk_backlog.tail) break; if (copied) { if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || !timeo || signal_pending(current)) break; } else { if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { copied = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_state == TCP_CLOSE) { if (!sock_flag(sk, SOCK_DONE)) { /* This occurs when user tries to read * from never connected socket. */ copied = -ENOTCONN; break; } break; } if (!timeo) { copied = -EAGAIN; break; } if (signal_pending(current)) { copied = sock_intr_errno(timeo); break; } } tcp_cleanup_rbuf(sk, copied); if (!sysctl_tcp_low_latency && tp->ucopy.task == user_recv) { /* Install new reader */ if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) { user_recv = current; tp->ucopy.task = user_recv; tp->ucopy.msg = msg; } tp->ucopy.len = len; WARN_ON(tp->copied_seq != tp->rcv_nxt && !(flags & (MSG_PEEK | MSG_TRUNC))); /* Ugly... If prequeue is not empty, we have to * process it before releasing socket, otherwise * order will be broken at second iteration. * More elegant solution is required!!! * * Look: we have the following (pseudo)queues: * * 1. packets in flight * 2. backlog * 3. prequeue * 4. receive_queue * * Each queue can be processed only if the next ones * are empty. At this point we have empty receive_queue. * But prequeue _can_ be not empty after 2nd iteration, * when we jumped to start of loop because backlog * processing added something to receive_queue. * We cannot release_sock(), because backlog contains * packets arrived _after_ prequeued ones. * * Shortly, algorithm is clear --- to process all * the queues in order. We could make it more directly, * requeueing packets from backlog to prequeue, if * is not empty. It is more elegant, but eats cycles, * unfortunately. */ if (!skb_queue_empty(&tp->ucopy.prequeue)) goto do_prequeue; /* __ Set realtime policy in scheduler __ */ } if (copied >= target) { /* Do not sleep, just process backlog. */ release_sock(sk); lock_sock(sk); } else { sk_wait_data(sk, &timeo, last); } if (user_recv) { int chunk; /* __ Restore normal policy in scheduler __ */ chunk = len - tp->ucopy.len; if (chunk != 0) { NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk); len -= chunk; copied += chunk; } if (tp->rcv_nxt == tp->copied_seq && !skb_queue_empty(&tp->ucopy.prequeue)) { do_prequeue: tcp_prequeue_process(sk); chunk = len - tp->ucopy.len; if (chunk != 0) { NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk); len -= chunk; copied += chunk; } } } if ((flags & MSG_PEEK) && (peek_seq - copied - urg_hole != tp->copied_seq)) { net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n", current->comm, task_pid_nr(current)); peek_seq = tp->copied_seq; } continue; found_ok_skb: /* Ok so how much can we use? */ used = skb->len - offset; if (len < used) used = len; /* Do we have urgent data here? */ if (tp->urg_data) { u32 urg_offset = tp->urg_seq - *seq; if (urg_offset < used) { if (!urg_offset) { if (!sock_flag(sk, SOCK_URGINLINE)) { ++*seq; urg_hole++; offset++; used--; if (!used) goto skip_copy; } } else used = urg_offset; } } if (!(flags & MSG_TRUNC)) { err = skb_copy_datagram_msg(skb, offset, msg, used); if (err) { /* Exception. Bailout! */ if (!copied) copied = -EFAULT; break; } } *seq += used; copied += used; len -= used; tcp_rcv_space_adjust(sk); skip_copy: if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) { tp->urg_data = 0; tcp_fast_path_check(sk); } if (used + offset < skb->len) continue; if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) goto found_fin_ok; if (!(flags & MSG_PEEK)) sk_eat_skb(sk, skb); continue; found_fin_ok: /* Process the FIN. */ ++*seq; if (!(flags & MSG_PEEK)) sk_eat_skb(sk, skb); break; } while (len > 0); if (user_recv) { if (!skb_queue_empty(&tp->ucopy.prequeue)) { int chunk; tp->ucopy.len = copied > 0 ? len : 0; tcp_prequeue_process(sk); if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) { NET_ADD_STATS(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk); len -= chunk; copied += chunk; } } tp->ucopy.task = NULL; tp->ucopy.len = 0; } /* According to UNIX98, msg_name/msg_namelen are ignored * on connected socket. I was just happy when found this 8) --ANK */ /* Clean up data we have read: This will do ACK frames. */ tcp_cleanup_rbuf(sk, copied); release_sock(sk); return copied; out: release_sock(sk); return err; recv_urg: err = tcp_recv_urg(sk, msg, len, flags); goto out; recv_sndq: err = tcp_peek_sndq(sk, msg, len); goto out; } EXPORT_SYMBOL(tcp_recvmsg); void tcp_set_state(struct sock *sk, int state) { int oldstate = sk->sk_state; switch (state) { case TCP_ESTABLISHED: if (oldstate != TCP_ESTABLISHED) TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB); break; case TCP_CLOSE: if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED) TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS); sk->sk_prot->unhash(sk); if (inet_csk(sk)->icsk_bind_hash && !(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) inet_put_port(sk); /* fall through */ default: if (oldstate == TCP_ESTABLISHED) TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB); } /* Change state AFTER socket is unhashed to avoid closed * socket sitting in hash tables. */ sk_state_store(sk, state); #ifdef STATE_TRACE SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n", sk, statename[oldstate], statename[state]); #endif } EXPORT_SYMBOL_GPL(tcp_set_state); /* * State processing on a close. This implements the state shift for * sending our FIN frame. Note that we only send a FIN for some * states. A shutdown() may have already sent the FIN, or we may be * closed. */ static const unsigned char new_state[16] = { /* current state: new state: action: */ [0 /* (Invalid) */] = TCP_CLOSE, [TCP_ESTABLISHED] = TCP_FIN_WAIT1 | TCP_ACTION_FIN, [TCP_SYN_SENT] = TCP_CLOSE, [TCP_SYN_RECV] = TCP_FIN_WAIT1 | TCP_ACTION_FIN, [TCP_FIN_WAIT1] = TCP_FIN_WAIT1, [TCP_FIN_WAIT2] = TCP_FIN_WAIT2, [TCP_TIME_WAIT] = TCP_CLOSE, [TCP_CLOSE] = TCP_CLOSE, [TCP_CLOSE_WAIT] = TCP_LAST_ACK | TCP_ACTION_FIN, [TCP_LAST_ACK] = TCP_LAST_ACK, [TCP_LISTEN] = TCP_CLOSE, [TCP_CLOSING] = TCP_CLOSING, [TCP_NEW_SYN_RECV] = TCP_CLOSE, /* should not happen ! */ }; static int tcp_close_state(struct sock *sk) { int next = (int)new_state[sk->sk_state]; int ns = next & TCP_STATE_MASK; tcp_set_state(sk, ns); return next & TCP_ACTION_FIN; } /* * Shutdown the sending side of a connection. Much like close except * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD). */ void tcp_shutdown(struct sock *sk, int how) { /* We need to grab some memory, and put together a FIN, * and then put it into the queue to be sent. * Tim MacKenzie(tym@dibbler.cs.monash.edu.au) 4 Dec '92. */ if (!(how & SEND_SHUTDOWN)) return; /* If we've already sent a FIN, or it's a closed state, skip this. */ if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) { /* Clear out any half completed packets. FIN if needed. */ if (tcp_close_state(sk)) tcp_send_fin(sk); } } EXPORT_SYMBOL(tcp_shutdown); bool tcp_check_oom(struct sock *sk, int shift) { bool too_many_orphans, out_of_socket_memory; too_many_orphans = tcp_too_many_orphans(sk, shift); out_of_socket_memory = tcp_out_of_memory(sk); if (too_many_orphans) net_info_ratelimited("too many orphaned sockets\n"); if (out_of_socket_memory) net_info_ratelimited("out of memory -- consider tuning tcp_mem\n"); return too_many_orphans || out_of_socket_memory; } void tcp_close(struct sock *sk, long timeout) { struct sk_buff *skb; int data_was_unread = 0; int state; lock_sock(sk); sk->sk_shutdown = SHUTDOWN_MASK; if (sk->sk_state == TCP_LISTEN) { tcp_set_state(sk, TCP_CLOSE); /* Special case. */ inet_csk_listen_stop(sk); goto adjudge_to_death; } /* We need to flush the recv. buffs. We do this only on the * descriptor close, not protocol-sourced closes, because the * reader process may not have drained the data yet! */ while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) { u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq; if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) len--; data_was_unread += len; __kfree_skb(skb); } sk_mem_reclaim(sk); /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */ if (sk->sk_state == TCP_CLOSE) goto adjudge_to_death; /* As outlined in RFC 2525, section 2.17, we send a RST here because * data was lost. To witness the awful effects of the old behavior of * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk * GET in an FTP client, suspend the process, wait for the client to * advertise a zero window, then kill -9 the FTP client, wheee... * Note: timeout is always zero in such a case. */ if (unlikely(tcp_sk(sk)->repair)) { sk->sk_prot->disconnect(sk, 0); } else if (data_was_unread) { /* Unread data was tossed, zap the connection. */ NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE); tcp_set_state(sk, TCP_CLOSE); tcp_send_active_reset(sk, sk->sk_allocation); } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) { /* Check zero linger _after_ checking for unread data. */ sk->sk_prot->disconnect(sk, 0); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA); } else if (tcp_close_state(sk)) { /* We FIN if the application ate all the data before * zapping the connection. */ /* RED-PEN. Formally speaking, we have broken TCP state * machine. State transitions: * * TCP_ESTABLISHED -> TCP_FIN_WAIT1 * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible) * TCP_CLOSE_WAIT -> TCP_LAST_ACK * * are legal only when FIN has been sent (i.e. in window), * rather than queued out of window. Purists blame. * * F.e. "RFC state" is ESTABLISHED, * if Linux state is FIN-WAIT-1, but FIN is still not sent. * * The visible declinations are that sometimes * we enter time-wait state, when it is not required really * (harmless), do not send active resets, when they are * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when * they look as CLOSING or LAST_ACK for Linux) * Probably, I missed some more holelets. * --ANK * XXX (TFO) - To start off we don't support SYN+ACK+FIN * in a single packet! (May consider it later but will * probably need API support or TCP_CORK SYN-ACK until * data is written and socket is closed.) */ tcp_send_fin(sk); } sk_stream_wait_close(sk, timeout); adjudge_to_death: state = sk->sk_state; sock_hold(sk); sock_orphan(sk); /* It is the last release_sock in its life. It will remove backlog. */ release_sock(sk); /* Now socket is owned by kernel and we acquire BH lock to finish close. No need to check for user refs. */ local_bh_disable(); bh_lock_sock(sk); WARN_ON(sock_owned_by_user(sk)); percpu_counter_inc(sk->sk_prot->orphan_count); /* Have we already been destroyed by a softirq or backlog? */ if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE) goto out; /* This is a (useful) BSD violating of the RFC. There is a * problem with TCP as specified in that the other end could * keep a socket open forever with no application left this end. * We use a 1 minute timeout (about the same as BSD) then kill * our end. If they send after that then tough - BUT: long enough * that we won't make the old 4*rto = almost no time - whoops * reset mistake. * * Nope, it was not mistake. It is really desired behaviour * f.e. on http servers, when such sockets are useless, but * consume significant resources. Let's do it with special * linger2 option. --ANK */ if (sk->sk_state == TCP_FIN_WAIT2) { struct tcp_sock *tp = tcp_sk(sk); if (tp->linger2 < 0) { tcp_set_state(sk, TCP_CLOSE); tcp_send_active_reset(sk, GFP_ATOMIC); __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONLINGER); } else { const int tmo = tcp_fin_time(sk); if (tmo > TCP_TIMEWAIT_LEN) { inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN); } else { tcp_time_wait(sk, TCP_FIN_WAIT2, tmo); goto out; } } } if (sk->sk_state != TCP_CLOSE) { sk_mem_reclaim(sk); if (tcp_check_oom(sk, 0)) { tcp_set_state(sk, TCP_CLOSE); tcp_send_active_reset(sk, GFP_ATOMIC); __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONMEMORY); } } if (sk->sk_state == TCP_CLOSE) { struct request_sock *req = tcp_sk(sk)->fastopen_rsk; /* We could get here with a non-NULL req if the socket is * aborted (e.g., closed with unread data) before 3WHS * finishes. */ if (req) reqsk_fastopen_remove(sk, req, false); inet_csk_destroy_sock(sk); } /* Otherwise, socket is reprieved until protocol close. */ out: bh_unlock_sock(sk); local_bh_enable(); sock_put(sk); } EXPORT_SYMBOL(tcp_close); /* These states need RST on ABORT according to RFC793 */ static inline bool tcp_need_reset(int state) { return (1 << state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 | TCPF_FIN_WAIT2 | TCPF_SYN_RECV); } int tcp_disconnect(struct sock *sk, int flags) { struct inet_sock *inet = inet_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int err = 0; int old_state = sk->sk_state; if (old_state != TCP_CLOSE) tcp_set_state(sk, TCP_CLOSE); /* ABORT function of RFC793 */ if (old_state == TCP_LISTEN) { inet_csk_listen_stop(sk); } else if (unlikely(tp->repair)) { sk->sk_err = ECONNABORTED; } else if (tcp_need_reset(old_state) || (tp->snd_nxt != tp->write_seq && (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) { /* The last check adjusts for discrepancy of Linux wrt. RFC * states */ tcp_send_active_reset(sk, gfp_any()); sk->sk_err = ECONNRESET; } else if (old_state == TCP_SYN_SENT) sk->sk_err = ECONNRESET; tcp_clear_xmit_timers(sk); __skb_queue_purge(&sk->sk_receive_queue); tcp_write_queue_purge(sk); tcp_fastopen_active_disable_ofo_check(sk); skb_rbtree_purge(&tp->out_of_order_queue); inet->inet_dport = 0; if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) inet_reset_saddr(sk); sk->sk_shutdown = 0; sock_reset_flag(sk, SOCK_DONE); tp->srtt_us = 0; tp->write_seq += tp->max_window + 2; if (tp->write_seq == 0) tp->write_seq = 1; icsk->icsk_backoff = 0; tp->snd_cwnd = 2; icsk->icsk_probes_out = 0; tp->packets_out = 0; tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; tp->snd_cwnd_cnt = 0; tp->window_clamp = 0; tcp_set_ca_state(sk, TCP_CA_Open); tcp_clear_retrans(tp); inet_csk_delack_init(sk); /* Initialize rcv_mss to TCP_MIN_MSS to avoid division by 0 * issue in __tcp_select_window() */ icsk->icsk_ack.rcv_mss = TCP_MIN_MSS; tcp_init_send_head(sk); memset(&tp->rx_opt, 0, sizeof(tp->rx_opt)); __sk_dst_reset(sk); tcp_saved_syn_free(tp); /* Clean up fastopen related fields */ tcp_free_fastopen_req(tp); inet->defer_connect = 0; WARN_ON(inet->inet_num && !icsk->icsk_bind_hash); sk->sk_error_report(sk); return err; } EXPORT_SYMBOL(tcp_disconnect); static inline bool tcp_can_repair_sock(const struct sock *sk) { return ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) && (sk->sk_state != TCP_LISTEN); } static int tcp_repair_set_window(struct tcp_sock *tp, char __user *optbuf, int len) { struct tcp_repair_window opt; if (!tp->repair) return -EPERM; if (len != sizeof(opt)) return -EINVAL; if (copy_from_user(&opt, optbuf, sizeof(opt))) return -EFAULT; if (opt.max_window < opt.snd_wnd) return -EINVAL; if (after(opt.snd_wl1, tp->rcv_nxt + opt.rcv_wnd)) return -EINVAL; if (after(opt.rcv_wup, tp->rcv_nxt)) return -EINVAL; tp->snd_wl1 = opt.snd_wl1; tp->snd_wnd = opt.snd_wnd; tp->max_window = opt.max_window; tp->rcv_wnd = opt.rcv_wnd; tp->rcv_wup = opt.rcv_wup; return 0; } static int tcp_repair_options_est(struct tcp_sock *tp, struct tcp_repair_opt __user *optbuf, unsigned int len) { struct tcp_repair_opt opt; while (len >= sizeof(opt)) { if (copy_from_user(&opt, optbuf, sizeof(opt))) return -EFAULT; optbuf++; len -= sizeof(opt); switch (opt.opt_code) { case TCPOPT_MSS: tp->rx_opt.mss_clamp = opt.opt_val; break; case TCPOPT_WINDOW: { u16 snd_wscale = opt.opt_val & 0xFFFF; u16 rcv_wscale = opt.opt_val >> 16; if (snd_wscale > TCP_MAX_WSCALE || rcv_wscale > TCP_MAX_WSCALE) return -EFBIG; tp->rx_opt.snd_wscale = snd_wscale; tp->rx_opt.rcv_wscale = rcv_wscale; tp->rx_opt.wscale_ok = 1; } break; case TCPOPT_SACK_PERM: if (opt.opt_val != 0) return -EINVAL; tp->rx_opt.sack_ok |= TCP_SACK_SEEN; if (sysctl_tcp_fack) tcp_enable_fack(tp); break; case TCPOPT_TIMESTAMP: if (opt.opt_val != 0) return -EINVAL; tp->rx_opt.tstamp_ok = 1; break; } } return 0; } /* * Socket option code for TCP. */ static int do_tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); struct net *net = sock_net(sk); int val; int err = 0; /* These are data/string values, all the others are ints */ switch (optname) { case TCP_CONGESTION: { char name[TCP_CA_NAME_MAX]; if (optlen < 1) return -EINVAL; val = strncpy_from_user(name, optval, min_t(long, TCP_CA_NAME_MAX-1, optlen)); if (val < 0) return -EFAULT; name[val] = 0; lock_sock(sk); err = tcp_set_congestion_control(sk, name); release_sock(sk); return err; } default: /* fallthru */ break; } if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; lock_sock(sk); switch (optname) { case TCP_MAXSEG: /* Values greater than interface MTU won't take effect. However * at the point when this call is done we typically don't yet * know which interface is going to be used */ if (val && (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW)) { err = -EINVAL; break; } tp->rx_opt.user_mss = val; break; case TCP_NODELAY: if (val) { /* TCP_NODELAY is weaker than TCP_CORK, so that * this option on corked socket is remembered, but * it is not activated until cork is cleared. * * However, when TCP_NODELAY is set we make * an explicit push, which overrides even TCP_CORK * for currently queued segments. */ tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH; tcp_push_pending_frames(sk); } else { tp->nonagle &= ~TCP_NAGLE_OFF; } break; case TCP_THIN_LINEAR_TIMEOUTS: if (val < 0 || val > 1) err = -EINVAL; else tp->thin_lto = val; break; case TCP_THIN_DUPACK: if (val < 0 || val > 1) err = -EINVAL; break; case TCP_REPAIR: if (!tcp_can_repair_sock(sk)) err = -EPERM; else if (val == 1) { tp->repair = 1; sk->sk_reuse = SK_FORCE_REUSE; tp->repair_queue = TCP_NO_QUEUE; } else if (val == 0) { tp->repair = 0; sk->sk_reuse = SK_NO_REUSE; tcp_send_window_probe(sk); } else err = -EINVAL; break; case TCP_REPAIR_QUEUE: if (!tp->repair) err = -EPERM; else if (val < TCP_QUEUES_NR) tp->repair_queue = val; else err = -EINVAL; break; case TCP_QUEUE_SEQ: if (sk->sk_state != TCP_CLOSE) err = -EPERM; else if (tp->repair_queue == TCP_SEND_QUEUE) tp->write_seq = val; else if (tp->repair_queue == TCP_RECV_QUEUE) tp->rcv_nxt = val; else err = -EINVAL; break; case TCP_REPAIR_OPTIONS: if (!tp->repair) err = -EINVAL; else if (sk->sk_state == TCP_ESTABLISHED) err = tcp_repair_options_est(tp, (struct tcp_repair_opt __user *)optval, optlen); else err = -EPERM; break; case TCP_CORK: /* When set indicates to always queue non-full frames. * Later the user clears this option and we transmit * any pending partial frames in the queue. This is * meant to be used alongside sendfile() to get properly * filled frames when the user (for example) must write * out headers with a write() call first and then use * sendfile to send out the data parts. * * TCP_CORK can be set together with TCP_NODELAY and it is * stronger than TCP_NODELAY. */ if (val) { tp->nonagle |= TCP_NAGLE_CORK; } else { tp->nonagle &= ~TCP_NAGLE_CORK; if (tp->nonagle&TCP_NAGLE_OFF) tp->nonagle |= TCP_NAGLE_PUSH; tcp_push_pending_frames(sk); } break; case TCP_KEEPIDLE: if (val < 1 || val > MAX_TCP_KEEPIDLE) err = -EINVAL; else { tp->keepalive_time = val * HZ; if (sock_flag(sk, SOCK_KEEPOPEN) && !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { u32 elapsed = keepalive_time_elapsed(tp); if (tp->keepalive_time > elapsed) elapsed = tp->keepalive_time - elapsed; else elapsed = 0; inet_csk_reset_keepalive_timer(sk, elapsed); } } break; case TCP_KEEPINTVL: if (val < 1 || val > MAX_TCP_KEEPINTVL) err = -EINVAL; else tp->keepalive_intvl = val * HZ; break; case TCP_KEEPCNT: if (val < 1 || val > MAX_TCP_KEEPCNT) err = -EINVAL; else tp->keepalive_probes = val; break; case TCP_SYNCNT: if (val < 1 || val > MAX_TCP_SYNCNT) err = -EINVAL; else icsk->icsk_syn_retries = val; break; case TCP_SAVE_SYN: if (val < 0 || val > 1) err = -EINVAL; else tp->save_syn = val; break; case TCP_LINGER2: if (val < 0) tp->linger2 = -1; else if (val > net->ipv4.sysctl_tcp_fin_timeout / HZ) tp->linger2 = 0; else tp->linger2 = val * HZ; break; case TCP_DEFER_ACCEPT: /* Translate value in seconds to number of retransmits */ icsk->icsk_accept_queue.rskq_defer_accept = secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ); break; case TCP_WINDOW_CLAMP: if (!val) { if (sk->sk_state != TCP_CLOSE) { err = -EINVAL; break; } tp->window_clamp = 0; } else tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ? SOCK_MIN_RCVBUF / 2 : val; break; case TCP_QUICKACK: if (!val) { icsk->icsk_ack.pingpong = 1; } else { icsk->icsk_ack.pingpong = 0; if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) && inet_csk_ack_scheduled(sk)) { icsk->icsk_ack.pending |= ICSK_ACK_PUSHED; tcp_cleanup_rbuf(sk, 1); if (!(val & 1)) icsk->icsk_ack.pingpong = 1; } } break; #ifdef CONFIG_TCP_MD5SIG case TCP_MD5SIG: /* Read the IP->Key mappings from userspace */ err = tp->af_specific->md5_parse(sk, optval, optlen); break; #endif case TCP_USER_TIMEOUT: /* Cap the max time in ms TCP will retry or probe the window * before giving up and aborting (ETIMEDOUT) a connection. */ if (val < 0) err = -EINVAL; else icsk->icsk_user_timeout = msecs_to_jiffies(val); break; case TCP_FASTOPEN: if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { tcp_fastopen_init_key_once(true); fastopen_queue_tune(sk, val); } else { err = -EINVAL; } break; case TCP_FASTOPEN_CONNECT: if (val > 1 || val < 0) { err = -EINVAL; } else if (sysctl_tcp_fastopen & TFO_CLIENT_ENABLE) { if (sk->sk_state == TCP_CLOSE) tp->fastopen_connect = val; else err = -EINVAL; } else { err = -EOPNOTSUPP; } break; case TCP_TIMESTAMP: if (!tp->repair) err = -EPERM; else tp->tsoffset = val - tcp_time_stamp; break; case TCP_REPAIR_WINDOW: err = tcp_repair_set_window(tp, optval, optlen); break; case TCP_NOTSENT_LOWAT: tp->notsent_lowat = val; sk->sk_write_space(sk); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { const struct inet_connection_sock *icsk = inet_csk(sk); if (level != SOL_TCP) return icsk->icsk_af_ops->setsockopt(sk, level, optname, optval, optlen); return do_tcp_setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(tcp_setsockopt); #ifdef CONFIG_COMPAT int compat_tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level != SOL_TCP) return inet_csk_compat_setsockopt(sk, level, optname, optval, optlen); return do_tcp_setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_tcp_setsockopt); #endif static void tcp_get_info_chrono_stats(const struct tcp_sock *tp, struct tcp_info *info) { u64 stats[__TCP_CHRONO_MAX], total = 0; enum tcp_chrono i; for (i = TCP_CHRONO_BUSY; i < __TCP_CHRONO_MAX; ++i) { stats[i] = tp->chrono_stat[i - 1]; if (i == tp->chrono_type) stats[i] += tcp_time_stamp - tp->chrono_start; stats[i] *= USEC_PER_SEC / HZ; total += stats[i]; } info->tcpi_busy_time = total; info->tcpi_rwnd_limited = stats[TCP_CHRONO_RWND_LIMITED]; info->tcpi_sndbuf_limited = stats[TCP_CHRONO_SNDBUF_LIMITED]; } /* Return information about state of tcp endpoint in API format. */ void tcp_get_info(struct sock *sk, struct tcp_info *info) { const struct tcp_sock *tp = tcp_sk(sk); /* iff sk_type == SOCK_STREAM */ const struct inet_connection_sock *icsk = inet_csk(sk); u32 now, intv; u64 rate64; bool slow; u32 rate; memset(info, 0, sizeof(*info)); if (sk->sk_type != SOCK_STREAM) return; info->tcpi_state = sk_state_load(sk); /* Report meaningful fields for all TCP states, including listeners */ rate = READ_ONCE(sk->sk_pacing_rate); rate64 = rate != ~0U ? rate : ~0ULL; info->tcpi_pacing_rate = rate64; rate = READ_ONCE(sk->sk_max_pacing_rate); rate64 = rate != ~0U ? rate : ~0ULL; info->tcpi_max_pacing_rate = rate64; info->tcpi_reordering = tp->reordering; info->tcpi_snd_cwnd = tp->snd_cwnd; if (info->tcpi_state == TCP_LISTEN) { /* listeners aliased fields : * tcpi_unacked -> Number of children ready for accept() * tcpi_sacked -> max backlog */ info->tcpi_unacked = sk->sk_ack_backlog; info->tcpi_sacked = sk->sk_max_ack_backlog; return; } slow = lock_sock_fast(sk); info->tcpi_ca_state = icsk->icsk_ca_state; info->tcpi_retransmits = icsk->icsk_retransmits; info->tcpi_probes = icsk->icsk_probes_out; info->tcpi_backoff = icsk->icsk_backoff; if (tp->rx_opt.tstamp_ok) info->tcpi_options |= TCPI_OPT_TIMESTAMPS; if (tcp_is_sack(tp)) info->tcpi_options |= TCPI_OPT_SACK; if (tp->rx_opt.wscale_ok) { info->tcpi_options |= TCPI_OPT_WSCALE; info->tcpi_snd_wscale = tp->rx_opt.snd_wscale; info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale; } if (tp->ecn_flags & TCP_ECN_OK) info->tcpi_options |= TCPI_OPT_ECN; if (tp->ecn_flags & TCP_ECN_SEEN) info->tcpi_options |= TCPI_OPT_ECN_SEEN; if (tp->syn_data_acked) info->tcpi_options |= TCPI_OPT_SYN_DATA; info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto); info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato); info->tcpi_snd_mss = tp->mss_cache; info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss; info->tcpi_unacked = tp->packets_out; info->tcpi_sacked = tp->sacked_out; info->tcpi_lost = tp->lost_out; info->tcpi_retrans = tp->retrans_out; info->tcpi_fackets = tp->fackets_out; now = tcp_time_stamp; info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime); info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime); info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp); info->tcpi_pmtu = icsk->icsk_pmtu_cookie; info->tcpi_rcv_ssthresh = tp->rcv_ssthresh; info->tcpi_rtt = tp->srtt_us >> 3; info->tcpi_rttvar = tp->mdev_us >> 2; info->tcpi_snd_ssthresh = tp->snd_ssthresh; info->tcpi_advmss = tp->advmss; info->tcpi_rcv_rtt = tp->rcv_rtt_est.rtt_us >> 3; info->tcpi_rcv_space = tp->rcvq_space.space; info->tcpi_total_retrans = tp->total_retrans; info->tcpi_bytes_acked = tp->bytes_acked; info->tcpi_bytes_received = tp->bytes_received; info->tcpi_notsent_bytes = max_t(int, 0, tp->write_seq - tp->snd_nxt); tcp_get_info_chrono_stats(tp, info); info->tcpi_segs_out = tp->segs_out; info->tcpi_segs_in = tp->segs_in; info->tcpi_min_rtt = tcp_min_rtt(tp); info->tcpi_data_segs_in = tp->data_segs_in; info->tcpi_data_segs_out = tp->data_segs_out; info->tcpi_delivery_rate_app_limited = tp->rate_app_limited ? 1 : 0; rate = READ_ONCE(tp->rate_delivered); intv = READ_ONCE(tp->rate_interval_us); if (rate && intv) { rate64 = (u64)rate * tp->mss_cache * USEC_PER_SEC; do_div(rate64, intv); info->tcpi_delivery_rate = rate64; } unlock_sock_fast(sk, slow); } EXPORT_SYMBOL_GPL(tcp_get_info); struct sk_buff *tcp_get_timestamping_opt_stats(const struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *stats; struct tcp_info info; stats = alloc_skb(5 * nla_total_size_64bit(sizeof(u64)), GFP_ATOMIC); if (!stats) return NULL; tcp_get_info_chrono_stats(tp, &info); nla_put_u64_64bit(stats, TCP_NLA_BUSY, info.tcpi_busy_time, TCP_NLA_PAD); nla_put_u64_64bit(stats, TCP_NLA_RWND_LIMITED, info.tcpi_rwnd_limited, TCP_NLA_PAD); nla_put_u64_64bit(stats, TCP_NLA_SNDBUF_LIMITED, info.tcpi_sndbuf_limited, TCP_NLA_PAD); nla_put_u64_64bit(stats, TCP_NLA_DATA_SEGS_OUT, tp->data_segs_out, TCP_NLA_PAD); nla_put_u64_64bit(stats, TCP_NLA_TOTAL_RETRANS, tp->total_retrans, TCP_NLA_PAD); return stats; } static int do_tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct net *net = sock_net(sk); int val, len; if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, sizeof(int)); if (len < 0) return -EINVAL; switch (optname) { case TCP_MAXSEG: val = tp->mss_cache; if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) val = tp->rx_opt.user_mss; if (tp->repair) val = tp->rx_opt.mss_clamp; break; case TCP_NODELAY: val = !!(tp->nonagle&TCP_NAGLE_OFF); break; case TCP_CORK: val = !!(tp->nonagle&TCP_NAGLE_CORK); break; case TCP_KEEPIDLE: val = keepalive_time_when(tp) / HZ; break; case TCP_KEEPINTVL: val = keepalive_intvl_when(tp) / HZ; break; case TCP_KEEPCNT: val = keepalive_probes(tp); break; case TCP_SYNCNT: val = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_syn_retries; break; case TCP_LINGER2: val = tp->linger2; if (val >= 0) val = (val ? : net->ipv4.sysctl_tcp_fin_timeout) / HZ; break; case TCP_DEFER_ACCEPT: val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept, TCP_TIMEOUT_INIT / HZ, TCP_RTO_MAX / HZ); break; case TCP_WINDOW_CLAMP: val = tp->window_clamp; break; case TCP_INFO: { struct tcp_info info; if (get_user(len, optlen)) return -EFAULT; tcp_get_info(sk, &info); len = min_t(unsigned int, len, sizeof(info)); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &info, len)) return -EFAULT; return 0; } case TCP_CC_INFO: { const struct tcp_congestion_ops *ca_ops; union tcp_cc_info info; size_t sz = 0; int attr; if (get_user(len, optlen)) return -EFAULT; ca_ops = icsk->icsk_ca_ops; if (ca_ops && ca_ops->get_info) sz = ca_ops->get_info(sk, ~0U, &attr, &info); len = min_t(unsigned int, len, sz); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &info, len)) return -EFAULT; return 0; } case TCP_QUICKACK: val = !icsk->icsk_ack.pingpong; break; case TCP_CONGESTION: if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, TCP_CA_NAME_MAX); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, icsk->icsk_ca_ops->name, len)) return -EFAULT; return 0; case TCP_THIN_LINEAR_TIMEOUTS: val = tp->thin_lto; break; case TCP_THIN_DUPACK: val = 0; break; case TCP_REPAIR: val = tp->repair; break; case TCP_REPAIR_QUEUE: if (tp->repair) val = tp->repair_queue; else return -EINVAL; break; case TCP_REPAIR_WINDOW: { struct tcp_repair_window opt; if (get_user(len, optlen)) return -EFAULT; if (len != sizeof(opt)) return -EINVAL; if (!tp->repair) return -EPERM; opt.snd_wl1 = tp->snd_wl1; opt.snd_wnd = tp->snd_wnd; opt.max_window = tp->max_window; opt.rcv_wnd = tp->rcv_wnd; opt.rcv_wup = tp->rcv_wup; if (copy_to_user(optval, &opt, len)) return -EFAULT; return 0; } case TCP_QUEUE_SEQ: if (tp->repair_queue == TCP_SEND_QUEUE) val = tp->write_seq; else if (tp->repair_queue == TCP_RECV_QUEUE) val = tp->rcv_nxt; else return -EINVAL; break; case TCP_USER_TIMEOUT: val = jiffies_to_msecs(icsk->icsk_user_timeout); break; case TCP_FASTOPEN: val = icsk->icsk_accept_queue.fastopenq.max_qlen; break; case TCP_FASTOPEN_CONNECT: val = tp->fastopen_connect; break; case TCP_TIMESTAMP: val = tcp_time_stamp + tp->tsoffset; break; case TCP_NOTSENT_LOWAT: val = tp->notsent_lowat; break; case TCP_SAVE_SYN: val = tp->save_syn; break; case TCP_SAVED_SYN: { if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); if (tp->saved_syn) { if (len < tp->saved_syn[0]) { if (put_user(tp->saved_syn[0], optlen)) { release_sock(sk); return -EFAULT; } release_sock(sk); return -EINVAL; } len = tp->saved_syn[0]; if (put_user(len, optlen)) { release_sock(sk); return -EFAULT; } if (copy_to_user(optval, tp->saved_syn + 1, len)) { release_sock(sk); return -EFAULT; } tcp_saved_syn_free(tp); release_sock(sk); } else { release_sock(sk); len = 0; if (put_user(len, optlen)) return -EFAULT; } return 0; } default: return -ENOPROTOOPT; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { struct inet_connection_sock *icsk = inet_csk(sk); if (level != SOL_TCP) return icsk->icsk_af_ops->getsockopt(sk, level, optname, optval, optlen); return do_tcp_getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(tcp_getsockopt); #ifdef CONFIG_COMPAT int compat_tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level != SOL_TCP) return inet_csk_compat_getsockopt(sk, level, optname, optval, optlen); return do_tcp_getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_tcp_getsockopt); #endif #ifdef CONFIG_TCP_MD5SIG static DEFINE_PER_CPU(struct tcp_md5sig_pool, tcp_md5sig_pool); static DEFINE_MUTEX(tcp_md5sig_mutex); static bool tcp_md5sig_pool_populated = false; static void __tcp_alloc_md5sig_pool(void) { struct crypto_ahash *hash; int cpu; hash = crypto_alloc_ahash("md5", 0, CRYPTO_ALG_ASYNC); if (IS_ERR(hash)) return; for_each_possible_cpu(cpu) { void *scratch = per_cpu(tcp_md5sig_pool, cpu).scratch; struct ahash_request *req; if (!scratch) { scratch = kmalloc_node(sizeof(union tcp_md5sum_block) + sizeof(struct tcphdr), GFP_KERNEL, cpu_to_node(cpu)); if (!scratch) return; per_cpu(tcp_md5sig_pool, cpu).scratch = scratch; } if (per_cpu(tcp_md5sig_pool, cpu).md5_req) continue; req = ahash_request_alloc(hash, GFP_KERNEL); if (!req) return; ahash_request_set_callback(req, 0, NULL, NULL); per_cpu(tcp_md5sig_pool, cpu).md5_req = req; } /* before setting tcp_md5sig_pool_populated, we must commit all writes * to memory. See smp_rmb() in tcp_get_md5sig_pool() */ smp_wmb(); tcp_md5sig_pool_populated = true; } bool tcp_alloc_md5sig_pool(void) { if (unlikely(!tcp_md5sig_pool_populated)) { mutex_lock(&tcp_md5sig_mutex); if (!tcp_md5sig_pool_populated) __tcp_alloc_md5sig_pool(); mutex_unlock(&tcp_md5sig_mutex); } return tcp_md5sig_pool_populated; } EXPORT_SYMBOL(tcp_alloc_md5sig_pool); /** * tcp_get_md5sig_pool - get md5sig_pool for this user * * We use percpu structure, so if we succeed, we exit with preemption * and BH disabled, to make sure another thread or softirq handling * wont try to get same context. */ struct tcp_md5sig_pool *tcp_get_md5sig_pool(void) { local_bh_disable(); if (tcp_md5sig_pool_populated) { /* coupled with smp_wmb() in __tcp_alloc_md5sig_pool() */ smp_rmb(); return this_cpu_ptr(&tcp_md5sig_pool); } local_bh_enable(); return NULL; } EXPORT_SYMBOL(tcp_get_md5sig_pool); int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp, const struct sk_buff *skb, unsigned int header_len) { struct scatterlist sg; const struct tcphdr *tp = tcp_hdr(skb); struct ahash_request *req = hp->md5_req; unsigned int i; const unsigned int head_data_len = skb_headlen(skb) > header_len ? skb_headlen(skb) - header_len : 0; const struct skb_shared_info *shi = skb_shinfo(skb); struct sk_buff *frag_iter; sg_init_table(&sg, 1); sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len); ahash_request_set_crypt(req, &sg, NULL, head_data_len); if (crypto_ahash_update(req)) return 1; for (i = 0; i < shi->nr_frags; ++i) { const struct skb_frag_struct *f = &shi->frags[i]; unsigned int offset = f->page_offset; struct page *page = skb_frag_page(f) + (offset >> PAGE_SHIFT); sg_set_page(&sg, page, skb_frag_size(f), offset_in_page(offset)); ahash_request_set_crypt(req, &sg, NULL, skb_frag_size(f)); if (crypto_ahash_update(req)) return 1; } skb_walk_frags(skb, frag_iter) if (tcp_md5_hash_skb_data(hp, frag_iter, 0)) return 1; return 0; } EXPORT_SYMBOL(tcp_md5_hash_skb_data); int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key) { struct scatterlist sg; sg_init_one(&sg, key->key, key->keylen); ahash_request_set_crypt(hp->md5_req, &sg, NULL, key->keylen); return crypto_ahash_update(hp->md5_req); } EXPORT_SYMBOL(tcp_md5_hash_key); #endif void tcp_done(struct sock *sk) { struct request_sock *req = tcp_sk(sk)->fastopen_rsk; if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV) TCP_INC_STATS(sock_net(sk), TCP_MIB_ATTEMPTFAILS); tcp_set_state(sk, TCP_CLOSE); tcp_clear_xmit_timers(sk); if (req) reqsk_fastopen_remove(sk, req, false); sk->sk_shutdown = SHUTDOWN_MASK; if (!sock_flag(sk, SOCK_DEAD)) sk->sk_state_change(sk); else inet_csk_destroy_sock(sk); } EXPORT_SYMBOL_GPL(tcp_done); int tcp_abort(struct sock *sk, int err) { if (!sk_fullsock(sk)) { if (sk->sk_state == TCP_NEW_SYN_RECV) { struct request_sock *req = inet_reqsk(sk); local_bh_disable(); inet_csk_reqsk_queue_drop_and_put(req->rsk_listener, req); local_bh_enable(); return 0; } return -EOPNOTSUPP; } /* Don't race with userspace socket closes such as tcp_close. */ lock_sock(sk); if (sk->sk_state == TCP_LISTEN) { tcp_set_state(sk, TCP_CLOSE); inet_csk_listen_stop(sk); } /* Don't race with BH socket closes such as inet_csk_listen_stop. */ local_bh_disable(); bh_lock_sock(sk); if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_err = err; /* This barrier is coupled with smp_rmb() in tcp_poll() */ smp_wmb(); sk->sk_error_report(sk); if (tcp_need_reset(sk->sk_state)) tcp_send_active_reset(sk, GFP_ATOMIC); tcp_done(sk); } bh_unlock_sock(sk); local_bh_enable(); release_sock(sk); return 0; } EXPORT_SYMBOL_GPL(tcp_abort); extern struct tcp_congestion_ops tcp_reno; static __initdata unsigned long thash_entries; static int __init set_thash_entries(char *str) { ssize_t ret; if (!str) return 0; ret = kstrtoul(str, 0, &thash_entries); if (ret) return 0; return 1; } __setup("thash_entries=", set_thash_entries); static void __init tcp_init_mem(void) { unsigned long limit = nr_free_buffer_pages() / 16; limit = max(limit, 128UL); sysctl_tcp_mem[0] = limit / 4 * 3; /* 4.68 % */ sysctl_tcp_mem[1] = limit; /* 6.25 % */ sysctl_tcp_mem[2] = sysctl_tcp_mem[0] * 2; /* 9.37 % */ } void __init tcp_init(void) { int max_rshare, max_wshare, cnt; unsigned long limit; unsigned int i; BUILD_BUG_ON(sizeof(struct tcp_skb_cb) > FIELD_SIZEOF(struct sk_buff, cb)); percpu_counter_init(&tcp_sockets_allocated, 0, GFP_KERNEL); percpu_counter_init(&tcp_orphan_count, 0, GFP_KERNEL); inet_hashinfo_init(&tcp_hashinfo); tcp_hashinfo.bind_bucket_cachep = kmem_cache_create("tcp_bind_bucket", sizeof(struct inet_bind_bucket), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); /* Size and allocate the main established and bind bucket * hash tables. * * The methodology is similar to that of the buffer cache. */ tcp_hashinfo.ehash = alloc_large_system_hash("TCP established", sizeof(struct inet_ehash_bucket), thash_entries, 17, /* one slot per 128 KB of memory */ 0, NULL, &tcp_hashinfo.ehash_mask, 0, thash_entries ? 0 : 512 * 1024); for (i = 0; i <= tcp_hashinfo.ehash_mask; i++) INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i); if (inet_ehash_locks_alloc(&tcp_hashinfo)) panic("TCP: failed to alloc ehash_locks"); tcp_hashinfo.bhash = alloc_large_system_hash("TCP bind", sizeof(struct inet_bind_hashbucket), tcp_hashinfo.ehash_mask + 1, 17, /* one slot per 128 KB of memory */ 0, &tcp_hashinfo.bhash_size, NULL, 0, 64 * 1024); tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size; for (i = 0; i < tcp_hashinfo.bhash_size; i++) { spin_lock_init(&tcp_hashinfo.bhash[i].lock); INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain); } cnt = tcp_hashinfo.ehash_mask + 1; sysctl_tcp_max_orphans = cnt / 2; tcp_init_mem(); /* Set per-socket limits to no more than 1/128 the pressure threshold */ limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7); max_wshare = min(4UL*1024*1024, limit); max_rshare = min(6UL*1024*1024, limit); sysctl_tcp_wmem[0] = SK_MEM_QUANTUM; sysctl_tcp_wmem[1] = 16*1024; sysctl_tcp_wmem[2] = max(64*1024, max_wshare); sysctl_tcp_rmem[0] = SK_MEM_QUANTUM; sysctl_tcp_rmem[1] = 87380; sysctl_tcp_rmem[2] = max(87380, max_rshare); pr_info("Hash tables configured (established %u bind %u)\n", tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size); tcp_v4_init(); tcp_metrics_init(); BUG_ON(tcp_register_congestion_control(&tcp_reno) != 0); tcp_tasklet_init(); }
./CrossVul/dataset_final_sorted/CWE-369/c/good_2768_0
crossvul-cpp_data_good_258_0
/* * MOV, 3GP, MP4 muxer * Copyright (c) 2003 Thomas Raivio * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org> * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com> * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdint.h> #include <inttypes.h> #include "movenc.h" #include "avformat.h" #include "avio_internal.h" #include "riff.h" #include "avio.h" #include "isom.h" #include "avc.h" #include "libavcodec/ac3_parser_internal.h" #include "libavcodec/dnxhddata.h" #include "libavcodec/flac.h" #include "libavcodec/get_bits.h" #include "libavcodec/internal.h" #include "libavcodec/put_bits.h" #include "libavcodec/vc1_common.h" #include "libavcodec/raw.h" #include "internal.h" #include "libavutil/avstring.h" #include "libavutil/intfloat.h" #include "libavutil/mathematics.h" #include "libavutil/libm.h" #include "libavutil/opt.h" #include "libavutil/dict.h" #include "libavutil/pixdesc.h" #include "libavutil/stereo3d.h" #include "libavutil/timecode.h" #include "libavutil/color_utils.h" #include "hevc.h" #include "rtpenc.h" #include "mov_chan.h" #include "vpcc.h" static const AVOption options[] = { { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 }, { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags), { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "empty_hdlr_name", "write zero-length name string in hdlr atoms within mdia and minf atoms", offsetof(MOVMuxContext, empty_hdlr_name), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { NULL }, }; #define MOV_CLASS(flavor)\ static const AVClass flavor ## _muxer_class = {\ .class_name = #flavor " muxer",\ .item_name = av_default_item_name,\ .option = options,\ .version = LIBAVUTIL_VERSION_INT,\ }; static int get_moov_size(AVFormatContext *s); static int utf8len(const uint8_t *b) { int len = 0; int val; while (*b) { GET_UTF8(val, *b++, return -1;) len++; } return len; } //FIXME support 64 bit variant with wide placeholders static int64_t update_size(AVIOContext *pb, int64_t pos) { int64_t curpos = avio_tell(pb); avio_seek(pb, pos, SEEK_SET); avio_wb32(pb, curpos - pos); /* rewrite size */ avio_seek(pb, curpos, SEEK_SET); return curpos - pos; } static int co64_required(const MOVTrack *track) { if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX) return 1; return 0; } static int is_cover_image(const AVStream *st) { /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS * is encoded as sparse video track */ return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC; } static int rtp_hinting_needed(const AVStream *st) { /* Add hint tracks for each real audio and video stream */ if (is_cover_image(st)) return 0; return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO; } /* Chunk offset atom */ static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track) { int i; int mode64 = co64_required(track); // use 32 bit size variant if possible int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ if (mode64) ffio_wfourcc(pb, "co64"); else ffio_wfourcc(pb, "stco"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->chunkCount); /* entry count */ for (i = 0; i < track->entry; i++) { if (!track->cluster[i].chunkNum) continue; if (mode64 == 1) avio_wb64(pb, track->cluster[i].pos + track->data_offset); else avio_wb32(pb, track->cluster[i].pos + track->data_offset); } return update_size(pb, pos); } /* Sample size atom */ static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track) { int equalChunks = 1; int i, j, entries = 0, tst = -1, oldtst = -1; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsz"); avio_wb32(pb, 0); /* version & flags */ for (i = 0; i < track->entry; i++) { tst = track->cluster[i].size / track->cluster[i].entries; if (oldtst != -1 && tst != oldtst) equalChunks = 0; oldtst = tst; entries += track->cluster[i].entries; } if (equalChunks && track->entry) { int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0; sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0 avio_wb32(pb, sSize); // sample size avio_wb32(pb, entries); // sample count } else { avio_wb32(pb, 0); // sample size avio_wb32(pb, entries); // sample count for (i = 0; i < track->entry; i++) { for (j = 0; j < track->cluster[i].entries; j++) { avio_wb32(pb, track->cluster[i].size / track->cluster[i].entries); } } } return update_size(pb, pos); } /* Sample to chunk atom */ static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track) { int index = 0, oldval = -1, i; int64_t entryPos, curpos; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsc"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->chunkCount); // entry count for (i = 0; i < track->entry; i++) { if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) { avio_wb32(pb, track->cluster[i].chunkNum); // first chunk avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk avio_wb32(pb, 0x1); // sample description index oldval = track->cluster[i].samples_in_chunk; index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sync sample atom */ static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag) { int64_t curpos, entryPos; int i, index = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->entry); // entry count for (i = 0; i < track->entry; i++) { if (track->cluster[i].flags & flag) { avio_wb32(pb, i + 1); index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sample dependency atom */ static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track) { int i; uint8_t leading, dependent, reference, redundancy; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "sdtp"); avio_wb32(pb, 0); // version & flags for (i = 0; i < track->entry; i++) { dependent = MOV_SAMPLE_DEPENDENCY_YES; leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN; if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) { reference = MOV_SAMPLE_DEPENDENCY_NO; } if (track->cluster[i].flags & MOV_SYNC_SAMPLE) { dependent = MOV_SAMPLE_DEPENDENCY_NO; } avio_w8(pb, (leading << 6) | (dependent << 4) | (reference << 2) | redundancy); } return update_size(pb, pos); } static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x11); /* size */ if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr"); else ffio_wfourcc(pb, "damr"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */ avio_w8(pb, 0x00); /* Mode change period (no restriction) */ avio_w8(pb, 0x01); /* Frames per sample */ return 0x11; } static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track) { GetBitContext gbc; PutBitContext pbc; uint8_t buf[3]; int fscod, bsid, bsmod, acmod, lfeon, frmsizecod; if (track->vos_len < 7) return -1; avio_wb32(pb, 11); ffio_wfourcc(pb, "dac3"); init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8); fscod = get_bits(&gbc, 2); frmsizecod = get_bits(&gbc, 6); bsid = get_bits(&gbc, 5); bsmod = get_bits(&gbc, 3); acmod = get_bits(&gbc, 3); if (acmod == 2) { skip_bits(&gbc, 2); // dsurmod } else { if ((acmod & 1) && acmod != 1) skip_bits(&gbc, 2); // cmixlev if (acmod & 4) skip_bits(&gbc, 2); // surmixlev } lfeon = get_bits1(&gbc); init_put_bits(&pbc, buf, sizeof(buf)); put_bits(&pbc, 2, fscod); put_bits(&pbc, 5, bsid); put_bits(&pbc, 3, bsmod); put_bits(&pbc, 3, acmod); put_bits(&pbc, 1, lfeon); put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code put_bits(&pbc, 5, 0); // reserved flush_put_bits(&pbc); avio_write(pb, buf, sizeof(buf)); return 11; } struct eac3_info { AVPacket pkt; uint8_t ec3_done; uint8_t num_blocks; /* Layout of the EC3SpecificBox */ /* maximum bitrate */ uint16_t data_rate; /* number of independent substreams */ uint8_t num_ind_sub; struct { /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */ uint8_t fscod; /* bit stream identification 5 bits */ uint8_t bsid; /* one bit reserved */ /* audio service mixing (not supported yet) 1 bit */ /* bit stream mode 3 bits */ uint8_t bsmod; /* audio coding mode 3 bits */ uint8_t acmod; /* sub woofer on 1 bit */ uint8_t lfeon; /* 3 bits reserved */ /* number of dependent substreams associated with this substream 4 bits */ uint8_t num_dep_sub; /* channel locations of the dependent substream(s), if any, 9 bits */ uint16_t chan_loc; /* if there is no dependent substream, then one bit reserved instead */ } substream[1]; /* TODO: support 8 independent substreams */ }; #if CONFIG_AC3_PARSER static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov->fc, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { //info->num_ind_sub++; avpriv_request_sample(mov->fc, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } else { if (hdr->substreamid != 0) { avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } #endif static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track) { PutBitContext pbc; uint8_t *buf; struct eac3_info *info; int size, i; if (!track->eac3_priv) return AVERROR(EINVAL); info = track->eac3_priv; size = 2 + 4 * (info->num_ind_sub + 1); buf = av_malloc(size); if (!buf) { size = AVERROR(ENOMEM); goto end; } init_put_bits(&pbc, buf, size); put_bits(&pbc, 13, info->data_rate); put_bits(&pbc, 3, info->num_ind_sub); for (i = 0; i <= info->num_ind_sub; i++) { put_bits(&pbc, 2, info->substream[i].fscod); put_bits(&pbc, 5, info->substream[i].bsid); put_bits(&pbc, 1, 0); /* reserved */ put_bits(&pbc, 1, 0); /* asvc */ put_bits(&pbc, 3, info->substream[i].bsmod); put_bits(&pbc, 3, info->substream[i].acmod); put_bits(&pbc, 1, info->substream[i].lfeon); put_bits(&pbc, 5, 0); /* reserved */ put_bits(&pbc, 4, info->substream[i].num_dep_sub); if (!info->substream[i].num_dep_sub) { put_bits(&pbc, 1, 0); /* reserved */ size--; } else { put_bits(&pbc, 9, info->substream[i].chan_loc); } } flush_put_bits(&pbc); avio_wb32(pb, size + 8); ffio_wfourcc(pb, "dec3"); avio_write(pb, buf, size); av_free(buf); end: av_packet_unref(&info->pkt); av_freep(&track->eac3_priv); return size; } /** * This function writes extradata "as is". * Extradata must be formatted like a valid atom (with size and tag). */ static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track) { avio_write(pb, track->par->extradata, track->par->extradata_size); return track->par->extradata_size; } static int mov_write_enda_tag(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 1); /* little endian */ return 10; } static int mov_write_enda_tag_be(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 0); /* big endian */ return 10; } static void put_descr(AVIOContext *pb, int tag, unsigned int size) { int i = 3; avio_w8(pb, tag); for (; i > 0; i--) avio_w8(pb, (size >> (7 * i)) | 0x80); avio_w8(pb, size & 0x7F); } static unsigned compute_avg_bitrate(MOVTrack *track) { uint64_t size = 0; int i; if (!track->track_duration) return 0; for (i = 0; i < track->entry; i++) size += track->cluster[i].size; return size * 8 * track->timescale / track->track_duration; } static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic { AVCPBProperties *props; int64_t pos = avio_tell(pb); int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0; unsigned avg_bitrate; avio_wb32(pb, 0); // size ffio_wfourcc(pb, "esds"); avio_wb32(pb, 0); // Version // ES descriptor put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1); avio_wb16(pb, track->track_id); avio_w8(pb, 0x00); // flags (= no flags) // DecoderConfig descriptor put_descr(pb, 0x04, 13 + decoder_specific_info_len); // Object type indication if ((track->par->codec_id == AV_CODEC_ID_MP2 || track->par->codec_id == AV_CODEC_ID_MP3) && track->par->sample_rate > 24000) avio_w8(pb, 0x6B); // 11172-3 else avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id)); // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio) // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved) if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream) else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_w8(pb, 0x15); // flags (= Audiostream) else avio_w8(pb, 0x11); // flags (= Visualstream) props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB avg_bitrate = compute_avg_bitrate(track); avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window) avio_wb32(pb, avg_bitrate); if (track->vos_len) { // DecoderSpecific info descriptor put_descr(pb, 0x05, track->vos_len); avio_write(pb, track->vos_data, track->vos_len); } // SL descriptor put_descr(pb, 0x06, 1); avio_w8(pb, 0x02); return update_size(pb, pos); } static int mov_pcm_le_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24LE || codec_id == AV_CODEC_ID_PCM_S32LE || codec_id == AV_CODEC_ID_PCM_F32LE || codec_id == AV_CODEC_ID_PCM_F64LE; } static int mov_pcm_be_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24BE || codec_id == AV_CODEC_ID_PCM_S32BE || codec_id == AV_CODEC_ID_PCM_F32BE || codec_id == AV_CODEC_ID_PCM_F64BE; } static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); avio_wl32(pb, track->tag); // store it byteswapped track->par->codec_tag = av_bswap16(track->tag >> 16); if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0) return ret; return update_size(pb, pos); } static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "wfex"); if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0) return ret; return update_size(pb, pos); } static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dfLa"); avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */ if (track->par->extradata_size != FLAC_STREAMINFO_SIZE) return AVERROR_INVALIDDATA; /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */ avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */ avio_wb24(pb, track->par->extradata_size); /* Length */ avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */ return update_size(pb, pos); } static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dOps"); avio_w8(pb, 0); /* Version */ if (track->par->extradata_size < 19) { av_log(pb, AV_LOG_ERROR, "invalid extradata size\n"); return AVERROR_INVALIDDATA; } /* extradata contains an Ogg OpusHead, other than byte-ordering and OpusHead's preceeding magic/version, OpusSpecificBox is currently identical. */ avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */ avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */ avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */ avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */ /* Write the rest of the header out without byte-swapping. */ avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18); return update_size(pb, pos); } static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { uint32_t layout_tag, bitmap; int64_t pos = avio_tell(pb); layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id, track->par->channel_layout, &bitmap); if (!layout_tag) { av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to " "lack of channel information\n"); return 0; } if (track->multichannel_as_mono) return 0; avio_wb32(pb, 0); // Size ffio_wfourcc(pb, "chan"); // Type avio_w8(pb, 0); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, layout_tag); // mChannelLayoutTag avio_wb32(pb, bitmap); // mChannelBitmap avio_wb32(pb, 0); // mNumberChannelDescriptions return update_size(pb, pos); } static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "wave"); if (track->par->codec_id != AV_CODEC_ID_QDM2) { avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "frma"); avio_wl32(pb, track->tag); } if (track->par->codec_id == AV_CODEC_ID_AAC) { /* useless atom needed by mplayer, ipod, not needed by quicktime */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0); mov_write_esds_tag(pb, track); } else if (mov_pcm_le_gt16(track->par->codec_id)) { mov_write_enda_tag(pb); } else if (mov_pcm_be_gt16(track->par->codec_id)) { mov_write_enda_tag_be(pb); } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) { mov_write_amr_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_AC3) { mov_write_ac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_EAC3) { mov_write_eac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_QDM2) { mov_write_extradata_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { mov_write_ms_tag(s, pb, track); } avio_wb32(pb, 8); /* size */ avio_wb32(pb, 0); /* null tag */ return update_size(pb, pos); } static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf) { uint8_t *unescaped; const uint8_t *start, *next, *end = track->vos_data + track->vos_len; int unescaped_size, seq_found = 0; int level = 0, interlace = 0; int packet_seq = track->vc1_info.packet_seq; int packet_entry = track->vc1_info.packet_entry; int slices = track->vc1_info.slices; PutBitContext pbc; if (track->start_dts == AV_NOPTS_VALUE) { /* No packets written yet, vc1_info isn't authoritative yet. */ /* Assume inline sequence and entry headers. */ packet_seq = packet_entry = 1; av_log(NULL, AV_LOG_WARNING, "moov atom written before any packets, unable to write correct " "dvc1 atom. Set the delay_moov flag to fix this.\n"); } unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE); if (!unescaped) return AVERROR(ENOMEM); start = find_next_marker(track->vos_data, end); for (next = start; next < end; start = next) { GetBitContext gb; int size; next = find_next_marker(start + 4, end); size = next - start - 4; if (size <= 0) continue; unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped); init_get_bits(&gb, unescaped, 8 * unescaped_size); if (AV_RB32(start) == VC1_CODE_SEQHDR) { int profile = get_bits(&gb, 2); if (profile != PROFILE_ADVANCED) { av_free(unescaped); return AVERROR(ENOSYS); } seq_found = 1; level = get_bits(&gb, 3); /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag, * width, height */ skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12); skip_bits(&gb, 1); /* broadcast */ interlace = get_bits1(&gb); skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */ } } if (!seq_found) { av_free(unescaped); return AVERROR(ENOSYS); } init_put_bits(&pbc, buf, 7); /* VC1DecSpecStruc */ put_bits(&pbc, 4, 12); /* profile - advanced */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* reserved */ /* VC1AdvDecSpecStruc */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* cbr */ put_bits(&pbc, 6, 0); /* reserved */ put_bits(&pbc, 1, !interlace); /* no interlace */ put_bits(&pbc, 1, !packet_seq); /* no multiple seq */ put_bits(&pbc, 1, !packet_entry); /* no multiple entry */ put_bits(&pbc, 1, !slices); /* no slice code */ put_bits(&pbc, 1, 0); /* no bframe */ put_bits(&pbc, 1, 0); /* reserved */ /* framerate */ if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0) put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den); else put_bits32(&pbc, 0xffffffff); flush_put_bits(&pbc); av_free(unescaped); return 0; } static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track) { uint8_t buf[7] = { 0 }; int ret; if ((ret = mov_write_dvc1_structs(track, buf)) < 0) return ret; avio_wb32(pb, track->vos_len + 8 + sizeof(buf)); ffio_wfourcc(pb, "dvc1"); avio_write(pb, buf, sizeof(buf)); avio_write(pb, track->vos_data, track->vos_len); return 0; } static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, track->vos_len + 8); ffio_wfourcc(pb, "glbl"); avio_write(pb, track->vos_data, track->vos_len); return 8 + track->vos_len; } /** * Compute flags for 'lpcm' tag. * See CoreAudioTypes and AudioStreamBasicDescription at Apple. */ static int mov_get_lpcm_flags(enum AVCodecID codec_id) { switch (codec_id) { case AV_CODEC_ID_PCM_F32BE: case AV_CODEC_ID_PCM_F64BE: return 11; case AV_CODEC_ID_PCM_F32LE: case AV_CODEC_ID_PCM_F64LE: return 9; case AV_CODEC_ID_PCM_U8: return 10; case AV_CODEC_ID_PCM_S16BE: case AV_CODEC_ID_PCM_S24BE: case AV_CODEC_ID_PCM_S32BE: return 14; case AV_CODEC_ID_PCM_S8: case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S24LE: case AV_CODEC_ID_PCM_S32LE: return 12; default: return 0; } } static int get_cluster_duration(MOVTrack *track, int cluster_idx) { int64_t next_dts; if (cluster_idx >= track->entry) return 0; if (cluster_idx + 1 == track->entry) next_dts = track->track_duration + track->start_dts; else next_dts = track->cluster[cluster_idx + 1].dts; next_dts -= track->cluster[cluster_idx].dts; av_assert0(next_dts >= 0); av_assert0(next_dts <= INT_MAX); return next_dts; } static int get_samples_per_packet(MOVTrack *track) { int i, first_duration; // return track->par->frame_size; /* use 1 for raw PCM */ if (!track->audio_vbr) return 1; /* check to see if duration is constant for all clusters */ if (!track->entry) return 0; first_duration = get_cluster_duration(track, 0); for (i = 1; i < track->entry; i++) { if (get_cluster_duration(track, i) != first_duration) return 0; } return first_duration; } static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int version = 0; uint32_t tag = track->tag; if (track->mode == MODE_MOV) { if (track->timescale > UINT16_MAX || !track->par->channels) { if (mov_get_lpcm_flags(track->par->codec_id)) tag = AV_RL32("lpcm"); version = 2; } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id) || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2) { version = 1; } } avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "enca"); } else { avio_wl32(pb, tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */ /* SoundDescription */ avio_wb16(pb, version); /* Version */ avio_wb16(pb, 0); /* Revision level */ avio_wb32(pb, 0); /* Reserved */ if (version == 2) { avio_wb16(pb, 3); avio_wb16(pb, 16); avio_wb16(pb, 0xfffe); avio_wb16(pb, 0); avio_wb32(pb, 0x00010000); avio_wb32(pb, 72); avio_wb64(pb, av_double2int(track->par->sample_rate)); avio_wb32(pb, track->par->channels); avio_wb32(pb, 0x7F000000); avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id)); avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id)); avio_wb32(pb, track->sample_size); avio_wb32(pb, get_samples_per_packet(track)); } else { if (track->mode == MODE_MOV) { avio_wb16(pb, track->par->channels); if (track->par->codec_id == AV_CODEC_ID_PCM_U8 || track->par->codec_id == AV_CODEC_ID_PCM_S8) avio_wb16(pb, 8); /* bits per sample */ else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726) avio_wb16(pb, track->par->bits_per_coded_sample); else avio_wb16(pb, 16); avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */ } else { /* reserved for mp4/3gp */ if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { avio_wb16(pb, track->par->channels); } else { avio_wb16(pb, 2); } if (track->par->codec_id == AV_CODEC_ID_FLAC) { avio_wb16(pb, track->par->bits_per_raw_sample); } else { avio_wb16(pb, 16); } avio_wb16(pb, 0); } avio_wb16(pb, 0); /* packet size (= 0) */ if (track->par->codec_id == AV_CODEC_ID_OPUS) avio_wb16(pb, 48000); else avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ? track->par->sample_rate : 0); avio_wb16(pb, 0); /* Reserved */ } if (version == 1) { /* SoundDescription V1 extended info */ if (mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id)) avio_wb32(pb, 1); /* must be 1 for uncompressed formats */ else avio_wb32(pb, track->par->frame_size); /* Samples per packet */ avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */ avio_wb32(pb, track->sample_size); /* Bytes per frame */ avio_wb32(pb, 2); /* Bytes per sample */ } if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_AAC || track->par->codec_id == AV_CODEC_ID_AC3 || track->par->codec_id == AV_CODEC_ID_EAC3 || track->par->codec_id == AV_CODEC_ID_AMR_NB || track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2 || (mov_pcm_le_gt16(track->par->codec_id) && version==1) || (mov_pcm_be_gt16(track->par->codec_id) && version==1))) mov_write_wave_tag(s, pb, track); else if (track->tag == MKTAG('m','p','4','a')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) mov_write_amr_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AC3) mov_write_ac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_EAC3) mov_write_eac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_ALAC) mov_write_extradata_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) mov_write_wfex_tag(s, pb, track); else if (track->par->codec_id == AV_CODEC_ID_FLAC) mov_write_dfla_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_OPUS) mov_write_dops_tag(pb, track); else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_chan_tag(s, pb, track); if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } return update_size(pb, pos); } static int mov_write_d263_tag(AVIOContext *pb) { avio_wb32(pb, 0xf); /* size */ ffio_wfourcc(pb, "d263"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ /* FIXME use AVCodecContext level/profile, when encoder will set values */ avio_w8(pb, 0xa); /* level */ avio_w8(pb, 0); /* profile */ return 0xf; } static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "avcC"); ff_isom_write_avcc(pb, track->vos_data, track->vos_len); return update_size(pb, pos); } static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "vpcC"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); /* flags */ ff_isom_write_vpcc(s, pb, track->par); return update_size(pb, pos); } static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "hvcC"); if (track->tag == MKTAG('h','v','c','1')) ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1); else ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0); return update_size(pb, pos); } /* also used by all avid codecs (dv, imx, meridien) and their variants */ static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track) { int i; int interlaced; int cid; int display_width = track->par->width; if (track->vos_data && track->vos_len > 0x29) { if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) { /* looks like a DNxHD bit stream */ interlaced = (track->vos_data[5] & 2); cid = AV_RB32(track->vos_data + 0x28); } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n"); return 0; } } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n"); return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "0001"); if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */ track->par->color_range == AVCOL_RANGE_UNSPECIFIED) { avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */ } else { /* Full range (0-255) */ avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */ } avio_wb32(pb, 0); /* unknown */ if (track->tag == MKTAG('A','V','d','h')) { avio_wb32(pb, 32); ffio_wfourcc(pb, "ADHR"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 0); /* unknown */ return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 120); /* size */ ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); /* dnxhd cid, some id ? */ if ( track->par->sample_aspect_ratio.num > 0 && track->par->sample_aspect_ratio.den > 0) display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den; avio_wb32(pb, display_width); /* values below are based on samples created with quicktime and avid codecs */ if (interlaced) { avio_wb32(pb, track->par->height / 2); avio_wb32(pb, 2); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 4); /* unknown */ } else { avio_wb32(pb, track->par->height); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ if (track->par->height == 1080) avio_wb32(pb, 5); /* unknown */ else avio_wb32(pb, 6); /* unknown */ } /* padding */ for (i = 0; i < 10; i++) avio_wb64(pb, 0); return 0; } static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 12); ffio_wfourcc(pb, "DpxE"); if (track->par->extradata_size >= 12 && !memcmp(&track->par->extradata[4], "DpxE", 4)) { avio_wb32(pb, track->par->extradata[11]); } else { avio_wb32(pb, 1); } return 0; } static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (track->par->width == 720) { /* SD */ if (track->par->height == 480) { /* NTSC */ if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n'); else tag = MKTAG('d','v','c',' '); }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p'); else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p'); else tag = MKTAG('d','v','p','p'); } else if (track->par->height == 720) { /* HD 720 line */ if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q'); else tag = MKTAG('d','v','h','p'); } else if (track->par->height == 1080) { /* HD 1080 line */ if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5'); else tag = MKTAG('d','v','h','6'); } else { av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n"); return 0; } return tag; } static AVRational find_fps(AVFormatContext *s, AVStream *st) { AVRational rate = st->avg_frame_rate; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS rate = av_inv_q(st->codec->time_base); if (av_timecode_check_frame_rate(rate) < 0) { av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n", rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den); rate = st->avg_frame_rate; } FF_ENABLE_DEPRECATION_WARNINGS #endif return rate; } static int defined_frame_rate(AVFormatContext *s, AVStream *st) { AVRational rational_framerate = find_fps(s, st); int rate = 0; if (rational_framerate.den != 0) rate = av_q2d(rational_framerate); return rate; } static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('m', '2', 'v', '1'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','4'); else if (rate == 25) tag = MKTAG('x','d','v','5'); else if (rate == 30) tag = MKTAG('x','d','v','1'); else if (rate == 50) tag = MKTAG('x','d','v','a'); else if (rate == 60) tag = MKTAG('x','d','v','9'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','6'); else if (rate == 25) tag = MKTAG('x','d','v','7'); else if (rate == 30) tag = MKTAG('x','d','v','8'); } else { if (rate == 25) tag = MKTAG('x','d','v','3'); else if (rate == 30) tag = MKTAG('x','d','v','2'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','d'); else if (rate == 25) tag = MKTAG('x','d','v','e'); else if (rate == 30) tag = MKTAG('x','d','v','f'); } else { if (rate == 25) tag = MKTAG('x','d','v','c'); else if (rate == 30) tag = MKTAG('x','d','v','b'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','4'); else if (rate == 25) tag = MKTAG('x','d','5','5'); else if (rate == 30) tag = MKTAG('x','d','5','1'); else if (rate == 50) tag = MKTAG('x','d','5','a'); else if (rate == 60) tag = MKTAG('x','d','5','9'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','d'); else if (rate == 25) tag = MKTAG('x','d','5','e'); else if (rate == 30) tag = MKTAG('x','d','5','f'); } else { if (rate == 25) tag = MKTAG('x','d','5','c'); else if (rate == 30) tag = MKTAG('x','d','5','b'); } } } return tag; } static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P10) { if (track->par->width == 960 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','p'); else if (rate == 25) tag = MKTAG('a','i','5','q'); else if (rate == 30) tag = MKTAG('a','i','5','p'); else if (rate == 50) tag = MKTAG('a','i','5','q'); else if (rate == 60) tag = MKTAG('a','i','5','p'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','3'); else if (rate == 25) tag = MKTAG('a','i','5','2'); else if (rate == 30) tag = MKTAG('a','i','5','3'); } else { if (rate == 50) tag = MKTAG('a','i','5','5'); else if (rate == 60) tag = MKTAG('a','i','5','6'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P10) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','p'); else if (rate == 25) tag = MKTAG('a','i','1','q'); else if (rate == 30) tag = MKTAG('a','i','1','p'); else if (rate == 50) tag = MKTAG('a','i','1','q'); else if (rate == 60) tag = MKTAG('a','i','1','p'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','3'); else if (rate == 25) tag = MKTAG('a','i','1','2'); else if (rate == 30) tag = MKTAG('a','i','1','3'); } else { if (rate == 25) tag = MKTAG('a','i','1','5'); else if (rate == 50) tag = MKTAG('a','i','1','5'); else if (rate == 60) tag = MKTAG('a','i','1','6'); } } else if ( track->par->width == 4096 && track->par->height == 2160 || track->par->width == 3840 && track->par->height == 2160 || track->par->width == 2048 && track->par->height == 1080) { tag = MKTAG('a','i','v','x'); } } return tag; } static const struct { enum AVPixelFormat pix_fmt; uint32_t tag; unsigned bps; } mov_pix_fmt_tags[] = { { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 }, { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 }, { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 }, { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 }, { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 }, { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 }, { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 }, { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 }, { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 }, { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 }, { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 }, { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 }, { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 }, { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 }, { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 }, }; static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = MKTAG('A','V','d','n'); if (track->par->profile != FF_PROFILE_UNKNOWN && track->par->profile != FF_PROFILE_DNXHD) tag = MKTAG('A','V','d','h'); return tag; } static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int i; enum AVPixelFormat pix_fmt; for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) { if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) { tag = mov_pix_fmt_tags[i].tag; track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps; if (track->par->codec_tag == mov_pix_fmt_tags[i].tag) break; } } pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov, track->par->bits_per_coded_sample); if (tag == MKTAG('r','a','w',' ') && track->par->format != pix_fmt && track->par->format != AV_PIX_FMT_GRAY8 && track->par->format != AV_PIX_FMT_NONE) av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n", av_get_pix_fmt_name(track->par->format)); return tag; } static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL && (track->par->codec_id == AV_CODEC_ID_DVVIDEO || track->par->codec_id == AV_CODEC_ID_RAWVIDEO || track->par->codec_id == AV_CODEC_ID_H263 || track->par->codec_id == AV_CODEC_ID_H264 || track->par->codec_id == AV_CODEC_ID_DNXHD || track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO || av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio if (track->par->codec_id == AV_CODEC_ID_DVVIDEO) tag = mov_get_dv_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) tag = mov_get_rawvideo_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO) tag = mov_get_mpeg2_xdcam_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_H264) tag = mov_get_h264_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_DNXHD) tag = mov_get_dnxhd_codec_tag(s, track); else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id); if (tag) av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, " "the file may be unplayable!\n"); } } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id); if (ms_tag) { tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff)); av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, " "the file may be unplayable!\n"); } } } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id); } return tag; } static const AVCodecTag codec_cover_image_tags[] = { { AV_CODEC_ID_MJPEG, 0xD }, { AV_CODEC_ID_PNG, 0xE }, { AV_CODEC_ID_BMP, 0x1B }, { AV_CODEC_ID_NONE, 0 }, }; static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (is_cover_image(track->st)) return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id); if (track->mode == MODE_MP4 || track->mode == MODE_PSP) tag = track->par->codec_tag; else if (track->mode == MODE_ISM) tag = track->par->codec_tag; else if (track->mode == MODE_IPOD) { if (!av_match_ext(s->url, "m4a") && !av_match_ext(s->url, "m4v") && !av_match_ext(s->url, "m4b")) av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v " "Quicktime/Ipod might not play the file\n"); tag = track->par->codec_tag; } else if (track->mode & MODE_3GP) tag = track->par->codec_tag; else if (track->mode == MODE_F4V) tag = track->par->codec_tag; else tag = mov_get_codec_tag(s, track); return tag; } /** Write uuid atom. * Needed to make file play in iPods running newest firmware * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1 */ static int mov_write_uuid_tag_ipod(AVIOContext *pb) { avio_wb32(pb, 28); ffio_wfourcc(pb, "uuid"); avio_wb32(pb, 0x6b6840f2); avio_wb32(pb, 0x5f244fc5); avio_wb32(pb, 0xba39a51b); avio_wb32(pb, 0xcf0323f3); avio_wb32(pb, 0x0); return 28; } static const uint16_t fiel_data[] = { 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e }; static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order) { unsigned mov_field_order = 0; if (field_order < FF_ARRAY_ELEMS(fiel_data)) mov_field_order = fiel_data[field_order]; else return 0; avio_wb32(pb, 10); ffio_wfourcc(pb, "fiel"); avio_wb16(pb, mov_field_order); return 10; } static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wl32(pb, track->tag); // store it byteswapped avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_write_esds_tag(pb, track); else if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); return update_size(pb, pos); } static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d) { int8_t stereo_mode; if (stereo_3d->flags != 0) { av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags); return 0; } switch (stereo_3d->type) { case AV_STEREO3D_2D: stereo_mode = 0; break; case AV_STEREO3D_TOPBOTTOM: stereo_mode = 1; break; case AV_STEREO3D_SIDEBYSIDE: stereo_mode = 2; break; default: av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type)); return 0; } avio_wb32(pb, 13); /* size */ ffio_wfourcc(pb, "st3d"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_w8(pb, stereo_mode); return 13; } static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping) { int64_t sv3d_pos, svhd_pos, proj_pos; const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT; if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR && spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE && spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) { av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection); return 0; } sv3d_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sv3d"); svhd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "svhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_put_str(pb, metadata_source); update_size(pb, svhd_pos); proj_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "proj"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "prhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->yaw); avio_wb32(pb, spherical_mapping->pitch); avio_wb32(pb, spherical_mapping->roll); switch (spherical_mapping->projection) { case AV_SPHERICAL_EQUIRECTANGULAR: case AV_SPHERICAL_EQUIRECTANGULAR_TILE: avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "equi"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->bound_top); avio_wb32(pb, spherical_mapping->bound_bottom); avio_wb32(pb, spherical_mapping->bound_left); avio_wb32(pb, spherical_mapping->bound_right); break; case AV_SPHERICAL_CUBEMAP: avio_wb32(pb, 20); /* size */ ffio_wfourcc(pb, "cbmp"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, 0); /* layout */ avio_wb32(pb, spherical_mapping->padding); /* padding */ break; } update_size(pb, proj_pos); return update_size(pb, sv3d_pos); } static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 40); ffio_wfourcc(pb, "clap"); avio_wb32(pb, track->par->width); /* apertureWidth_N */ avio_wb32(pb, 1); /* apertureWidth_D (= 1) */ avio_wb32(pb, track->height); /* apertureHeight_N */ avio_wb32(pb, 1); /* apertureHeight_D (= 1) */ avio_wb32(pb, 0); /* horizOff_N (= 0) */ avio_wb32(pb, 1); /* horizOff_D (= 1) */ avio_wb32(pb, 0); /* vertOff_N (= 0) */ avio_wb32(pb, 1); /* vertOff_D (= 1) */ return 40; } static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track) { AVRational sar; av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num, track->par->sample_aspect_ratio.den, INT_MAX); avio_wb32(pb, 16); ffio_wfourcc(pb, "pasp"); avio_wb32(pb, sar.num); avio_wb32(pb, sar.den); return 16; } static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma) { uint32_t gama = 0; if (gamma <= 0.0) { gamma = avpriv_get_gamma_from_trc(track->par->color_trc); } av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma); if (gamma > 1e-6) { gama = (uint32_t)lrint((double)(1<<16) * gamma); av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama); av_assert0(track->mode == MODE_MOV); avio_wb32(pb, 12); ffio_wfourcc(pb, "gama"); avio_wb32(pb, gama); return 12; } else { av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n"); } return 0; } static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track) { // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9 // Ref (MP4): ISO/IEC 14496-12:2012 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED && track->par->color_trc == AVCOL_TRC_UNSPECIFIED && track->par->color_space == AVCOL_SPC_UNSPECIFIED) { if ((track->par->width >= 1920 && track->par->height >= 1080) || (track->par->width == 1280 && track->par->height == 720)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n"); track->par->color_primaries = AVCOL_PRI_BT709; } else if (track->par->width == 720 && track->height == 576) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n"); track->par->color_primaries = AVCOL_PRI_BT470BG; } else if (track->par->width == 720 && (track->height == 486 || track->height == 480)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n"); track->par->color_primaries = AVCOL_PRI_SMPTE170M; } else { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n"); } switch (track->par->color_primaries) { case AVCOL_PRI_BT709: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_BT709; break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_BT470BG: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_SMPTE170M; break; } } /* We should only ever be called by MOV or MP4. */ av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4); avio_wb32(pb, 18 + (track->mode == MODE_MP4)); ffio_wfourcc(pb, "colr"); if (track->mode == MODE_MP4) ffio_wfourcc(pb, "nclx"); else ffio_wfourcc(pb, "nclc"); switch (track->par->color_primaries) { case AVCOL_PRI_BT709: avio_wb16(pb, 1); break; case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break; case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break; case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break; case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break; default: avio_wb16(pb, 2); } switch (track->par->color_trc) { case AVCOL_TRC_BT709: avio_wb16(pb, 1); break; case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break; case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break; case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break; default: avio_wb16(pb, 2); } switch (track->par->color_space) { case AVCOL_SPC_BT709: avio_wb16(pb, 1); break; case AVCOL_SPC_BT470BG: case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break; case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break; default: avio_wb16(pb, 2); } if (track->mode == MODE_MP4) { int full_range = track->par->color_range == AVCOL_RANGE_JPEG; avio_w8(pb, full_range << 7); return 19; } else { return 18; } } static void find_compressor(char * compressor_name, int len, MOVTrack *track) { AVDictionaryEntry *encoder; int xdcam_res = (track->par->width == 1280 && track->par->height == 720) || (track->par->width == 1440 && track->par->height == 1080) || (track->par->width == 1920 && track->par->height == 1080); if (track->mode == MODE_MOV && (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) { av_strlcpy(compressor_name, encoder->value, 32); } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) { int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(NULL, st); av_strlcatf(compressor_name, len, "XDCAM"); if (track->par->format == AV_PIX_FMT_YUV422P) { av_strlcatf(compressor_name, len, " HD422"); } else if(track->par->width == 1440) { av_strlcatf(compressor_name, len, " HD"); } else av_strlcatf(compressor_name, len, " EX"); av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p'); av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1)); } } static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); char compressor_name[32] = { 0 }; int avid = 0; int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422) || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422) || track->par->codec_id == AV_CODEC_ID_V308 || track->par->codec_id == AV_CODEC_ID_V408 || track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210); avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "encv"); } else { avio_wl32(pb, track->tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (uncompressed_ycbcr) { avio_wb16(pb, 2); /* Codec stream version */ } else { avio_wb16(pb, 0); /* Codec stream version */ } avio_wb16(pb, 0); /* Codec stream revision (=0) */ if (track->mode == MODE_MOV) { ffio_wfourcc(pb, "FFMP"); /* Vendor */ if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) { avio_wb32(pb, 0); /* Temporal Quality */ avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/ } else { avio_wb32(pb, 0x200); /* Temporal Quality = normal */ avio_wb32(pb, 0x200); /* Spatial Quality = normal */ } } else { avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ } avio_wb16(pb, track->par->width); /* Video width */ avio_wb16(pb, track->height); /* Video height */ avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */ avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */ avio_wb32(pb, 0); /* Data size (= 0) */ avio_wb16(pb, 1); /* Frame count (= 1) */ /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */ find_compressor(compressor_name, 32, track); avio_w8(pb, strlen(compressor_name)); avio_write(pb, compressor_name, 31); if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210)) avio_wb16(pb, 0x18); else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample) avio_wb16(pb, track->par->bits_per_coded_sample | (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0)); else avio_wb16(pb, 0x18); /* Reserved */ if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) { int pal_size = 1 << track->par->bits_per_coded_sample; int i; avio_wb16(pb, 0); /* Color table ID */ avio_wb32(pb, 0); /* Color table seed */ avio_wb16(pb, 0x8000); /* Color table flags */ avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */ for (i = 0; i < pal_size; i++) { uint32_t rgb = track->palette[i]; uint16_t r = (rgb >> 16) & 0xff; uint16_t g = (rgb >> 8) & 0xff; uint16_t b = rgb & 0xff; avio_wb16(pb, 0); avio_wb16(pb, (r << 8) | r); avio_wb16(pb, (g << 8) | g); avio_wb16(pb, (b << 8) | b); } } else avio_wb16(pb, 0xffff); /* Reserved */ if (track->tag == MKTAG('m','p','4','v')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H263) mov_write_d263_tag(pb); else if (track->par->codec_id == AV_CODEC_ID_AVUI || track->par->codec_id == AV_CODEC_ID_SVQ3) { mov_write_extradata_tag(pb, track); avio_wb32(pb, 0); } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) { mov_write_avid_tag(pb, track); avid = 1; } else if (track->par->codec_id == AV_CODEC_ID_HEVC) mov_write_hvcc_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) { mov_write_avcc_tag(pb, track); if (track->mode == MODE_IPOD) mov_write_uuid_tag_ipod(pb); } else if (track->par->codec_id == AV_CODEC_ID_VP9) { mov_write_vpcc_tag(mov->fc, pb, track); } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0) mov_write_dvc1_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_VP6F || track->par->codec_id == AV_CODEC_ID_VP6A) { /* Don't write any potential extradata here - the cropping * is signalled via the normal width/height fields. */ } else if (track->par->codec_id == AV_CODEC_ID_R10K) { if (track->par->codec_tag == MKTAG('R','1','0','k')) mov_write_dpxe_tag(pb, track); } else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->par->codec_id != AV_CODEC_ID_H264 && track->par->codec_id != AV_CODEC_ID_MPEG4 && track->par->codec_id != AV_CODEC_ID_DNXHD) { int field_order = track->par->field_order; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN) field_order = track->st->codec->field_order; FF_ENABLE_DEPRECATION_WARNINGS #endif if (field_order != AV_FIELD_UNKNOWN) mov_write_fiel_tag(pb, track, field_order); } if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) { if (track->mode == MODE_MOV) mov_write_gama_tag(pb, track, mov->gamma); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n"); } if (mov->flags & FF_MOV_FLAG_WRITE_COLR) { if (track->mode == MODE_MOV || track->mode == MODE_MP4) mov_write_colr_tag(pb, track); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n"); } if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) { AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL); AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL); if (stereo_3d) mov_write_st3d_tag(pb, stereo_3d); if (spherical_mapping) mov_write_sv3d_tag(mov->fc, pb, spherical_mapping); } if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) { mov_write_pasp_tag(pb, track); } if (uncompressed_ycbcr){ mov_write_clap_tag(pb, track); } if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } /* extra padding for avid stsd */ /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */ if (avid) avio_wb32(pb, 0); return update_size(pb, pos); } static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "rtp "); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb16(pb, 1); /* Hint track version */ avio_wb16(pb, 1); /* Highest compatible version */ avio_wb32(pb, track->max_packet_size); /* Max packet size */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "tims"); avio_wb32(pb, track->timescale); return update_size(pb, pos); } static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name) { uint64_t str_size =strlen(reel_name); int64_t pos = avio_tell(pb); if (str_size >= UINT16_MAX){ av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size); avio_wb16(pb, 0); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "name"); /* Data format */ avio_wb16(pb, str_size); /* string size */ avio_wb16(pb, track->language); /* langcode */ avio_write(pb, reel_name, str_size); /* reel name */ return update_size(pb,pos); } static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); #if 1 int frame_duration; int nb_frames; AVDictionaryEntry *t = NULL; if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) { #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den); nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num); FF_ENABLE_DEPRECATION_WARNINGS #else av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n"); return AVERROR(EINVAL); #endif } else { frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den); nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num); } if (nb_frames > 255) { av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ avio_wb32(pb, 0); /* Flags */ avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */ avio_wb32(pb, track->timescale); /* Timescale */ avio_wb32(pb, frame_duration); /* Frame duration */ avio_w8(pb, nb_frames); /* Number of frames */ avio_w8(pb, 0); /* Reserved */ t = av_dict_get(track->st->metadata, "reel_name", NULL, 0); if (t && utf8len(t->value) && track->mode != MODE_MP4) mov_write_source_reference_tag(pb, track, t->value); else avio_wb16(pb, 0); /* zero size */ #else avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); #endif return update_size(pb, pos); } static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb32(pb, 0); /* Reserved */ return update_size(pb, pos); } static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsd"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_video_tag(pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_audio_tag(s, pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) mov_write_subtitle_tag(pb, track); else if (track->par->codec_tag == MKTAG('r','t','p',' ')) mov_write_rtp_tag(pb, track); else if (track->par->codec_tag == MKTAG('t','m','c','d')) mov_write_tmcd_tag(pb, track); else if (track->par->codec_tag == MKTAG('g','p','m','d')) mov_write_gpmd_tag(pb, track); return update_size(pb, pos); } static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; MOVStts *ctts_entries; uint32_t entries = 0; uint32_t atom_size; int i; ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */ if (!ctts_entries) return AVERROR(ENOMEM); ctts_entries[0].count = 1; ctts_entries[0].duration = track->cluster[0].cts; for (i = 1; i < track->entry; i++) { if (track->cluster[i].cts == ctts_entries[entries].duration) { ctts_entries[entries].count++; /* compress */ } else { entries++; ctts_entries[entries].duration = track->cluster[i].cts; ctts_entries[entries].count = 1; } } entries++; /* last one */ atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "ctts"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, ctts_entries[i].count); avio_wb32(pb, ctts_entries[i].duration); } av_free(ctts_entries); return atom_size; } /* Time to sample atom */ static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track) { MOVStts *stts_entries = NULL; uint32_t entries = -1; uint32_t atom_size; int i; if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) { stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */ if (!stts_entries) return AVERROR(ENOMEM); stts_entries[0].count = track->sample_count; stts_entries[0].duration = 1; entries = 1; } else { if (track->entry) { stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */ if (!stts_entries) return AVERROR(ENOMEM); } for (i = 0; i < track->entry; i++) { int duration = get_cluster_duration(track, i); if (i && duration == stts_entries[entries].duration) { stts_entries[entries].count++; /* compress */ } else { entries++; stts_entries[entries].duration = duration; stts_entries[entries].count = 1; } } entries++; /* last one */ } atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "stts"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, stts_entries[i].count); avio_wb32(pb, stts_entries[i].duration); } av_free(stts_entries); return atom_size; } static int mov_write_dref_tag(AVIOContext *pb) { avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "dref"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ avio_wb32(pb, 0xc); /* size */ //FIXME add the alis and rsrc atom ffio_wfourcc(pb, "url "); avio_wb32(pb, 1); /* version & flags */ return 28; } static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track) { struct sgpd_entry { int count; int16_t roll_distance; int group_description_index; }; struct sgpd_entry *sgpd_entries = NULL; int entries = -1; int group = 0; int i, j; const int OPUS_SEEK_PREROLL_MS = 80; int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS, (AVRational){1, 1000}, (AVRational){1, 48000}); if (!track->entry) return 0; sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries)); if (!sgpd_entries) return AVERROR(ENOMEM); av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC); if (track->par->codec_id == AV_CODEC_ID_OPUS) { for (i = 0; i < track->entry; i++) { int roll_samples_remaining = roll_samples; int distance = 0; for (j = i - 1; j >= 0; j--) { roll_samples_remaining -= get_cluster_duration(track, j); distance++; if (roll_samples_remaining <= 0) break; } /* We don't have enough preceeding samples to compute a valid roll_distance here, so this sample can't be independently decoded. */ if (roll_samples_remaining > 0) distance = 0; /* Verify distance is a minimum of 2 (60ms) packets and a maximum of 32 (2.5ms) packets. */ av_assert0(distance == 0 || (distance >= 2 && distance <= 32)); if (i && distance == sgpd_entries[entries].roll_distance) { sgpd_entries[entries].count++; } else { entries++; sgpd_entries[entries].count = 1; sgpd_entries[entries].roll_distance = distance; sgpd_entries[entries].group_description_index = distance ? ++group : 0; } } } else { entries++; sgpd_entries[entries].count = track->sample_count; sgpd_entries[entries].roll_distance = 1; sgpd_entries[entries].group_description_index = ++group; } entries++; if (!group) { av_free(sgpd_entries); return 0; } /* Write sgpd tag */ avio_wb32(pb, 24 + (group * 2)); /* size */ ffio_wfourcc(pb, "sgpd"); avio_wb32(pb, 1 << 24); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, 2); /* default_length */ avio_wb32(pb, group); /* entry_count */ for (i = 0; i < entries; i++) { if (sgpd_entries[i].group_description_index) { avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */ } } /* Write sbgp tag */ avio_wb32(pb, 20 + (entries * 8)); /* size */ ffio_wfourcc(pb, "sbgp"); avio_wb32(pb, 0); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, entries); /* entry_count */ for (i = 0; i < entries; i++) { avio_wb32(pb, sgpd_entries[i].count); /* sample_count */ avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */ } av_free(sgpd_entries); return 0; } static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stbl"); mov_write_stsd_tag(s, pb, mov, track); mov_write_stts_tag(pb, track); if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_tag == MKTAG('r','t','p',' ')) && track->has_keyframes && track->has_keyframes < track->entry) mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable) mov_write_sdtp_tag(pb, track); if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS) mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->flags & MOV_TRACK_CTTS && track->entry) { if ((ret = mov_write_ctts_tag(s, pb, track)) < 0) return ret; } mov_write_stsc_tag(pb, track); mov_write_stsz_tag(pb, track); mov_write_stco_tag(pb, track); if (track->cenc.aes_ctr) { ff_mov_cenc_write_stbl_atoms(&track->cenc, pb); } if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) { mov_preroll_write_stbl_atoms(pb, track); } return update_size(pb, pos); } static int mov_write_dinf_tag(AVIOContext *pb) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "dinf"); mov_write_dref_tag(pb); return update_size(pb, pos); } static int mov_write_nmhd_tag(AVIOContext *pb) { avio_wb32(pb, 12); ffio_wfourcc(pb, "nmhd"); avio_wb32(pb, 0); return 12; } static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); const char *font = "Lucida Grande"; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* text font */ avio_wb16(pb, 0); /* text face */ avio_wb16(pb, 12); /* text size */ avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */ avio_wb16(pb, 0x0000); /* text color (red) */ avio_wb16(pb, 0x0000); /* text color (green) */ avio_wb16(pb, 0x0000); /* text color (blue) */ avio_wb16(pb, 0xffff); /* background color (red) */ avio_wb16(pb, 0xffff); /* background color (green) */ avio_wb16(pb, 0xffff); /* background color (blue) */ avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */ avio_write(pb, font, strlen(font)); /* font name */ return update_size(pb, pos); } static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gmhd"); avio_wb32(pb, 0x18); /* gmin size */ ffio_wfourcc(pb, "gmin");/* generic media info */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0x40); /* graphics mode = */ avio_wb16(pb, 0x8000); /* opColor (r?) */ avio_wb16(pb, 0x8000); /* opColor (g?) */ avio_wb16(pb, 0x8000); /* opColor (b?) */ avio_wb16(pb, 0); /* balance */ avio_wb16(pb, 0); /* reserved */ /* * This special text atom is required for * Apple Quicktime chapters. The contents * don't appear to be documented, so the * bytes are copied verbatim. */ if (track->tag != MKTAG('c','6','0','8')) { avio_wb32(pb, 0x2C); /* size */ ffio_wfourcc(pb, "text"); avio_wb16(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00004000); avio_wb16(pb, 0x0000); } if (track->par->codec_tag == MKTAG('t','m','c','d')) { int64_t tmcd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); mov_write_tcmi_tag(pb, track); update_size(pb, tmcd_pos); } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { int64_t gpmd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* version */ update_size(pb, gpmd_pos); } return update_size(pb, pos); } static int mov_write_smhd_tag(AVIOContext *pb) { avio_wb32(pb, 16); /* size */ ffio_wfourcc(pb, "smhd"); avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* reserved (balance, normally = 0) */ avio_wb16(pb, 0); /* reserved */ return 16; } static int mov_write_vmhd_tag(AVIOContext *pb) { avio_wb32(pb, 0x14); /* size (always 0x14) */ ffio_wfourcc(pb, "vmhd"); avio_wb32(pb, 0x01); /* version & flags */ avio_wb64(pb, 0); /* reserved (graphics mode = copy) */ return 0x14; } static int is_clcp_track(MOVTrack *track) { return track->tag == MKTAG('c','7','0','8') || track->tag == MKTAG('c','6','0','8'); } static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; const char *hdlr, *descr = NULL, *hdlr_type = NULL; int64_t pos = avio_tell(pb); hdlr = "dhlr"; hdlr_type = "url "; descr = "DataHandler"; if (track) { hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0"; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { hdlr_type = "vide"; descr = "VideoHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { hdlr_type = "soun"; descr = "SoundHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (is_clcp_track(track)) { hdlr_type = "clcp"; descr = "ClosedCaptionHandler"; } else { if (track->tag == MKTAG('t','x','3','g')) { hdlr_type = "sbtl"; } else if (track->tag == MKTAG('m','p','4','s')) { hdlr_type = "subp"; } else { hdlr_type = "text"; } descr = "SubtitleHandler"; } } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) { hdlr_type = "hint"; descr = "HintHandler"; } else if (track->par->codec_tag == MKTAG('t','m','c','d')) { hdlr_type = "tmcd"; descr = "TimeCodeHandler"; } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { hdlr_type = "meta"; descr = "GoPro MET"; // GoPro Metadata } else { av_log(s, AV_LOG_WARNING, "Unknown hldr_type for %s, writing dummy values\n", av_fourcc2str(track->par->codec_tag)); } if (track->st) { // hdlr.name is used by some players to identify the content title // of the track. So if an alternate handler description is // specified, use it. AVDictionaryEntry *t; t = av_dict_get(track->st->metadata, "handler_name", NULL, 0); if (t && utf8len(t->value)) descr = t->value; } } if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */ descr = ""; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); /* Version & flags */ avio_write(pb, hdlr, 4); /* handler */ ffio_wfourcc(pb, hdlr_type); /* handler type */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ if (!track || track->mode == MODE_MOV) avio_w8(pb, strlen(descr)); /* pascal string */ avio_write(pb, descr, strlen(descr)); /* handler description */ if (track && track->mode != MODE_MOV) avio_w8(pb, 0); /* c string */ return update_size(pb, pos); } static int mov_write_hmhd_tag(AVIOContext *pb) { /* This atom must be present, but leaving the values at zero * seems harmless. */ avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "hmhd"); avio_wb32(pb, 0); /* version, flags */ avio_wb16(pb, 0); /* maxPDUsize */ avio_wb16(pb, 0); /* avgPDUsize */ avio_wb32(pb, 0); /* maxbitrate */ avio_wb32(pb, 0); /* avgbitrate */ avio_wb32(pb, 0); /* reserved */ return 28; } static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "minf"); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_vmhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_smhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) { mov_write_gmhd_tag(pb, track); } else { mov_write_nmhd_tag(pb); } } else if (track->tag == MKTAG('r','t','p',' ')) { mov_write_hmhd_tag(pb); } else if (track->tag == MKTAG('t','m','c','d')) { if (track->mode != MODE_MOV) mov_write_nmhd_tag(pb); else mov_write_gmhd_tag(pb, track); } else if (track->tag == MKTAG('g','p','m','d')) { mov_write_gmhd_tag(pb, track); } if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */ mov_write_hdlr_tag(s, pb, NULL); mov_write_dinf_tag(pb); if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int version = track->track_duration < INT32_MAX ? 0 : 1; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, "mdhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */ avio_wb16(pb, track->language); /* language */ avio_wb16(pb, 0); /* reserved (quality) */ if (version != 0 && track->mode == MODE_MOV) { av_log(NULL, AV_LOG_ERROR, "FATAL error, file duration too long for timebase, this file will not be\n" "playable with quicktime. Choose a different timebase or a different\n" "container format\n"); } return 32; } static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "mdia"); mov_write_mdhd_tag(pb, mov, track); mov_write_hdlr_tag(s, pb, track); if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } /* transformation matrix |a b u| |c d v| |tx ty w| */ static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c, int16_t d, int16_t tx, int16_t ty) { avio_wb32(pb, a << 16); /* 16.16 format */ avio_wb32(pb, b << 16); /* 16.16 format */ avio_wb32(pb, 0); /* u in 2.30 format */ avio_wb32(pb, c << 16); /* 16.16 format */ avio_wb32(pb, d << 16); /* 16.16 format */ avio_wb32(pb, 0); /* v in 2.30 format */ avio_wb32(pb, tx << 16); /* 16.16 format */ avio_wb32(pb, ty << 16); /* 16.16 format */ avio_wb32(pb, 1 << 30); /* w in 2.30 format */ } static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int flags = MOV_TKHD_FLAG_IN_MOVIE; int rotation = 0; int group = 0; uint32_t *display_matrix = NULL; int display_matrix_size, i; if (st) { if (mov->per_stream_grouping) group = st->index; else group = st->codecpar->codec_type; display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &display_matrix_size); if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix)) display_matrix = NULL; } if (track->flags & MOV_TRACK_ENABLED) flags |= MOV_TKHD_FLAG_ENABLED; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */ ffio_wfourcc(pb, "tkhd"); avio_w8(pb, version); avio_wb24(pb, flags); if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->track_id); /* track-id */ avio_wb32(pb, 0); /* reserved */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb16(pb, 0); /* layer */ avio_wb16(pb, group); /* alternate group) */ /* Volume, only for audio */ if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_wb16(pb, 0x0100); else avio_wb16(pb, 0); avio_wb16(pb, 0); /* reserved */ /* Matrix structure */ #if FF_API_OLD_ROTATE_API if (st && st->metadata) { AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0); rotation = (rot && rot->value) ? atoi(rot->value) : 0; } #endif if (display_matrix) { for (i = 0; i < 9; i++) avio_wb32(pb, display_matrix[i]); #if FF_API_OLD_ROTATE_API } else if (rotation == 90) { write_matrix(pb, 0, 1, -1, 0, track->par->height, 0); } else if (rotation == 180) { write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height); } else if (rotation == 270) { write_matrix(pb, 0, -1, 1, 0, 0, track->par->width); #endif } else { write_matrix(pb, 1, 0, 0, 1, 0, 0); } /* Track width and height, for visual only */ if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) { int64_t track_width_1616; if (track->mode == MODE_MOV) { track_width_1616 = track->par->width * 0x10000ULL; } else { track_width_1616 = av_rescale(st->sample_aspect_ratio.num, track->par->width * 0x10000LL, st->sample_aspect_ratio.den); if (!track_width_1616 || track->height != track->par->height || track_width_1616 > UINT32_MAX) track_width_1616 = track->par->width * 0x10000ULL; } if (track_width_1616 > UINT32_MAX) { av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n"); track_width_1616 = 0; } avio_wb32(pb, track_width_1616); if (track->height > 0xFFFF) { av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n"); avio_wb32(pb, 0); } else avio_wb32(pb, track->height * 0x10000U); } else { avio_wb32(pb, 0); avio_wb32(pb, 0); } return 0x5c; } static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track) { int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width, track->par->sample_aspect_ratio.den); int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tapt"); avio_wb32(pb, 20); ffio_wfourcc(pb, "clef"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "prof"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "enof"); avio_wb32(pb, 0); avio_wb32(pb, track->par->width << 16); avio_wb32(pb, track->par->height << 16); return update_size(pb, pos); } // This box seems important for the psp playback ... without it the movie seems to hang static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int entry_size, entry_count, size; int64_t delay, start_ct = track->start_cts; int64_t start_dts = track->start_dts; if (track->entry) { if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) { av_log(mov->fc, AV_LOG_DEBUG, "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n", track->cluster[0].dts, track->cluster[0].cts, start_dts, start_ct, track->track_id); start_dts = track->cluster[0].dts; start_ct = track->cluster[0].cts; } } delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN); version |= delay < INT32_MAX ? 0 : 1; entry_size = (version == 1) ? 20 : 12; entry_count = 1 + (delay > 0); size = 24 + entry_count * entry_size; /* write the atom data */ avio_wb32(pb, size); ffio_wfourcc(pb, "edts"); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "elst"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entry_count); if (delay > 0) { /* add an empty edit to delay presentation */ /* In the positive delay case, the delay includes the cts * offset, and the second edit list entry below trims out * the same amount from the actual content. This makes sure * that the offset last sample is included in the edit * list duration as well. */ if (version == 1) { avio_wb64(pb, delay); avio_wb64(pb, -1); } else { avio_wb32(pb, delay); avio_wb32(pb, -1); } avio_wb32(pb, 0x00010000); } else { /* Avoid accidentally ending up with start_ct = -1 which has got a * special meaning. Normally start_ct should end up positive or zero * here, but use FFMIN in case dts is a small positive integer * rounded to 0 when represented in MOV_TIMESCALE units. */ av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0); start_ct = -FFMIN(start_dts, 0); /* Note, this delay is calculated from the pts of the first sample, * ensuring that we don't reduce the duration for cases with * dts<0 pts=0. */ duration += delay; } /* For fragmented files, we don't know the full length yet. Setting * duration to 0 allows us to only specify the offset, including * the rest of the content (from all future fragments) without specifying * an explicit duration. */ if (mov->flags & FF_MOV_FLAG_FRAGMENT) duration = 0; /* duration */ if (version == 1) { avio_wb64(pb, duration); avio_wb64(pb, start_ct); } else { avio_wb32(pb, duration); avio_wb32(pb, start_ct); } avio_wb32(pb, 0x00010000); return size; } static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 20); // size ffio_wfourcc(pb, "tref"); avio_wb32(pb, 12); // size (subatom) avio_wl32(pb, track->tref_tag); avio_wb32(pb, track->tref_id); return 20; } // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it) static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov) { avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x1c); // another size here! ffio_wfourcc(pb, "MTDT"); avio_wb32(pb, 0x00010012); avio_wb32(pb, 0x0a); avio_wb32(pb, 0x55c40000); avio_wb32(pb, 0x1); avio_wb32(pb, 0x0); return 0x34; } static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track) { AVFormatContext *ctx = track->rtp_ctx; char buf[1000] = ""; int len; ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track, NULL, NULL, 0, 0, ctx); av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id); len = strlen(buf); avio_wb32(pb, len + 24); ffio_wfourcc(pb, "udta"); avio_wb32(pb, len + 16); ffio_wfourcc(pb, "hnti"); avio_wb32(pb, len + 8); ffio_wfourcc(pb, "sdp "); avio_write(pb, buf, len); return len + 24; } static int mov_write_track_metadata(AVIOContext *pb, AVStream *st, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */ return update_size(pb, pos); } static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVStream *st) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; if (!st) return 0; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & (MODE_MP4|MODE_MOV)) mov_write_track_metadata(pb_buf, st, "name", "title"); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t pos = avio_tell(pb); int entry_backup = track->entry; int chunk_backup = track->chunkCount; int ret; /* If we want to have an empty moov, but some samples already have been * buffered (delay_moov), pretend that no samples have been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) track->chunkCount = track->entry = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "trak"); mov_write_tkhd_tag(pb, mov, track, st); av_assert2(mov->use_editlist >= 0); if (track->start_dts != AV_NOPTS_VALUE) { if (mov->use_editlist) mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track)) av_log(mov->fc, AV_LOG_WARNING, "Not writing any edit list even though one would have been required\n"); } if (track->tref_tag) mov_write_tref_tag(pb, track); if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0) return ret; if (track->mode == MODE_PSP) mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box if (track->tag == MKTAG('r','t','p',' ')) mov_write_udta_sdp(pb, track); if (track->mode == MODE_MOV) { if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio); if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) { mov_write_tapt_tag(pb, track); } } if (is_clcp_track(track) && st->sample_aspect_ratio.num) { mov_write_tapt_tag(pb, track); } } mov_write_track_udta_tag(pb, mov, st); track->entry = entry_backup; track->chunkCount = chunk_backup; return update_size(pb, pos); } static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov) { int i, has_audio = 0, has_video = 0; int64_t pos = avio_tell(pb); int audio_profile = mov->iods_audio_profile; int video_profile = mov->iods_video_profile; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO; has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO; } } if (audio_profile < 0) audio_profile = 0xFF - has_audio; if (video_profile < 0) video_profile = 0xFF - has_video; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "iods"); avio_wb32(pb, 0); /* version & flags */ put_descr(pb, 0x10, 7); avio_wb16(pb, 0x004f); avio_w8(pb, 0xff); avio_w8(pb, 0xff); avio_w8(pb, audio_profile); avio_w8(pb, video_profile); avio_w8(pb, 0xff); return update_size(pb, pos); } static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x20); /* size */ ffio_wfourcc(pb, "trex"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->track_id); /* track ID */ avio_wb32(pb, 1); /* default sample description index */ avio_wb32(pb, 0); /* default sample duration */ avio_wb32(pb, 0); /* default sample size */ avio_wb32(pb, 0); /* default sample flags */ return 0; } static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "mvex"); for (i = 0; i < mov->nb_streams; i++) mov_write_trex_tag(pb, &mov->tracks[i]); return update_size(pb, pos); } static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov) { int max_track_id = 1, i; int64_t max_track_len = 0; int version; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) { int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration, MOV_TIMESCALE, mov->tracks[i].timescale, AV_ROUND_UP); if (max_track_len < max_track_len_temp) max_track_len = max_track_len_temp; if (max_track_id < mov->tracks[i].track_id) max_track_id = mov->tracks[i].track_id; } } /* If using delay_moov, make sure the output is the same as if no * samples had been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { max_track_len = 0; max_track_id = 1; } version = max_track_len < UINT32_MAX ? 0 : 1; avio_wb32(pb, version == 1 ? 120 : 108); /* size */ ffio_wfourcc(pb, "mvhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, mov->time); avio_wb64(pb, mov->time); } else { avio_wb32(pb, mov->time); /* creation time */ avio_wb32(pb, mov->time); /* modification time */ } avio_wb32(pb, MOV_TIMESCALE); (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */ avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */ avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */ avio_wb16(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ /* Matrix structure */ write_matrix(pb, 1, 0, 0, 1, 0, 0); avio_wb32(pb, 0); /* reserved (preview time) */ avio_wb32(pb, 0); /* reserved (preview duration) */ avio_wb32(pb, 0); /* reserved (poster time) */ avio_wb32(pb, 0); /* reserved (selection time) */ avio_wb32(pb, 0); /* reserved (selection duration) */ avio_wb32(pb, 0); /* reserved (current time) */ avio_wb32(pb, max_track_id + 1); /* Next track id */ return 0x6c; } static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdir"); ffio_wfourcc(pb, "appl"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } /* helper function to write a data tag with the specified string as data */ static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style) { if (long_style) { int size = 16 + strlen(data); avio_wb32(pb, size); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 1); avio_wb32(pb, 0); avio_write(pb, data, strlen(data)); return size; } else { if (!lang) lang = ff_mov_iso639_to_lang("und", 1); avio_wb16(pb, strlen(data)); /* string length */ avio_wb16(pb, lang); avio_write(pb, data, strlen(data)); return strlen(data) + 4; } } static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style) { int size = 0; if (value && value[0]) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, name); mov_write_string_data_tag(pb, value, lang, long_style); size = update_size(pb, pos); } return size; } static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s, const char *tag, int *lang) { int l, len, len2; AVDictionaryEntry *t, *t2 = NULL; char tag2[16]; *lang = 0; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return NULL; len = strlen(t->key); snprintf(tag2, sizeof(tag2), "%s-", tag); while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) { len2 = strlen(t2->key); if (len2 == len + 4 && !strcmp(t->value, t2->value) && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) { *lang = l; return t; } } return t; } static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int long_style) { int lang; AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang); if (!t) return 0; return mov_write_string_tag(pb, name, t->value, lang, long_style); } /* iTunes bpm number */ static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0); int size = 0, tmpo = t ? atoi(t->value) : 0; if (tmpo) { size = 26; avio_wb32(pb, size); ffio_wfourcc(pb, "tmpo"); avio_wb32(pb, size-8); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); //type specifier avio_wb32(pb, 0); avio_wb16(pb, tmpo); // data } return size; } /* 3GPP TS 26.244 */ static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb) { int lang; int64_t pos = avio_tell(pb); double latitude, longitude, altitude; int32_t latitude_fix, longitude_fix, altitude_fix; AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang); const char *ptr, *place = ""; char *end; static const char *astronomical_body = "earth"; if (!t) return 0; ptr = t->value; longitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; latitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; altitude = strtod(ptr, &end); /* If no altitude was present, the default 0 should be fine */ if (*end == '/') place = end + 1; latitude_fix = (int32_t) ((1 << 16) * latitude); longitude_fix = (int32_t) ((1 << 16) * longitude); altitude_fix = (int32_t) ((1 << 16) * altitude); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "loci"); /* type */ avio_wb32(pb, 0); /* version + flags */ avio_wb16(pb, lang); avio_write(pb, place, strlen(place) + 1); avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */ avio_wb32(pb, latitude_fix); avio_wb32(pb, longitude_fix); avio_wb32(pb, altitude_fix); avio_write(pb, astronomical_body, strlen(astronomical_body) + 1); avio_w8(pb, 0); /* additional notes, null terminated string */ return update_size(pb, pos); } /* iTunes track or disc number */ static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s, int disc) { AVDictionaryEntry *t = av_dict_get(s->metadata, disc ? "disc" : "track", NULL, 0); int size = 0, track = t ? atoi(t->value) : 0; if (track) { int tracks = 0; char *slash = strchr(t->value, '/'); if (slash) tracks = atoi(slash + 1); avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, disc ? "disk" : "trkn"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0); // 8 bytes empty avio_wb32(pb, 0); avio_wb16(pb, 0); // empty avio_wb16(pb, track); // track / disc number avio_wb16(pb, tracks); // total track / disc number avio_wb16(pb, 0); // empty size = 32; } return size; } static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int len) { AVDictionaryEntry *t = NULL; uint8_t num; int size = 24 + len; if (len != 1 && len != 4) return -1; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return 0; num = atoi(t->value); avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); avio_wb32(pb, 0); if (len==4) avio_wb32(pb, num); else avio_w8 (pb, num); return size; } static int mov_write_covr(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = 0; int i; for (i = 0; i < s->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (!is_cover_image(trk->st) || trk->cover_image.size <= 0) continue; if (!pos) { pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "covr"); } avio_wb32(pb, 16 + trk->cover_image.size); ffio_wfourcc(pb, "data"); avio_wb32(pb, trk->tag); avio_wb32(pb , 0); avio_write(pb, trk->cover_image.data, trk->cover_image.size); } return pos ? update_size(pb, pos) : 0; } /* iTunes meta data list */ static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); mov_write_string_metadata(s, pb, "\251nam", "title" , 1); mov_write_string_metadata(s, pb, "\251ART", "artist" , 1); mov_write_string_metadata(s, pb, "aART", "album_artist", 1); mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1); mov_write_string_metadata(s, pb, "\251alb", "album" , 1); mov_write_string_metadata(s, pb, "\251day", "date" , 1); if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) { if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1); } mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1); mov_write_string_metadata(s, pb, "\251gen", "genre" , 1); mov_write_string_metadata(s, pb, "cprt", "copyright", 1); mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1); mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1); mov_write_string_metadata(s, pb, "desc", "description",1); mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1); mov_write_string_metadata(s, pb, "tvsh", "show" , 1); mov_write_string_metadata(s, pb, "tven", "episode_id",1); mov_write_string_metadata(s, pb, "tvnn", "network" , 1); mov_write_string_metadata(s, pb, "keyw", "keywords" , 1); mov_write_int8_metadata (s, pb, "tves", "episode_sort",4); mov_write_int8_metadata (s, pb, "tvsn", "season_number",4); mov_write_int8_metadata (s, pb, "stik", "media_type",1); mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1); mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1); mov_write_int8_metadata (s, pb, "cpil", "compilation", 1); mov_write_covr(pb, s); mov_write_trkn_tag(pb, mov, s, 0); // track number mov_write_trkn_tag(pb, mov, s, 1); // disc number mov_write_tmpo_tag(pb, s); return update_size(pb, pos); } static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdta"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int64_t curpos, entry_pos; int count = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "keys"); avio_wb32(pb, 0); entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* entry count */ while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { avio_wb32(pb, strlen(t->key) + 8); ffio_wfourcc(pb, "mdta"); avio_write(pb, t->key, strlen(t->key)); count += 1; } curpos = avio_tell(pb); avio_seek(pb, entry_pos, SEEK_SET); avio_wb32(pb, count); // rewrite entry count avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int count = 1; /* keys are 1-index based */ avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { int64_t entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wb32(pb, count); /* key */ mov_write_string_data_tag(pb, t->value, 0, 1); update_size(pb, entry_pos); count += 1; } return update_size(pb, pos); } /* meta data tags */ static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int size = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "meta"); avio_wb32(pb, 0); if (mov->flags & FF_MOV_FLAG_USE_MDTA) { mov_write_mdta_hdlr_tag(pb, mov, s); mov_write_mdta_keys_tag(pb, mov, s); mov_write_mdta_ilst_tag(pb, mov, s); } else { /* iTunes metadata tag */ mov_write_itunes_hdlr_tag(pb, mov, s); mov_write_ilst_tag(pb, mov, s); } size = update_size(pb, pos); return size; } static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb, const char *name, const char *key) { int len; AVDictionaryEntry *t; if (!(t = av_dict_get(s->metadata, key, NULL, 0))) return 0; len = strlen(t->value); if (len > 0) { int size = len + 8; avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_write(pb, t->value, len); return size; } return 0; } static int ascii_to_wc(AVIOContext *pb, const uint8_t *b) { int val; while (*b) { GET_UTF8(val, *b++, return -1;) avio_wb16(pb, val); } avio_wb16(pb, 0x00); return 0; } static uint16_t language_code(const char *str) { return (((str[0] - 0x60) & 0x1F) << 10) + (((str[1] - 0x60) & 0x1F) << 5) + (( str[2] - 0x60) & 0x1F); } static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_wb32(pb, 0); /* version + flags */ if (!strcmp(tag, "yrrc")) avio_wb16(pb, atoi(t->value)); else { avio_wb16(pb, language_code("eng")); /* language */ avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */ if (!strcmp(tag, "albm") && (t = av_dict_get(s->metadata, "track", NULL, 0))) avio_w8(pb, atoi(t->value)); } return update_size(pb, pos); } static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i, nb_chapters = FFMIN(s->nb_chapters, 255); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "chpl"); avio_wb32(pb, 0x01000000); // version + flags avio_wb32(pb, 0); // unknown avio_w8(pb, nb_chapters); for (i = 0; i < nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000})); if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { int len = FFMIN(strlen(t->value), 255); avio_w8(pb, len); avio_write(pb, t->value, len); } else avio_w8(pb, 0); } return update_size(pb, pos); } static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & MODE_3GP) { mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist"); mov_write_3gp_udta_tag(pb_buf, s, "titl", "title"); mov_write_3gp_udta_tag(pb_buf, s, "auth", "author"); mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre"); mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment"); mov_write_3gp_udta_tag(pb_buf, s, "albm", "album"); mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright"); mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date"); mov_write_loci_tag(s, pb_buf); } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0); mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0); mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0); mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0); mov_write_string_metadata(s, pb_buf, "\251day", "date", 0); mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0); // currently ignored by mov.c mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0); // add support for libquicktime, this atom is also actually read by mov.c mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0); mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0); mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0); mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0); mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0); mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0); mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0); mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp"); } else { /* iTunes meta data */ mov_write_meta_tag(pb_buf, mov, s); mov_write_loci_tag(s, pb_buf); } if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL)) mov_write_chpl_tag(pb_buf, s); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static void mov_write_psp_udta_tag(AVIOContext *pb, const char *str, const char *lang, int type) { int len = utf8len(str) + 1; if (len <= 0) return; avio_wb16(pb, len * 2 + 10); /* size */ avio_wb32(pb, type); /* type */ avio_wb16(pb, language_code(lang)); /* language */ avio_wb16(pb, 0x01); /* ? */ ascii_to_wc(pb, str); } static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0); int64_t pos, pos2; if (title) { pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); pos2 = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "MTDT"); avio_wb16(pb, 4); // ? avio_wb16(pb, 0x0C); /* size */ avio_wb32(pb, 0x0B); /* type */ avio_wb16(pb, language_code("und")); /* language */ avio_wb16(pb, 0x0); /* ? */ avio_wb16(pb, 0x021C); /* data */ if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04); mov_write_psp_udta_tag(pb, title->value, "eng", 0x01); mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03); update_size(pb, pos2); return update_size(pb, pos); } return 0; } static void build_chunks(MOVTrack *trk) { int i; MOVIentry *chunk = &trk->cluster[0]; uint64_t chunkSize = chunk->size; chunk->chunkNum = 1; if (trk->chunkCount) return; trk->chunkCount = 1; for (i = 1; i<trk->entry; i++){ if (chunk->pos + chunkSize == trk->cluster[i].pos && chunkSize + trk->cluster[i].size < (1<<20)){ chunkSize += trk->cluster[i].size; chunk->samples_in_chunk += trk->cluster[i].entries; } else { trk->cluster[i].chunkNum = chunk->chunkNum+1; chunk=&trk->cluster[i]; chunkSize = chunk->size; trk->chunkCount++; } } } /** * Assign track ids. If option "use_stream_ids_as_track_ids" is set, * the stream ids are used as track ids. * * This assumes mov->tracks and s->streams are in the same order and * there are no gaps in either of them (so mov->tracks[n] refers to * s->streams[n]). * * As an exception, there can be more entries in * s->streams than in mov->tracks, in which case new track ids are * generated (starting after the largest found stream id). */ static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s) { int i; if (mov->track_ids_ok) return 0; if (mov->use_stream_ids_as_track_ids) { int next_generated_track_id = 0; for (i = 0; i < s->nb_streams; i++) { if (s->streams[i]->id > next_generated_track_id) next_generated_track_id = s->streams[i]->id; } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id; } } else { for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i + 1; } } mov->track_ids_ok = 1; return 0; } static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int i; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "moov"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].time = mov->time; if (mov->tracks[i].entry) build_chunks(&mov->tracks[i]); } if (mov->chapter_track) for (i = 0; i < s->nb_streams; i++) { mov->tracks[i].tref_tag = MKTAG('c','h','a','p'); mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->tag == MKTAG('r','t','p',' ')) { track->tref_tag = MKTAG('h','i','n','t'); track->tref_id = mov->tracks[track->src_track].track_id; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { int * fallback, size; fallback = (int*)av_stream_get_side_data(track->st, AV_PKT_DATA_FALLBACK_TRACK, &size); if (fallback != NULL && size == sizeof(int)) { if (*fallback >= 0 && *fallback < mov->nb_streams) { track->tref_tag = MKTAG('f','a','l','l'); track->tref_id = mov->tracks[*fallback].track_id; } } } } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('t','m','c','d')) { int src_trk = mov->tracks[i].src_track; mov->tracks[src_trk].tref_tag = mov->tracks[i].tag; mov->tracks[src_trk].tref_id = mov->tracks[i].track_id; //src_trk may have a different timescale than the tmcd track mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration, mov->tracks[i].timescale, mov->tracks[src_trk].timescale); } } mov_write_mvhd_tag(pb, mov); if (mov->mode != MODE_MOV && !mov->iods_skip) mov_write_iods_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL); if (ret < 0) return ret; } } if (mov->flags & FF_MOV_FLAG_FRAGMENT) mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */ if (mov->mode == MODE_PSP) mov_write_uuidusmt_tag(pb, s); else mov_write_udta_tag(pb, mov, s); return update_size(pb, pos); } static void param_write_int(AVIOContext *pb, const char *name, int value) { avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value); } static void param_write_string(AVIOContext *pb, const char *name, const char *value) { avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value); } static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len) { char buf[150]; len = FFMIN(sizeof(buf) / 2 - 1, len); ff_data_to_hex(buf, value, len, 0); buf[2 * len] = '\0'; avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf); } static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i; int64_t manifest_bit_rate = 0; AVCPBProperties *props = NULL; static const uint8_t uuid[] = { 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd, 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }; avio_wb32(pb, 0); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_wb32(pb, 0); avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n"); avio_printf(pb, "<head>\n"); if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT)) avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n", LIBAVFORMAT_IDENT); avio_printf(pb, "</head>\n"); avio_printf(pb, "<body>\n"); avio_printf(pb, "<switch>\n"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; const char *type; int track_id = track->track_id; char track_name_buf[32] = { 0 }; AVStream *st = track->st; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) { type = "video"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { type = "audio"; } else { continue; } props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); if (track->par->bit_rate) { manifest_bit_rate = track->par->bit_rate; } else if (props) { manifest_bit_rate = props->max_bitrate; } avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type, manifest_bit_rate); param_write_int(pb, "systemBitrate", manifest_bit_rate); param_write_int(pb, "trackID", track_id); param_write_string(pb, "systemLanguage", lang ? lang->value : "und"); /* Build track name piece by piece: */ /* 1. track type */ av_strlcat(track_name_buf, type, sizeof(track_name_buf)); /* 2. track language, if available */ if (lang) av_strlcatf(track_name_buf, sizeof(track_name_buf), "_%s", lang->value); /* 3. special type suffix */ /* "_cc" = closed captions, "_ad" = audio_description */ if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf)); else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED) av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf)); param_write_string(pb, "trackName", track_name_buf); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->par->codec_id == AV_CODEC_ID_H264) { uint8_t *ptr; int size = track->par->extradata_size; if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr, &size)) { param_write_hex(pb, "CodecPrivateData", ptr ? ptr : track->par->extradata, size); av_free(ptr); } param_write_string(pb, "FourCC", "H264"); } else if (track->par->codec_id == AV_CODEC_ID_VC1) { param_write_string(pb, "FourCC", "WVC1"); param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); } param_write_int(pb, "MaxWidth", track->par->width); param_write_int(pb, "MaxHeight", track->par->height); param_write_int(pb, "DisplayWidth", track->par->width); param_write_int(pb, "DisplayHeight", track->par->height); } else { if (track->par->codec_id == AV_CODEC_ID_AAC) { switch (track->par->profile) { case FF_PROFILE_AAC_HE_V2: param_write_string(pb, "FourCC", "AACP"); break; case FF_PROFILE_AAC_HE: param_write_string(pb, "FourCC", "AACH"); break; default: param_write_string(pb, "FourCC", "AACL"); } } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) { param_write_string(pb, "FourCC", "WMAP"); } param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id)); param_write_int(pb, "Channels", track->par->channels); param_write_int(pb, "SamplingRate", track->par->sample_rate); param_write_int(pb, "BitsPerSample", 16); param_write_int(pb, "PacketSize", track->par->block_align ? track->par->block_align : 4); } avio_printf(pb, "</%s>\n", type); } avio_printf(pb, "</switch>\n"); avio_printf(pb, "</body>\n"); avio_printf(pb, "</smil>\n"); return update_size(pb, pos); } static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 16); ffio_wfourcc(pb, "mfhd"); avio_wb32(pb, 0); avio_wb32(pb, mov->fragments); return 0; } static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry) { return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO : (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC); } static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET; if (!track->entry) { flags |= MOV_TFHD_DURATION_IS_EMPTY; } else { flags |= MOV_TFHD_DEFAULT_FLAGS; } if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET) flags &= ~MOV_TFHD_BASE_DATA_OFFSET; if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) { flags &= ~MOV_TFHD_BASE_DATA_OFFSET; flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF; } /* Don't set a default sample size, the silverlight player refuses * to play files with that set. Don't set a default sample duration, * WMP freaks out if it is set. Don't set a base data offset, PIFF * file format says it MUST NOT be set. */ if (track->mode == MODE_ISM) flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET); avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfhd"); avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, track->track_id); /* track-id */ if (flags & MOV_TFHD_BASE_DATA_OFFSET) avio_wb64(pb, moof_offset); if (flags & MOV_TFHD_DEFAULT_DURATION) { track->default_duration = get_cluster_duration(track, 0); avio_wb32(pb, track->default_duration); } if (flags & MOV_TFHD_DEFAULT_SIZE) { track->default_size = track->entry ? track->cluster[0].size : 1; avio_wb32(pb, track->default_size); } else track->default_size = -1; if (flags & MOV_TFHD_DEFAULT_FLAGS) { /* Set the default flags based on the second sample, if available. * If the first sample is different, that can be signaled via a separate field. */ if (track->entry > 1) track->default_sample_flags = get_sample_flags(track, &track->cluster[1]); else track->default_sample_flags = track->par->codec_type == AVMEDIA_TYPE_VIDEO ? (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) : MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO; avio_wb32(pb, track->default_sample_flags); } return update_size(pb, pos); } static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int moof_size, int first, int end) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TRUN_DATA_OFFSET; int i; for (i = first; i < end; i++) { if (get_cluster_duration(track, i) != track->default_duration) flags |= MOV_TRUN_SAMPLE_DURATION; if (track->cluster[i].size != track->default_size) flags |= MOV_TRUN_SAMPLE_SIZE; if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags) flags |= MOV_TRUN_SAMPLE_FLAGS; } if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 && get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags) flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS; if (track->flags & MOV_TRACK_CTTS) flags |= MOV_TRUN_SAMPLE_CTS; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "trun"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, end - first); /* sample count */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) && !mov->first_trun) avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */ else avio_wb32(pb, moof_size + 8 + track->data_offset + track->cluster[first].pos); /* data offset */ if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[first])); for (i = first; i < end; i++) { if (flags & MOV_TRUN_SAMPLE_DURATION) avio_wb32(pb, get_cluster_duration(track, i)); if (flags & MOV_TRUN_SAMPLE_SIZE) avio_wb32(pb, track->cluster[i].size); if (flags & MOV_TRUN_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[i])); if (flags & MOV_TRUN_SAMPLE_CTS) avio_wb32(pb, track->cluster[i].cts); } mov->first_trun = 0; return update_size(pb, pos); } static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); static const uint8_t uuid[] = { 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6, 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2 }; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_wb64(pb, track->start_dts + track->frag_start + track->cluster[0].cts); avio_wb64(pb, track->end_pts - (track->cluster[0].dts + track->cluster[0].cts)); return update_size(pb, pos); } static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int entry) { int n = track->nb_frag_info - 1 - entry, i; int size = 8 + 16 + 4 + 1 + 16*n; static const uint8_t uuid[] = { 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95, 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f }; if (entry < 0) return 0; avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET); avio_wb32(pb, size); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_w8(pb, n); for (i = 0; i < n; i++) { int index = entry + 1 + i; avio_wb64(pb, track->frag_info[index].time); avio_wb64(pb, track->frag_info[index].duration); } if (n < mov->ism_lookahead) { int free_size = 16 * (mov->ism_lookahead - n); avio_wb32(pb, free_size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, free_size - 8); } return 0; } static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; for (i = 0; i < mov->ism_lookahead; i++) { /* Update the tfrf tag for the last ism_lookahead fragments, * nb_frag_info - 1 is the next fragment to be written. */ mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i); } avio_seek(pb, pos, SEEK_SET); return 0; } static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks, int size) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; MOVFragmentInfo *info; if ((tracks >= 0 && i != tracks) || !track->entry) continue; track->nb_frag_info++; if (track->nb_frag_info >= track->frag_info_capacity) { unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT; if (av_reallocp_array(&track->frag_info, new_capacity, sizeof(*track->frag_info))) return AVERROR(ENOMEM); track->frag_info_capacity = new_capacity; } info = &track->frag_info[track->nb_frag_info - 1]; info->offset = avio_tell(pb); info->size = size; // Try to recreate the original pts for the first packet // from the fields we have stored info->time = track->start_dts + track->frag_start + track->cluster[0].cts; info->duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); // If the pts is less than zero, we will have trimmed // away parts of the media track using an edit list, // and the corresponding start presentation time is zero. if (info->time < 0) { info->duration += info->time; info->time = 0; } info->tfrf_offset = 0; mov_write_tfrf_tags(pb, mov, track); } return 0; } static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if ((tracks >= 0 && i != tracks) || !track->entry) continue; if (track->nb_frag_info > max) { memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info)); track->nb_frag_info = max; } } } static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tfdt"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb64(pb, track->frag_start); return update_size(pb, pos); } static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset, int moof_size) { int64_t pos = avio_tell(pb); int i, start = 0; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "traf"); mov_write_tfhd_tag(pb, mov, track, moof_offset); if (mov->mode != MODE_ISM) mov_write_tfdt_tag(pb, track); for (i = 1; i < track->entry; i++) { if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) { mov_write_trun_tag(pb, mov, track, moof_size, start, i); start = i; } } mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry); if (mov->mode == MODE_ISM) { mov_write_tfxd_tag(pb, track); if (mov->ism_lookahead) { int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead; if (track->nb_frag_info > 0) { MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1]; if (!info->tfrf_offset) info->tfrf_offset = avio_tell(pb); } avio_wb32(pb, 8 + size); ffio_wfourcc(pb, "free"); for (i = 0; i < size; i++) avio_w8(pb, 0); } } return update_size(pb, pos); } static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov, int tracks, int moof_size) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "moof"); mov->first_trun = 1; mov_write_mfhd_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; if (!track->entry) continue; mov_write_traf_tag(pb, mov, track, pos, moof_size); } return update_size(pb, pos); } static int mov_write_sidx_tag(AVIOContext *pb, MOVTrack *track, int ref_size, int total_sidx_size) { int64_t pos = avio_tell(pb), offset_pos, end_pos; int64_t presentation_time, duration, offset; int starts_with_SAP, i, entries; if (track->entry) { entries = 1; presentation_time = track->start_dts + track->frag_start + track->cluster[0].cts; duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE; // pts<0 should be cut away using edts if (presentation_time < 0) { duration += presentation_time; presentation_time = 0; } } else { entries = track->nb_frag_info; if (entries <= 0) return 0; presentation_time = track->frag_info[0].time; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sidx"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); /* reference_ID */ avio_wb32(pb, track->timescale); /* timescale */ avio_wb64(pb, presentation_time); /* earliest_presentation_time */ offset_pos = avio_tell(pb); avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */ avio_wb16(pb, 0); /* reserved */ avio_wb16(pb, entries); /* reference_count */ for (i = 0; i < entries; i++) { if (!track->entry) { if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) { av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n"); } duration = track->frag_info[i].duration; ref_size = track->frag_info[i].size; starts_with_SAP = 1; } avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */ avio_wb32(pb, duration); /* subsegment_duration */ avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */ } end_pos = avio_tell(pb); offset = pos + total_sidx_size - end_pos; avio_seek(pb, offset_pos, SEEK_SET); avio_wb64(pb, offset); avio_seek(pb, end_pos, SEEK_SET); return update_size(pb, pos); } static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov, int tracks, int ref_size) { int i, round, ret; AVIOContext *avio_buf; int total_size = 0; for (round = 0; round < 2; round++) { // First run one round to calculate the total size of all // sidx atoms. // This would be much simpler if we'd only write one sidx // atom, for the first track in the moof. if (round == 0) { if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; } else { avio_buf = pb; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; // When writing a sidx for the full file, entry is 0, but // we want to include all tracks. ref_size is 0 in this case, // since we read it from frag_info instead. if (!track->entry && ref_size > 0) continue; total_size -= mov_write_sidx_tag(avio_buf, track, ref_size, total_size); } if (round == 0) total_size = ffio_close_null_buf(avio_buf); } return 0; } static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks) { int64_t pos = avio_tell(pb), pts_us, ntp_ts; MOVTrack *first_track; /* PRFT should be associated with at most one track. So, choosing only the * first track. */ if (tracks > 0) return 0; first_track = &(mov->tracks[0]); if (!first_track->entry) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n"); return 0; } if (first_track->cluster[0].pts == AV_NOPTS_VALUE) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n"); return 0; } if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) { ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time()); } else if (mov->write_prft == MOV_PRFT_SRC_PTS) { pts_us = av_rescale_q(first_track->cluster[0].pts, first_track->st->time_base, AV_TIME_BASE_Q); ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US); } else { av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n", mov->write_prft); return 0; } avio_wb32(pb, 0); // Size place holder ffio_wfourcc(pb, "prft"); // Type avio_w8(pb, 1); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, first_track->track_id); // reference track ID avio_wb64(pb, ntp_ts); // NTP time stamp avio_wb64(pb, first_track->cluster[0].pts); //media time return update_size(pb, pos); } static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks, int64_t mdat_size) { AVIOContext *avio_buf; int ret, moof_size; if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; mov_write_moof_tag_internal(avio_buf, mov, tracks, 0); moof_size = ffio_close_null_buf(avio_buf); if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size); if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB) mov_write_prft_tag(pb, mov, tracks); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX || !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) || mov->ism_lookahead) { if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0) return ret; if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) && mov->flags & FF_MOV_FLAG_SKIP_TRAILER) { mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1); } } return mov_write_moof_tag_internal(pb, mov, tracks, moof_size); } static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfra"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); avio_wb32(pb, 0); /* length of traf/trun/sample num */ avio_wb32(pb, track->nb_frag_info); for (i = 0; i < track->nb_frag_info; i++) { avio_wb64(pb, track->frag_info[i].time); avio_wb64(pb, track->frag_info[i].offset + track->data_offset); avio_w8(pb, 1); /* traf number */ avio_w8(pb, 1); /* trun number */ avio_w8(pb, 1); /* sample number */ } return update_size(pb, pos); } static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "mfra"); /* An empty mfra atom is enough to indicate to the publishing point that * the stream has ended. */ if (mov->flags & FF_MOV_FLAG_ISML) return update_size(pb, pos); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->nb_frag_info) mov_write_tfra_tag(pb, track); } avio_wb32(pb, 16); ffio_wfourcc(pb, "mfro"); avio_wb32(pb, 0); /* version + flags */ avio_wb32(pb, avio_tell(pb) + 4 - pos); return update_size(pb, pos); } static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 8); // placeholder for extended size field (64 bit) ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free"); mov->mdat_pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "mdat"); return 0; } /* TODO: This needs to be more general */ static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = avio_tell(pb); int has_h264 = 0, has_video = 0; int minor = 0x200; int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) has_video = 1; if (st->codecpar->codec_id == AV_CODEC_ID_H264) has_h264 = 1; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ftyp"); if (mov->major_brand && strlen(mov->major_brand) >= 4) ffio_wfourcc(pb, mov->major_brand); else if (mov->mode == MODE_3GP) { ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4"); minor = has_h264 ? 0x100 : 0x200; } else if (mov->mode & MODE_3G2) { ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a"); minor = has_h264 ? 0x20000 : 0x10000; } else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) ffio_wfourcc(pb, "iso4"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "isom"); else if (mov->mode == MODE_IPOD) ffio_wfourcc(pb, has_video ? "M4V ":"M4A "); else if (mov->mode == MODE_ISM) ffio_wfourcc(pb, "isml"); else if (mov->mode == MODE_F4V) ffio_wfourcc(pb, "f4v "); else ffio_wfourcc(pb, "qt "); avio_wb32(pb, minor); if (mov->mode == MODE_MOV) ffio_wfourcc(pb, "qt "); else if (mov->mode == MODE_ISM) { ffio_wfourcc(pb, "piff"); } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) { ffio_wfourcc(pb, "isom"); ffio_wfourcc(pb, "iso2"); if (has_h264) ffio_wfourcc(pb, "avc1"); } // We add tfdt atoms when fragmenting, signal this with the iso6 compatible // brand. This is compatible with users that don't understand tfdt. if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM) ffio_wfourcc(pb, "iso6"); if (mov->mode == MODE_3GP) ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4"); else if (mov->mode & MODE_3G2) ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a"); else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "mp41"); if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) ffio_wfourcc(pb, "dash"); return update_size(pb, pos); } static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s) { AVStream *video_st = s->streams[0]; AVCodecParameters *video_par = s->streams[0]->codecpar; AVCodecParameters *audio_par = s->streams[1]->codecpar; int audio_rate = audio_par->sample_rate; int64_t frame_rate = video_st->avg_frame_rate.den ? (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den : 0; int audio_kbitrate = audio_par->bit_rate / 1000; int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate); if (frame_rate < 0 || frame_rate > INT32_MAX) { av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000); return AVERROR(EINVAL); } avio_wb32(pb, 0x94); /* size */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "PROF"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x3); /* 3 sections ? */ avio_wb32(pb, 0x14); /* size */ ffio_wfourcc(pb, "FPRF"); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x2c); /* size */ ffio_wfourcc(pb, "APRF"); /* audio */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x2); /* TrackID */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0x20f); avio_wb32(pb, 0x0); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_rate); avio_wb32(pb, audio_par->channels); avio_wb32(pb, 0x34); /* size */ ffio_wfourcc(pb, "VPRF"); /* video */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x1); /* TrackID */ if (video_par->codec_id == AV_CODEC_ID_H264) { ffio_wfourcc(pb, "avc1"); avio_wb16(pb, 0x014D); avio_wb16(pb, 0x0015); } else { ffio_wfourcc(pb, "mp4v"); avio_wb16(pb, 0x0000); avio_wb16(pb, 0x0103); } avio_wb32(pb, 0x0); avio_wb32(pb, video_kbitrate); avio_wb32(pb, video_kbitrate); avio_wb32(pb, frame_rate); avio_wb32(pb, frame_rate); avio_wb16(pb, video_par->width); avio_wb16(pb, video_par->height); avio_wb32(pb, 0x010001); /* ? */ return 0; } static int mov_write_identification(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; mov_write_ftyp_tag(pb,s); if (mov->mode == MODE_PSP) { int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) video_streams_nb++; else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) audio_streams_nb++; else other_streams_nb++; } if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) { av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n"); return AVERROR(EINVAL); } return mov_write_uuidprof_tag(pb, s); } return 0; } static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags) { uint32_t c = -1; int i, closed_gop = 0; for (i = 0; i < pkt->size - 4; i++) { c = (c << 8) + pkt->data[i]; if (c == 0x1b8) { // gop closed_gop = pkt->data[i + 4] >> 6 & 0x01; } else if (c == 0x100) { // pic int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6); if (!temp_ref || closed_gop) // I picture is not reordered *flags = MOV_SYNC_SAMPLE; else *flags = MOV_PARTIAL_SYNC_SAMPLE; break; } } return 0; } static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk) { const uint8_t *start, *next, *end = pkt->data + pkt->size; int seq = 0, entry = 0; int key = pkt->flags & AV_PKT_FLAG_KEY; start = find_next_marker(pkt->data, end); for (next = start; next < end; start = next) { next = find_next_marker(start + 4, end); switch (AV_RB32(start)) { case VC1_CODE_SEQHDR: seq = 1; break; case VC1_CODE_ENTRYPOINT: entry = 1; break; case VC1_CODE_SLICE: trk->vc1_info.slices = 1; break; } } if (!trk->entry && trk->vc1_info.first_packet_seen) trk->vc1_info.first_frag_written = 1; if (!trk->entry && !trk->vc1_info.first_frag_written) { /* First packet in first fragment */ trk->vc1_info.first_packet_seq = seq; trk->vc1_info.first_packet_entry = entry; trk->vc1_info.first_packet_seen = 1; } else if ((seq && !trk->vc1_info.packet_seq) || (entry && !trk->vc1_info.packet_entry)) { int i; for (i = 0; i < trk->entry; i++) trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE; trk->has_keyframes = 0; if (seq) trk->vc1_info.packet_seq = 1; if (entry) trk->vc1_info.packet_entry = 1; if (!trk->vc1_info.first_frag_written) { /* First fragment */ if ((!seq || trk->vc1_info.first_packet_seq) && (!entry || trk->vc1_info.first_packet_entry)) { /* First packet had the same headers as this one, readd the * sync sample flag. */ trk->cluster[0].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes = 1; } } } if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry) key = seq && entry; else if (trk->vc1_info.packet_seq) key = seq; else if (trk->vc1_info.packet_entry) key = entry; if (key) { trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes++; } } static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; int ret, buf_size; uint8_t *buf; int i, offset; if (!track->mdat_buf) return 0; if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; offset = avio_tell(mov->mdat_buf); avio_write(mov->mdat_buf, buf, buf_size); av_free(buf); for (i = track->entries_flushed; i < track->entry; i++) track->cluster[i].pos += offset; track->entries_flushed = track->entry; return 0; } static int mov_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int i, first_track = -1; int64_t mdat_size = 0; int ret; int has_video = 0, starts_with_key = 0, first_video_track = 1; if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) return 0; // Try to fill in the duration of the last packet in each stream // from queued packets in the interleave queues. If the flushing // of fragments was triggered automatically by an AVPacket, we // already have reliable info for the end of that track, but other // tracks may need to be filled in. for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (!track->end_reliable) { AVPacket pkt; if (!ff_interleaved_peek(s, i, &pkt, 1)) { if (track->dts_shift != AV_NOPTS_VALUE) pkt.dts += track->dts_shift; track->track_duration = pkt.dts - track->start_dts; if (pkt.pts != AV_NOPTS_VALUE) track->end_pts = pkt.pts; else track->end_pts = pkt.dts; } } } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->entry <= 1) continue; // Sample durations are calculated as the diff of dts values, // but for the last sample in a fragment, we don't know the dts // of the first sample in the next fragment, so we have to rely // on what was set as duration in the AVPacket. Not all callers // set this though, so we might want to replace it with an // estimate if it currently is zero. if (get_cluster_duration(track, track->entry - 1) != 0) continue; // Use the duration (i.e. dts diff) of the second last sample for // the last one. This is a wild guess (and fatal if it turns out // to be too long), but probably the best we can do - having a zero // duration is bad as well. track->track_duration += get_cluster_duration(track, track->entry - 2); track->end_pts += get_cluster_duration(track, track->entry - 2); if (!mov->missing_duration_warned) { av_log(s, AV_LOG_WARNING, "Estimating the duration of the last packet in a " "fragment, consider setting the duration field in " "AVPacket instead.\n"); mov->missing_duration_warned = 1; } } if (!mov->moov_written) { int64_t pos = avio_tell(s->pb); uint8_t *buf; int buf_size, moov_size; for (i = 0; i < mov->nb_streams; i++) if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st)) break; /* Don't write the initial moov unless all tracks have data */ if (i < mov->nb_streams && !force) return 0; moov_size = get_moov_size(s); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = pos + moov_size + 8; avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER); if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov_write_identification(s->pb, s); if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) { if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); avio_flush(s->pb); mov->moov_written = 1; return 0; } buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; avio_wb32(s->pb, buf_size + 8); ffio_wfourcc(s->pb, "mdat"); avio_write(s->pb, buf, buf_size); av_free(buf); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); mov->moov_written = 1; mov->mdat_size = 0; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry) mov->tracks[i].frag_start += mov->tracks[i].start_dts + mov->tracks[i].track_duration - mov->tracks[i].cluster[0].dts; mov->tracks[i].entry = 0; mov->tracks[i].end_reliable = 0; } avio_flush(s->pb); return 0; } if (mov->frag_interleave) { for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int ret; if ((ret = mov_flush_fragment_interleaving(s, track)) < 0) return ret; } if (!mov->mdat_buf) return 0; mdat_size = avio_tell(mov->mdat_buf); } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave) track->data_offset = 0; else track->data_offset = mdat_size; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { has_video = 1; if (first_video_track) { if (track->entry) starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE; first_video_track = 0; } } if (!track->entry) continue; if (track->mdat_buf) mdat_size += avio_tell(track->mdat_buf); if (first_track < 0) first_track = i; } if (!mdat_size) return 0; avio_write_marker(s->pb, av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale), (has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int buf_size, write_moof = 1, moof_tracks = -1; uint8_t *buf; int64_t duration = 0; if (track->entry) duration = track->start_dts + track->track_duration - track->cluster[0].dts; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) { if (!track->mdat_buf) continue; mdat_size = avio_tell(track->mdat_buf); moof_tracks = i; } else { write_moof = i == first_track; } if (write_moof) { avio_flush(s->pb); mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size); mov->fragments++; avio_wb32(s->pb, mdat_size + 8); ffio_wfourcc(s->pb, "mdat"); } if (track->entry) track->frag_start += duration; track->entry = 0; track->entries_flushed = 0; track->end_reliable = 0; if (!mov->frag_interleave) { if (!track->mdat_buf) continue; buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; } else { if (!mov->mdat_buf) continue; buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; } avio_write(s->pb, buf, buf_size); av_free(buf); } mov->mdat_size = 0; avio_flush(s->pb); return 0; } static int mov_auto_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int had_moov = mov->moov_written; int ret = mov_flush_fragment(s, force); if (ret < 0) return ret; // If using delay_moov, the first flush only wrote the moov, // not the actual moof+mdat pair, thus flush once again. if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV) ret = mov_flush_fragment(s, force); return ret; } static int check_pkt(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; int64_t ref; uint64_t duration; if (trk->entry) { ref = trk->cluster[trk->entry - 1].dts; } else if ( trk->start_dts != AV_NOPTS_VALUE && !trk->frag_discont) { ref = trk->start_dts + trk->track_duration; } else ref = pkt->dts; // Skip tests for the first packet if (trk->dts_shift != AV_NOPTS_VALUE) { /* With negative CTS offsets we have set an offset to the DTS, * reverse this for the check. */ ref -= trk->dts_shift; } duration = pkt->dts - ref; if (pkt->dts < ref || duration >= INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n", duration, pkt->dts ); pkt->dts = ref + 1; pkt->pts = AV_NOPTS_VALUE; } if (pkt->duration < 0 || pkt->duration > INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration); return AVERROR(EINVAL); } return 0; } int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; unsigned int samples_in_chunk = 0; int size = pkt->size, ret = 0; uint8_t *reformatted_data = NULL; ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret; if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { if (mov->frag_interleave && mov->fragments > 0) { if (trk->entry - trk->entries_flushed >= mov->frag_interleave) { if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0) return ret; } } if (!trk->mdat_buf) { if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0) return ret; } pb = trk->mdat_buf; } else { if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } pb = mov->mdat_buf; } } if (par->codec_id == AV_CODEC_ID_AMR_NB) { /* We must find out how many AMR blocks there are in one packet */ static const uint16_t packed_size[16] = {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1}; int len = 0; while (len < size && samples_in_chunk < 100) { len += packed_size[(pkt->data[len] >> 3) & 0x0F]; samples_in_chunk++; } if (samples_in_chunk > 1) { av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n"); return -1; } } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS || par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { samples_in_chunk = trk->par->frame_size; } else if (trk->sample_size) samples_in_chunk = size / trk->sample_size; else samples_in_chunk = 1; if (samples_in_chunk < 1) { av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n"); return AVERROR_PATCHWELCOME; } /* copy extradata if it exists */ if (trk->vos_len == 0 && par->extradata_size > 0 && !TAG_IS_AVCI(trk->tag) && (par->codec_id != AV_CODEC_ID_DNXHD)) { trk->vos_len = par->extradata_size; trk->vos_data = av_malloc(trk->vos_len); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, par->extradata, trk->vos_len); } if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return -1; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) { /* from x264 or from bytestream H.264 */ /* NAL reformatting needed */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data, &size); avio_write(pb, reformatted_data, size); } else { if (trk->cenc.aes_ctr) { size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size); if (size < 0) { ret = size; goto err; } } else { size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size); } } } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 && (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) { /* extradata is Annex B, assume the bitstream is too and convert it */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL); avio_write(pb, reformatted_data, size); } else { size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL); } #if CONFIG_AC3_PARSER } else if (par->codec_id == AV_CODEC_ID_EAC3) { size = handle_eac3(mov, pkt, trk); if (size < 0) return size; else if (!size) goto end; avio_write(pb, pkt->data, size); #endif } else { if (trk->cenc.aes_ctr) { if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) { int nal_size_length = (par->extradata[4] & 0x3) + 1; ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size); } else { ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size); } if (ret) { goto err; } } else { avio_write(pb, pkt->data, size); } } if ((par->codec_id == AV_CODEC_ID_DNXHD || par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) { /* copy frame to create needed atoms */ trk->vos_len = size; trk->vos_data = av_malloc(size); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, pkt->data, size); } if (trk->entry >= trk->cluster_capacity) { unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE); if (av_reallocp_array(&trk->cluster, new_capacity, sizeof(*trk->cluster))) { ret = AVERROR(ENOMEM); goto err; } trk->cluster_capacity = new_capacity; } trk->cluster[trk->entry].pos = avio_tell(pb) - size; trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk; trk->cluster[trk->entry].chunkNum = 0; trk->cluster[trk->entry].size = size; trk->cluster[trk->entry].entries = samples_in_chunk; trk->cluster[trk->entry].dts = pkt->dts; trk->cluster[trk->entry].pts = pkt->pts; if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) { if (!trk->frag_discont) { /* First packet of a new fragment. We already wrote the duration * of the last packet of the previous fragment based on track_duration, * which might not exactly match our dts. Therefore adjust the dts * of this packet to be what the previous packets duration implies. */ trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration; /* We also may have written the pts and the corresponding duration * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with * the next fragment. This means the cts of the first sample must * be the same in all fragments, unless end_pts was updated by * the packet causing the fragment to be written. */ if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) || mov->mode == MODE_ISM) pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts; } else { /* New fragment, but discontinuous from previous fragments. * Pretend the duration sum of the earlier fragments is * pkt->dts - trk->start_dts. */ trk->frag_start = pkt->dts - trk->start_dts; trk->end_pts = AV_NOPTS_VALUE; trk->frag_discont = 0; } } if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) { /* Not using edit lists and shifting the first track to start from zero. * If the other streams start from a later timestamp, we won't be able * to signal the difference in starting time without an edit list. * Thus move the timestamp for this first sample to 0, increasing * its duration instead. */ trk->cluster[trk->entry].dts = trk->start_dts = 0; } if (trk->start_dts == AV_NOPTS_VALUE) { trk->start_dts = pkt->dts; if (trk->frag_discont) { if (mov->use_editlist) { /* Pretend the whole stream started at pts=0, with earlier fragments * already written. If the stream started at pts=0, the duration sum * of earlier fragments would have been pkt->pts. */ trk->frag_start = pkt->pts; trk->start_dts = pkt->dts - pkt->pts; } else { /* Pretend the whole stream started at dts=0, with earlier fragments * already written, with a duration summing up to pkt->dts. */ trk->frag_start = pkt->dts; trk->start_dts = 0; } trk->frag_discont = 0; } else if (pkt->dts && mov->moov_written) av_log(s, AV_LOG_WARNING, "Track %d starts with a nonzero dts %"PRId64", while the moov " "already has been written. Set the delay_moov flag to handle " "this case.\n", pkt->stream_index, pkt->dts); } trk->track_duration = pkt->dts - trk->start_dts + pkt->duration; trk->last_sample_is_subtitle_end = 0; if (pkt->pts == AV_NOPTS_VALUE) { av_log(s, AV_LOG_WARNING, "pts has no value\n"); pkt->pts = pkt->dts; } if (pkt->dts != pkt->pts) trk->flags |= MOV_TRACK_CTTS; trk->cluster[trk->entry].cts = pkt->pts - pkt->dts; trk->cluster[trk->entry].flags = 0; if (trk->start_cts == AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; if (trk->end_pts == AV_NOPTS_VALUE) trk->end_pts = trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration; else trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration); if (par->codec_id == AV_CODEC_ID_VC1) { mov_parse_vc1_frame(pkt, trk); } else if (pkt->flags & AV_PKT_FLAG_KEY) { if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO && trk->entry > 0) { // force sync sample for the first key frame mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags); if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE) trk->flags |= MOV_TRACK_STPS; } else { trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE; } if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE) trk->has_keyframes++; } if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) { trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE; trk->has_disposable++; } trk->entry++; trk->sample_count += samples_in_chunk; mov->mdat_size += size; if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry, reformatted_data, size); end: err: av_free(reformatted_data); return ret; } static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; int64_t frag_duration = 0; int size = pkt->size; int ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) { int i; for (i = 0; i < s->nb_streams; i++) mov->tracks[i].frag_discont = 1; mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT; } if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) { if (trk->dts_shift == AV_NOPTS_VALUE) trk->dts_shift = pkt->pts - pkt->dts; pkt->dts += trk->dts_shift; } if (trk->par->codec_id == AV_CODEC_ID_MP4ALS || trk->par->codec_id == AV_CODEC_ID_AAC || trk->par->codec_id == AV_CODEC_ID_FLAC) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!newextra) return AVERROR(ENOMEM); av_free(par->extradata); par->extradata = newextra; memcpy(par->extradata, side, side_size); par->extradata_size = side_size; if (!pkt->size) // Flush packet mov->need_rewrite_extradata = 1; } } if (!pkt->size) { if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) { trk->start_dts = pkt->dts; if (pkt->pts != AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; else trk->start_cts = 0; } return 0; /* Discard 0 sized packets */ } if (trk->entry && pkt->stream_index < s->nb_streams) frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q); if ((mov->max_fragment_duration && frag_duration >= mov->max_fragment_duration) || (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) || (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME && par->codec_type == AVMEDIA_TYPE_VIDEO && trk->entry && pkt->flags & AV_PKT_FLAG_KEY) || (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) { if (frag_duration >= mov->min_fragment_duration) { // Set the duration of this track to line up with the next // sample in this track. This avoids relying on AVPacket // duration, but only helps for this particular track, not // for the other ones that are flushed at the same time. trk->track_duration = pkt->dts - trk->start_dts; if (pkt->pts != AV_NOPTS_VALUE) trk->end_pts = pkt->pts; else trk->end_pts = pkt->dts; trk->end_reliable = 1; mov_auto_flush_fragment(s, 0); } } return ff_mov_write_packet(s, pkt); } static int mov_write_subtitle_end_packet(AVFormatContext *s, int stream_index, int64_t dts) { AVPacket end; uint8_t data[2] = {0}; int ret; av_init_packet(&end); end.size = sizeof(data); end.data = data; end.pts = dts; end.dts = dts; end.duration = 0; end.stream_index = stream_index; ret = mov_write_single_packet(s, &end); av_packet_unref(&end); return ret; } static int mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk; if (!pkt) { mov_flush_fragment(s, 1); return 1; } trk = &mov->tracks[pkt->stream_index]; if (is_cover_image(trk->st)) { int ret; if (trk->st->nb_frames >= 1) { if (trk->st->nb_frames == 1) av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d," " ignoring.\n", pkt->stream_index); return 0; } if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0) return ret; return 0; } else { int i; if (!pkt->size) return mov_write_single_packet(s, pkt); /* Passthrough. */ /* * Subtitles require special handling. * * 1) For full complaince, every track must have a sample at * dts == 0, which is rarely true for subtitles. So, as soon * as we see any packet with dts > 0, write an empty subtitle * at dts == 0 for any subtitle track with no samples in it. * * 2) For each subtitle track, check if the current packet's * dts is past the duration of the last subtitle sample. If * so, we now need to write an end sample for that subtitle. * * This must be done conditionally to allow for subtitles that * immediately replace each other, in which case an end sample * is not needed, and is, in fact, actively harmful. * * 3) See mov_write_trailer for how the final end sample is * handled. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; int ret; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && trk->track_duration < pkt->dts && (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) { ret = mov_write_subtitle_end_packet(s, i, trk->track_duration); if (ret < 0) return ret; trk->last_sample_is_subtitle_end = 1; } } if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) { AVPacket *opkt = pkt; int reshuffle_ret, ret; if (trk->is_unaligned_qt_rgb) { int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16; int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2; reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride); if (reshuffle_ret < 0) return reshuffle_ret; } else reshuffle_ret = 0; if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) { ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette); if (ret < 0) goto fail; if (ret) trk->pal_done++; } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO && (trk->par->format == AV_PIX_FMT_GRAY8 || trk->par->format == AV_PIX_FMT_MONOBLACK)) { for (i = 0; i < pkt->size; i++) pkt->data[i] = ~pkt->data[i]; } if (reshuffle_ret) { ret = mov_write_single_packet(s, pkt); fail: if (reshuffle_ret) av_packet_free(&pkt); return ret; } } return mov_write_single_packet(s, pkt); } } // QuickTime chapters involve an additional text track with the chapter names // as samples, and a tref pointing from the other tracks to the chapter one. static int mov_create_chapter_track(AVFormatContext *s, int tracknum) { AVIOContext *pb; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[tracknum]; AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY }; int i, len; track->mode = mov->mode; track->tag = MKTAG('t','e','x','t'); track->timescale = MOV_TIMESCALE; track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_SUBTITLE; #if 0 // These properties are required to make QT recognize the chapter track uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, }; if (ff_alloc_extradata(track->par, sizeof(chapter_properties))) return AVERROR(ENOMEM); memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties)); #else if (avio_open_dyn_buf(&pb) >= 0) { int size; uint8_t *buf; /* Stub header (usually for Quicktime chapter track) */ // TextSampleEntry avio_wb32(pb, 0x01); // displayFlags avio_w8(pb, 0x00); // horizontal justification avio_w8(pb, 0x00); // vertical justification avio_w8(pb, 0x00); // bgColourRed avio_w8(pb, 0x00); // bgColourGreen avio_w8(pb, 0x00); // bgColourBlue avio_w8(pb, 0x00); // bgColourAlpha // BoxRecord avio_wb16(pb, 0x00); // defTextBoxTop avio_wb16(pb, 0x00); // defTextBoxLeft avio_wb16(pb, 0x00); // defTextBoxBottom avio_wb16(pb, 0x00); // defTextBoxRight // StyleRecord avio_wb16(pb, 0x00); // startChar avio_wb16(pb, 0x00); // endChar avio_wb16(pb, 0x01); // fontID avio_w8(pb, 0x00); // fontStyleFlags avio_w8(pb, 0x00); // fontSize avio_w8(pb, 0x00); // fgColourRed avio_w8(pb, 0x00); // fgColourGreen avio_w8(pb, 0x00); // fgColourBlue avio_w8(pb, 0x00); // fgColourAlpha // FontTableBox avio_wb32(pb, 0x0D); // box size ffio_wfourcc(pb, "ftab"); // box atom name avio_wb16(pb, 0x01); // entry count // FontRecord avio_wb16(pb, 0x01); // font ID avio_w8(pb, 0x00); // font name length if ((size = avio_close_dyn_buf(pb, &buf)) > 0) { track->par->extradata = buf; track->par->extradata_size = size; } else { av_freep(&buf); } } #endif for (i = 0; i < s->nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.duration = end - pkt.dts; if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { static const char encd[12] = { 0x00, 0x00, 0x00, 0x0C, 'e', 'n', 'c', 'd', 0x00, 0x00, 0x01, 0x00 }; len = strlen(t->value); pkt.size = len + 2 + 12; pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB16(pkt.data, len); memcpy(pkt.data + 2, t->value, len); memcpy(pkt.data + len + 2, encd, sizeof(encd)); ff_mov_write_packet(s, &pkt); av_freep(&pkt.data); } } return 0; } static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr) { int ret; /* compute the frame number */ ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s); return ret; } static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc) { int ret; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[index]; AVStream *src_st = s->streams[src_index]; AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4}; AVRational rate = find_fps(s, src_st); /* tmcd track based on video stream */ track->mode = mov->mode; track->tag = MKTAG('t','m','c','d'); track->src_track = src_index; track->timescale = mov->tracks[src_index].timescale; if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME) track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME; /* set st to src_st for metadata access*/ track->st = src_st; /* encode context: tmcd data stream */ track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_DATA; track->par->codec_tag = track->tag; track->st->avg_frame_rate = av_inv_q(rate); /* the tmcd track just contains one packet with the frame number */ pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB32(pkt.data, tc.start); ret = ff_mov_write_packet(s, &pkt); av_free(pkt.data); return ret; } /* * st->disposition controls the "enabled" flag in the tkhd tag. * QuickTime will not play a track if it is not enabled. So make sure * that one track of each type (audio, video, subtitle) is enabled. * * Subtitles are special. For audio and video, setting "enabled" also * makes the track "default" (i.e. it is rendered when played). For * subtitles, an "enabled" subtitle is not rendered by default, but * if no subtitle is enabled, the subtitle menu in QuickTime will be * empty! */ static void enable_tracks(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; int enabled[AVMEDIA_TYPE_NB]; int first[AVMEDIA_TYPE_NB]; for (i = 0; i < AVMEDIA_TYPE_NB; i++) { enabled[i] = 0; first[i] = -1; } for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN || st->codecpar->codec_type >= AVMEDIA_TYPE_NB || is_cover_image(st)) continue; if (first[st->codecpar->codec_type] < 0) first[st->codecpar->codec_type] = i; if (st->disposition & AV_DISPOSITION_DEFAULT) { mov->tracks[i].flags |= MOV_TRACK_ENABLED; enabled[st->codecpar->codec_type]++; } } for (i = 0; i < AVMEDIA_TYPE_NB; i++) { switch (i) { case AVMEDIA_TYPE_VIDEO: case AVMEDIA_TYPE_AUDIO: case AVMEDIA_TYPE_SUBTITLE: if (enabled[i] > 1) mov->per_stream_grouping = 1; if (!enabled[i] && first[i] >= 0) mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED; break; } } } static void mov_free(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; if (mov->chapter_track) { if (mov->tracks[mov->chapter_track].par) av_freep(&mov->tracks[mov->chapter_track].par->extradata); av_freep(&mov->tracks[mov->chapter_track].par); } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) ff_mov_close_hinting(&mov->tracks[i]); else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd) av_freep(&mov->tracks[i].par); av_freep(&mov->tracks[i].cluster); av_freep(&mov->tracks[i].frag_info); av_packet_unref(&mov->tracks[i].cover_image); if (mov->tracks[i].vos_len) av_freep(&mov->tracks[i].vos_data); ff_mov_cenc_free(&mov->tracks[i].cenc); } av_freep(&mov->tracks); } static uint32_t rgb_to_yuv(uint32_t rgb) { uint8_t r, g, b; int y, cb, cr; r = (rgb >> 16) & 0xFF; g = (rgb >> 8) & 0xFF; b = (rgb ) & 0xFF; y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000); cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000); cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000); return (y << 16) | (cr << 8) | cb; } static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track, AVStream *st) { int i, width = 720, height = 480; int have_palette = 0, have_size = 0; uint32_t palette[16]; char *cur = st->codecpar->extradata; while (cur && *cur) { if (strncmp("palette:", cur, 8) == 0) { int i, count; count = sscanf(cur + 8, "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"", &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3], &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7], &palette[ 8], &palette[ 9], &palette[10], &palette[11], &palette[12], &palette[13], &palette[14], &palette[15]); for (i = 0; i < count; i++) { palette[i] = rgb_to_yuv(palette[i]); } have_palette = 1; } else if (!strncmp("size:", cur, 5)) { sscanf(cur + 5, "%dx%d", &width, &height); have_size = 1; } if (have_palette && have_size) break; cur += strcspn(cur, "\n\r"); cur += strspn(cur, "\n\r"); } if (have_palette) { track->vos_data = av_malloc(16*4); if (!track->vos_data) return AVERROR(ENOMEM); for (i = 0; i < 16; i++) { AV_WB32(track->vos_data + i * 4, palette[i]); } track->vos_len = 16 * 4; } st->codecpar->width = width; st->codecpar->height = track->height = height; return 0; } static int mov_init(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret; mov->fc = s; /* Default mode == MP4 */ mov->mode = MODE_MP4; if (s->oformat) { if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP; else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2; else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV; else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP; else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD; else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM; else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V; } if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV; /* Set the FRAGMENT flag if any of the fragmentation methods are * enabled. */ if (mov->max_fragment_duration || mov->max_fragment_size || mov->flags & (FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) mov->flags |= FF_MOV_FLAG_FRAGMENT; /* Set other implicit flags immediately */ if (mov->mode == MODE_ISM) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF | FF_MOV_FLAG_FRAGMENT; if (mov->flags & FF_MOV_FLAG_DASH) mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_DEFAULT_BASE_MOOF; if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) { av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n"); s->flags &= ~AVFMT_FLAG_AUTO_BSF; } if (mov->flags & FF_MOV_FLAG_FASTSTART) { mov->reserved_moov_size = -1; } if (mov->use_editlist < 0) { mov->use_editlist = 1; if (mov->flags & FF_MOV_FLAG_FRAGMENT && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { // If we can avoid needing an edit list by shifting the // tracks, prefer that over (trying to) write edit lists // in fragmented output. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) mov->use_editlist = 0; } } if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist) av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n"); if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO) s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO; /* Clear the omit_tfhd_offset flag if default_base_moof is set; * if the latter is set that's enough and omit_tfhd_offset doesn't * add anything extra on top of that. */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET; if (mov->frag_interleave && mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) { av_log(s, AV_LOG_ERROR, "Sample interleaving in fragments is mutually exclusive with " "omit_tfhd_offset and separate_moof\n"); return AVERROR(EINVAL); } /* Non-seekable output is ok if using fragmentation. If ism_lookahead * is enabled, we don't support non-seekable output at all. */ if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) { av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n"); return AVERROR(EINVAL); } mov->nb_streams = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) mov->chapter_track = mov->nb_streams++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) mov->nb_streams++; } if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4) || mov->write_tmcd == 1) { /* +1 tmcd track for each video stream with a timecode */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; AVDictionaryEntry *t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) { AVTimecode tc; ret = mov_check_timecode_track(s, &tc, i, t->value); if (ret >= 0) mov->nb_meta_tmcd++; } } /* check if there is already a tmcd track to remux */ if (mov->nb_meta_tmcd) { for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) { av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track " "so timecode metadata are now ignored\n"); mov->nb_meta_tmcd = 0; } } } mov->nb_streams += mov->nb_meta_tmcd; } // Reserve an extra stream for chapters for the case where chapters // are written in the trailer mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks)); if (!mov->tracks) return AVERROR(ENOMEM); if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) { if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) { mov->encryption_scheme = MOV_ENC_CENC_AES_CTR; if (mov->encryption_key_len != AES_CTR_KEY_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n", mov->encryption_key_len, AES_CTR_KEY_SIZE); return AVERROR(EINVAL); } if (mov->encryption_kid_len != CENC_KID_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n", mov->encryption_kid_len, CENC_KID_SIZE); return AVERROR(EINVAL); } } else { av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n", mov->encryption_scheme_str); return AVERROR(EINVAL); } } for (i = 0; i < s->nb_streams; i++) { AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); track->st = st; track->par = st->codecpar; track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV); if (track->language < 0) track->language = 0; track->mode = mov->mode; track->tag = mov_find_codec_tag(s, track); if (!track->tag) { av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, " "codec not currently supported in container\n", avcodec_get_name(st->codecpar->codec_id), i); return AVERROR(EINVAL); } /* If hinting of this track is enabled by a later hint track, * this is updated. */ track->hint_track = -1; track->start_dts = AV_NOPTS_VALUE; track->start_cts = AV_NOPTS_VALUE; track->end_pts = AV_NOPTS_VALUE; track->dts_shift = AV_NOPTS_VALUE; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') || track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') || track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) { if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) { av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n"); return AVERROR(EINVAL); } track->height = track->tag >> 24 == 'n' ? 486 : 576; } if (mov->video_track_timescale) { track->timescale = mov->video_track_timescale; } else { track->timescale = st->time_base.den; while(track->timescale < 10000) track->timescale *= 2; } if (st->codecpar->width > 65535 || st->codecpar->height > 65535) { av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height); return AVERROR(EINVAL); } if (track->mode == MODE_MOV && track->timescale > 100000) av_log(s, AV_LOG_WARNING, "WARNING codec timebase is very high. If duration is too long,\n" "file may not be playable by quicktime. Specify a shorter timebase\n" "or choose different container.\n"); if (track->mode == MODE_MOV && track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->tag == MKTAG('r','a','w',' ')) { enum AVPixelFormat pix_fmt = track->par->format; if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1) pix_fmt = AV_PIX_FMT_MONOWHITE; track->is_unaligned_qt_rgb = pix_fmt == AV_PIX_FMT_RGB24 || pix_fmt == AV_PIX_FMT_BGR24 || pix_fmt == AV_PIX_FMT_PAL8 || pix_fmt == AV_PIX_FMT_GRAY8 || pix_fmt == AV_PIX_FMT_MONOWHITE || pix_fmt == AV_PIX_FMT_MONOBLACK; } if (track->par->codec_id == AV_CODEC_ID_VP9) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n"); return AVERROR(EINVAL); } } else if (track->par->codec_id == AV_CODEC_ID_AV1) { /* spec is not finished, so forbid for now */ av_log(s, AV_LOG_ERROR, "AV1 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } else if (track->par->codec_id == AV_CODEC_ID_VP8) { /* altref frames handling is not defined in the spec as of version v1.0, * so just forbid muxing VP8 streams altogether until a new version does */ av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { track->timescale = st->codecpar->sample_rate; if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) { av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i); track->audio_vbr = 1; }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || st->codecpar->codec_id == AV_CODEC_ID_ILBC){ if (!st->codecpar->block_align) { av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i); return AVERROR(EINVAL); } track->sample_size = st->codecpar->block_align; }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */ track->audio_vbr = 1; }else{ track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels; } if (st->codecpar->codec_id == AV_CODEC_ID_ILBC || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) { track->audio_vbr = 1; } if (track->mode != MODE_MOV && track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) { if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) { av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n", i, track->par->sample_rate); return AVERROR(EINVAL); } else { av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n", i, track->par->sample_rate); } } if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id)); return AVERROR(EINVAL); } if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { av_log(s, AV_LOG_ERROR, "%s in MP4 support is experimental, add " "'-strict %d' if you want to use it.\n", avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL); return AVERROR_EXPERIMENTAL; } } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { track->timescale = st->time_base.den; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { track->timescale = st->time_base.den; } else { track->timescale = MOV_TIMESCALE; } if (!track->height) track->height = st->codecpar->height; /* The ism specific timescale isn't mandatory, but is assumed by * some tools, such as mp4split. */ if (mov->mode == MODE_ISM) track->timescale = 10000000; avpriv_set_pts_info(st, 64, 1, track->timescale); if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) { ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key, track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT); if (ret) return ret; } } enable_tracks(s); return 0; } static int mov_write_header(AVFormatContext *s) { AVIOContext *pb = s->pb; MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) nb_tracks++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { hint_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) nb_tracks++; } if (mov->mode == MODE_MOV || mov->mode == MODE_MP4) tmcd_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) { int j; AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; /* copy extradata if it exists */ if (st->codecpar->extradata_size) { if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_create_dvd_sub_decoder_specific_info(track, st); else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) { track->vos_len = st->codecpar->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) { return AVERROR(ENOMEM); } memcpy(track->vos_data, st->codecpar->extradata, track->vos_len); } } if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || track->par->channel_layout != AV_CH_LAYOUT_MONO) continue; for (j = 0; j < s->nb_streams; j++) { AVStream *stj= s->streams[j]; MOVTrack *trackj= &mov->tracks[j]; if (j == i) continue; if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || trackj->par->channel_layout != AV_CH_LAYOUT_MONO || trackj->language != track->language || trackj->tag != track->tag ) continue; track->multichannel_as_mono++; } } if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_identification(pb, s)) < 0) return ret; } if (mov->reserved_moov_size){ mov->reserved_header_pos = avio_tell(pb); if (mov->reserved_moov_size > 0) avio_skip(pb, mov->reserved_moov_size); } if (mov->flags & FF_MOV_FLAG_FRAGMENT) { /* If no fragmentation options have been set, set a default. */ if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) && !mov->max_fragment_duration && !mov->max_fragment_size) mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME; } else { if (mov->flags & FF_MOV_FLAG_FASTSTART) mov->reserved_header_pos = avio_tell(pb); mov_write_mdat_tag(pb, mov); } ff_parse_creation_time_metadata(s, &mov->time, 1); if (mov->time) mov->time += 0x7C25B080; // 1970 based -> 1904 based if (mov->chapter_track) if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) { if (rtp_hinting_needed(s->streams[i])) { if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0) return ret; hint_track++; } } } if (mov->nb_meta_tmcd) { /* Initialize the tmcd tracks */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { AVTimecode tc; if (!t) t = av_dict_get(st->metadata, "timecode", NULL, 0); if (!t) continue; if (mov_check_timecode_track(s, &tc, i, t->value) < 0) continue; if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0) return ret; tmcd_track++; } } } avio_flush(pb); if (mov->flags & FF_MOV_FLAG_ISML) mov_write_isml_manifest(pb, mov, s); if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_moov_tag(pb, mov, s)) < 0) return ret; avio_flush(pb); mov->moov_written = 1; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(pb); } return 0; } static int get_moov_size(AVFormatContext *s) { int ret; AVIOContext *moov_buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&moov_buf)) < 0) return ret; if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0) return ret; return ffio_close_null_buf(moov_buf); } static int get_sidx_size(AVFormatContext *s) { int ret; AVIOContext *buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&buf)) < 0) return ret; mov_write_sidx_tags(buf, mov, -1, 0); return ffio_close_null_buf(buf); } /* * This function gets the moov size if moved to the top of the file: the chunk * offset table can switch between stco (32-bit entries) to co64 (64-bit * entries) when the moov is moved to the beginning, so the size of the moov * would change. It also updates the chunk offset tables. */ static int compute_moov_size(AVFormatContext *s) { int i, moov_size, moov_size2; MOVMuxContext *mov = s->priv_data; moov_size = get_moov_size(s); if (moov_size < 0) return moov_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size; moov_size2 = get_moov_size(s); if (moov_size2 < 0) return moov_size2; /* if the size changed, we just switched from stco to co64 and need to * update the offsets */ if (moov_size2 != moov_size) for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size2 - moov_size; return moov_size2; } static int compute_sidx_size(AVFormatContext *s) { int i, sidx_size; MOVMuxContext *mov = s->priv_data; sidx_size = get_sidx_size(s); if (sidx_size < 0) return sidx_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += sidx_size; return sidx_size; } static int shift_data(AVFormatContext *s) { int ret = 0, moov_size; MOVMuxContext *mov = s->priv_data; int64_t pos, pos_end = avio_tell(s->pb); uint8_t *buf, *read_buf[2]; int read_buf_id = 0; int read_size[2]; AVIOContext *read_pb; if (mov->flags & FF_MOV_FLAG_FRAGMENT) moov_size = compute_sidx_size(s); else moov_size = compute_moov_size(s); if (moov_size < 0) return moov_size; buf = av_malloc(moov_size * 2); if (!buf) return AVERROR(ENOMEM); read_buf[0] = buf; read_buf[1] = buf + moov_size; /* Shift the data: the AVIO context of the output can only be used for * writing, so we re-open the same output, but for reading. It also avoids * a read/seek/write/seek back and forth. */ avio_flush(s->pb); ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL); if (ret < 0) { av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for " "the second pass (faststart)\n", s->url); goto end; } /* mark the end of the shift to up to the last data we wrote, and get ready * for writing */ pos_end = avio_tell(s->pb); avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET); /* start reading at where the new moov will be placed */ avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET); pos = avio_tell(read_pb); #define READ_BLOCK do { \ read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \ read_buf_id ^= 1; \ } while (0) /* shift data by chunk of at most moov_size */ READ_BLOCK; do { int n; READ_BLOCK; n = read_size[read_buf_id]; if (n <= 0) break; avio_write(s->pb, read_buf[read_buf_id], n); pos += n; } while (pos < pos_end); ff_format_io_close(s, &read_pb); end: av_free(buf); return ret; } static int mov_write_trailer(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; int res = 0; int i; int64_t moov_pos; if (mov->need_rewrite_extradata) { for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; AVCodecParameters *par = track->par; track->vos_len = par->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) return AVERROR(ENOMEM); memcpy(track->vos_data, par->extradata, track->vos_len); } mov->need_rewrite_extradata = 0; } /* * Before actually writing the trailer, make sure that there are no * dangling subtitles, that need a terminating sample. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && !trk->last_sample_is_subtitle_end) { mov_write_subtitle_end_packet(s, i, trk->track_duration); trk->last_sample_is_subtitle_end = 1; } } // If there were no chapters when the header was written, but there // are chapters now, write them in the trailer. This only works // when we are not doing fragments. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) { if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) { mov->chapter_track = mov->nb_streams++; if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0) return res; } } if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) { moov_pos = avio_tell(pb); /* Write size of mdat tag */ if (mov->mdat_size + 8 <= UINT32_MAX) { avio_seek(pb, mov->mdat_pos, SEEK_SET); avio_wb32(pb, mov->mdat_size + 8); } else { /* overwrite 'wide' placeholder atom */ avio_seek(pb, mov->mdat_pos - 8, SEEK_SET); /* special value: real atom size will be 64 bit value after * tag field */ avio_wb32(pb, 1); ffio_wfourcc(pb, "mdat"); avio_wb64(pb, mov->mdat_size + 16); } avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET); if (mov->flags & FF_MOV_FLAG_FASTSTART) { av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n"); res = shift_data(s); if (res < 0) return res; avio_seek(pb, mov->reserved_header_pos, SEEK_SET); if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } else if (mov->reserved_moov_size > 0) { int64_t size; if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos); if (size < 8){ av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size); return AVERROR(EINVAL); } avio_wb32(pb, size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, size - 8); avio_seek(pb, moov_pos, SEEK_SET); } else { if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } res = 0; } else { mov_auto_flush_fragment(s, 1); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = 0; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) { int64_t end; av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n"); res = shift_data(s); if (res < 0) return res; end = avio_tell(pb); avio_seek(pb, mov->reserved_header_pos, SEEK_SET); mov_write_sidx_tags(pb, mov, -1, 0); avio_seek(pb, end, SEEK_SET); avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) { avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } } return res; } static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt) { int ret = 1; AVStream *st = s->streams[pkt->stream_index]; if (st->codecpar->codec_id == AV_CODEC_ID_AAC) { if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL); } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) { ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL); } return ret; } static const AVCodecTag codec_3gp_tags[] = { { AV_CODEC_ID_H263, MKTAG('s','2','6','3') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') }, { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_NONE, 0 }, }; const AVCodecTag codec_mp4_tags[] = { { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') }, { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') }, { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') }, { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') }, { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') }, { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') }, { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') }, { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') }, { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') }, { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') }, { AV_CODEC_ID_NONE , 0 }, }; const AVCodecTag codec_ism_tags[] = { { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') }, { AV_CODEC_ID_NONE , 0 }, }; static const AVCodecTag codec_ipod_tags[] = { { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') }, { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') }, { AV_CODEC_ID_NONE, 0 }, }; static const AVCodecTag codec_f4v_tags[] = { { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') }, { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') }, { AV_CODEC_ID_NONE, 0 }, }; #if CONFIG_MOV_MUXER MOV_CLASS(mov) AVOutputFormat ff_mov_muxer = { .name = "mov", .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"), .extensions = "mov", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mov_muxer_class, }; #endif #if CONFIG_TGP_MUXER MOV_CLASS(tgp) AVOutputFormat ff_tgp_muxer = { .name = "3gp", .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"), .extensions = "3gp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tgp_muxer_class, }; #endif #if CONFIG_MP4_MUXER MOV_CLASS(mp4) AVOutputFormat ff_mp4_muxer = { .name = "mp4", .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "mp4", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mp4_muxer_class, }; #endif #if CONFIG_PSP_MUXER MOV_CLASS(psp) AVOutputFormat ff_psp_muxer = { .name = "psp", .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"), .extensions = "mp4,psp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &psp_muxer_class, }; #endif #if CONFIG_TG2_MUXER MOV_CLASS(tg2) AVOutputFormat ff_tg2_muxer = { .name = "3g2", .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"), .extensions = "3g2", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tg2_muxer_class, }; #endif #if CONFIG_IPOD_MUXER MOV_CLASS(ipod) AVOutputFormat ff_ipod_muxer = { .name = "ipod", .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "m4v,m4a,m4b", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ipod_muxer_class, }; #endif #if CONFIG_ISMV_MUXER MOV_CLASS(ismv) AVOutputFormat ff_ismv_muxer = { .name = "ismv", .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"), .mime_type = "video/mp4", .extensions = "ismv,isma", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, codec_ism_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ismv_muxer_class, }; #endif #if CONFIG_F4V_MUXER MOV_CLASS(f4v) AVOutputFormat ff_f4v_muxer = { .name = "f4v", .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"), .mime_type = "application/f4v", .extensions = "f4v", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH, .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &f4v_muxer_class, }; #endif
./CrossVul/dataset_final_sorted/CWE-369/c/good_258_0
crossvul-cpp_data_bad_4866_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /** @defgroup PI PI - Implementation of a packet iterator */ /*@{*/ /** @name Local static functions */ /*@{*/ /** Get next packet in layer-resolution-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-layer-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-precinct-component-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi); /** Get next packet in precinct-component-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi); /** Get next packet in component-precinct-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi); /** * Updates the coding parameters if the encoding is used with Progression order changes and final (or cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_poc_and_final(opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Updates the coding parameters if the encoding is not used with Progression order changes and final (and cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_num_comps the number of components * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_not_poc(opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the minimum dy of all the components of all the resolutions for the tile. */ static void opj_get_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * The precinct widths, heights, dx and dy for each component at each resolution will be stored as well. * the last parameter of the function should be an array of pointers of size nb components, each pointer leading * to an area of size 4 * max_res. The data is stored inside this area with the following pattern : * dx_compi_res0 , dy_compi_res0 , w_compi_res0, h_compi_res0 , dx_compi_res1 , dy_compi_res1 , w_compi_res1, h_compi_res1 , ... * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the minimum dy of all the components of all the resolutions for the tile. * @param p_resolutions pointer to an area corresponding to the one described above. */ static void opj_get_all_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions); /** * Allocates memory for a packet iterator. Data and data sizes are set by this operation. * No other data is set. The include section of the packet iterator is not allocated. * * @param p_image the image used to initialize the packet iterator (in fact only the number of components is relevant. * @param p_cp the coding parameters. * @param tileno the index of the tile from which creating the packet iterator. */ static opj_pi_iterator_t * opj_pi_create(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno); /** * FIXME DOC */ static void opj_pi_update_decode_not_poc(opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ static void opj_pi_update_decode_poc(opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ static OPJ_BOOL opj_pi_check_next_level(OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog); /*@}*/ /*@}*/ /* ========================================================== local functions ========================================================== */ static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static void opj_get_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res) { /* loop */ OPJ_UINT32 compno, resno; /* pointers */ const opj_tcp_t *l_tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* position in x and y of tile */ OPJ_UINT32 p, q; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps [p_tileno]; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ p = p_tileno % p_cp->tw; q = p_tileno / p_cp->tw; /* find extent of tile */ *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); /* max precision is 0 (can only grow) */ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min */ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* arithmetic variables to calculate */ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_pw, l_ph; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts */ for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); /* take the minimum size for dx for each comp and resolution */ *p_dx_min = opj_uint_min(*p_dx_min, l_dx); *p_dy_min = opj_uint_min(*p_dy_min, l_dy); /* various calculations of extents */ l_level_no = l_tccp->numresolutions - 1 - resno; l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy); l_product = l_pw * l_ph; /* update precision */ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_img_comp; ++l_tccp; } } static void opj_get_all_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions) { /* loop*/ OPJ_UINT32 compno, resno; /* pointers*/ const opj_tcp_t *tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* to store l_dx, l_dy, w and h for each resolution and component.*/ OPJ_UINT32 * lResolutionPtr; /* position in x and y of tile*/ OPJ_UINT32 p, q; /* non-corrected (in regard to image offset) tile offset */ OPJ_UINT32 l_tx0, l_ty0; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(tileno < p_cp->tw * p_cp->th); /* initializations*/ tcp = &p_cp->tcps [tileno]; l_tccp = tcp->tccps; l_img_comp = p_image->comps; /* position in x and y of tile*/ p = tileno % p_cp->tw; q = tileno / p_cp->tw; /* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */ l_tx0 = p_cp->tx0 + p * p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */ *p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0); *p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1); l_ty0 = p_cp->ty0 + q * p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */ *p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0); *p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1); /* max precision and resolution is 0 (can only grow)*/ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min*/ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* aritmetic variables to calculate*/ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; OPJ_UINT32 l_pdx, l_pdy, l_pw, l_ph; lResolutionPtr = p_resolutions[compno]; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts*/ l_level_no = l_tccp->numresolutions; for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; --l_level_no; /* precinct width and height*/ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; *lResolutionPtr++ = l_pdx; *lResolutionPtr++ = l_pdy; l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no)); /* take the minimum size for l_dx for each comp and resolution*/ *p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32) * p_dx_min, (OPJ_INT32)l_dx); *p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32) * p_dy_min, (OPJ_INT32)l_dy); /* various calculations of extents*/ l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy); *lResolutionPtr++ = l_pw; *lResolutionPtr++ = l_ph; l_product = l_pw * l_ph; /* update precision*/ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_tccp; ++l_img_comp; } } static opj_pi_iterator_t * opj_pi_create(const opj_image_t *image, const opj_cp_t *cp, OPJ_UINT32 tileno) { /* loop*/ OPJ_UINT32 pino, compno; /* number of poc in the p_pi*/ OPJ_UINT32 l_poc_bound; /* pointers to tile coding parameters and components.*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *tcp = 00; const opj_tccp_t *tccp = 00; /* current packet iterator being allocated*/ opj_pi_iterator_t *l_current_pi = 00; /* preconditions in debug*/ assert(cp != 00); assert(image != 00); assert(tileno < cp->tw * cp->th); /* initializations*/ tcp = &cp->tcps[tileno]; l_poc_bound = tcp->numpocs + 1; /* memory allocations*/ l_pi = (opj_pi_iterator_t*) opj_calloc((l_poc_bound), sizeof(opj_pi_iterator_t)); if (!l_pi) { return NULL; } l_current_pi = l_pi; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_pi->comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (! l_current_pi->comps) { opj_pi_destroy(l_pi, l_poc_bound); return NULL; } l_current_pi->numcomps = image->numcomps; for (compno = 0; compno < image->numcomps; ++compno) { opj_pi_comp_t *comp = &l_current_pi->comps[compno]; tccp = &tcp->tccps[compno]; comp->resolutions = (opj_pi_resolution_t*) opj_calloc(tccp->numresolutions, sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { opj_pi_destroy(l_pi, l_poc_bound); return 00; } comp->numresolutions = tccp->numresolutions; } ++l_current_pi; } return l_pi; } static void opj_pi_update_encode_poc_and_final(opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs + 1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE = l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; /* special treatment for the first element*/ l_current_poc->layS = 0; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; for (pino = 1; pino < l_poc_bound ; ++pino) { l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE = l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; /* special treatment here different from the first element*/ l_current_poc->layS = (l_current_poc->layE > (l_current_poc - 1)->layE) ? l_current_poc->layE : 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } static void opj_pi_update_encode_not_poc(opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs + 1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_poc->compS = 0; l_current_poc->compE = p_num_comps;/*p_image->numcomps;*/ l_current_poc->resS = 0; l_current_poc->resE = p_max_res; l_current_poc->layS = 0; l_current_poc->layE = l_tcp->numlayers; l_current_poc->prg = l_tcp->prg; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } static void opj_pi_update_decode_poc(opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; opj_poc_t* l_current_poc = 0; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_pi != 00); assert(p_tcp != 00); /* initializations*/ l_bound = p_tcp->numpocs + 1; l_current_pi = p_pi; l_current_poc = p_tcp->pocs; for (pino = 0; pino < l_bound; ++pino) { l_current_pi->poc.prg = l_current_poc->prg; /* Progression Order #0 */ l_current_pi->first = 1; l_current_pi->poc.resno0 = l_current_poc->resno0; /* Resolution Level Index #0 (Start) */ l_current_pi->poc.compno0 = l_current_poc->compno0; /* Component Index #0 (Start) */ l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = l_current_poc->resno1; /* Resolution Level Index #0 (End) */ l_current_pi->poc.compno1 = l_current_poc->compno1; /* Component Index #0 (End) */ l_current_pi->poc.layno1 = l_current_poc->layno1; /* Layer Index #0 (End) */ l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; ++l_current_poc; } } static void opj_pi_update_decode_not_poc(opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; /* preconditions in debug*/ assert(p_tcp != 00); assert(p_pi != 00); /* initializations*/ l_bound = p_tcp->numpocs + 1; l_current_pi = p_pi; for (pino = 0; pino < l_bound; ++pino) { l_current_pi->poc.prg = p_tcp->prg; l_current_pi->first = 1; l_current_pi->poc.resno0 = 0; l_current_pi->poc.compno0 = 0; l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = p_max_res; l_current_pi->poc.compno1 = l_current_pi->numcomps; l_current_pi->poc.layno1 = p_tcp->numlayers; l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; } } static OPJ_BOOL opj_pi_check_next_level(OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog) { OPJ_INT32 i; opj_tcp_t *tcps = &cp->tcps[tileno]; opj_poc_t *tcp = &tcps->pocs[pino]; if (pos >= 0) { for (i = pos; pos >= 0; i--) { switch (prog[i]) { case 'R': if (tcp->res_t == tcp->resE) { if (opj_pi_check_next_level(pos - 1, cp, tileno, pino, prog)) { return OPJ_TRUE; } else { return OPJ_FALSE; } } else { return OPJ_TRUE; } break; case 'C': if (tcp->comp_t == tcp->compE) { if (opj_pi_check_next_level(pos - 1, cp, tileno, pino, prog)) { return OPJ_TRUE; } else { return OPJ_FALSE; } } else { return OPJ_TRUE; } break; case 'L': if (tcp->lay_t == tcp->layE) { if (opj_pi_check_next_level(pos - 1, cp, tileno, pino, prog)) { return OPJ_TRUE; } else { return OPJ_FALSE; } } else { return OPJ_TRUE; } break; case 'P': switch (tcp->prg) { case OPJ_LRCP: /* fall through */ case OPJ_RLCP: if (tcp->prc_t == tcp->prcE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { return OPJ_TRUE; } else { return OPJ_FALSE; } } else { return OPJ_TRUE; } break; default: if (tcp->tx0_t == tcp->txE) { /*TY*/ if (tcp->ty0_t == tcp->tyE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { return OPJ_TRUE; } else { return OPJ_FALSE; } } else { return OPJ_TRUE; }/*TY*/ } else { return OPJ_TRUE; } break; }/*end case P*/ }/*end switch*/ }/*end for*/ }/*end if*/ return OPJ_FALSE; } /* ========================================================== Packet iterator interface ========================================================== */ opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0, l_tx1, l_ty0, l_ty1; OPJ_UINT32 l_dx_min, l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p, l_step_c, l_step_r, l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs + 1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image, p_cp, p_tile_no, &l_tx0, &l_tx1, &l_ty0, &l_ty1, &l_dx_min, &l_dy_min, &l_max_prec, &l_max_res, l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ /* prevent an integer overflow issue */ /* 0 < l_tcp->numlayers < 65536 c.f. opj_j2k_read_cod in j2k.c */ l_current_pi->include = 00; if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U))) { l_current_pi->include = (OPJ_INT16*) opj_calloc((size_t)( l_tcp->numlayers + 1U) * l_step_l, sizeof(OPJ_INT16)); } if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino < l_bound ; ++pino) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi - 1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc(l_pi, l_tcp, l_max_prec, l_max_res); } else { opj_pi_update_decode_not_poc(l_pi, l_tcp, l_max_prec, l_max_res); } return l_pi; } opj_pi_iterator_t *opj_pi_initialise_encode(const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no, J2K_T2_MODE p_t2_mode) { /* loop*/ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions*/ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set*/ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0, l_tx1, l_ty0, l_ty1; OPJ_UINT32 l_dx_min, l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p, l_step_c, l_step_r, l_step_l ; OPJ_UINT32 l_data_stride; /* pointers*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs + 1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi*/ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array*/ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters*/ opj_get_all_encoding_parameters(p_image, p_cp, p_tile_no, &l_tx0, &l_tx1, &l_ty0, &l_ty1, &l_dx_min, &l_dy_min, &l_max_prec, &l_max_res, l_tmp_ptr); /* step calculations*/ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator*/ l_pi->tp_on = (OPJ_BYTE)p_cp->m_specific_param.m_enc.m_tp_on; l_current_pi = l_pi; /* memory allocation for include*/ l_current_pi->include = (OPJ_INT16*) opj_calloc(l_tcp->numlayers * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator*/ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino < l_bound ; ++pino) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi - 1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC && (OPJ_IS_CINEMA(p_cp->rsiz) || p_t2_mode == FINAL_PASS)) { opj_pi_update_encode_poc_and_final(p_cp, p_tile_no, l_tx0, l_tx1, l_ty0, l_ty1, l_max_prec, l_max_res, l_dx_min, l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp, p_image->numcomps, p_tile_no, l_tx0, l_tx1, l_ty0, l_ty1, l_max_prec, l_max_res, l_dx_min, l_dy_min); } return l_pi; } void opj_pi_create_encode(opj_pi_iterator_t *pi, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, OPJ_UINT32 tpnum, OPJ_INT32 tppos, J2K_T2_MODE t2_mode) { const OPJ_CHAR *prog; OPJ_INT32 i; OPJ_UINT32 incr_top = 1, resetX = 0; opj_tcp_t *tcps = &cp->tcps[tileno]; opj_poc_t *tcp = &tcps->pocs[pino]; prog = opj_j2k_convert_progression_order(tcp->prg); pi[pino].first = 1; pi[pino].poc.prg = tcp->prg; if (!(cp->m_specific_param.m_enc.m_tp_on && ((!OPJ_IS_CINEMA(cp->rsiz) && (t2_mode == FINAL_PASS)) || OPJ_IS_CINEMA(cp->rsiz)))) { pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; } else { for (i = tppos + 1; i < 4; i++) { switch (prog[i]) { case 'R': pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; break; case 'C': pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; break; case 'L': pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; break; case 'P': switch (tcp->prg) { case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; break; default: pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; break; } break; } } if (tpnum == 0) { for (i = tppos; i >= 0; i--) { switch (prog[i]) { case 'C': tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; break; case 'R': tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; break; case 'L': tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; break; case 'P': switch (tcp->prg) { case OPJ_LRCP: case OPJ_RLCP: tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; break; default: tcp->tx0_t = tcp->txS; tcp->ty0_t = tcp->tyS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; break; } break; } } incr_top = 1; } else { for (i = tppos; i >= 0; i--) { switch (prog[i]) { case 'C': pi[pino].poc.compno0 = tcp->comp_t - 1; pi[pino].poc.compno1 = tcp->comp_t; break; case 'R': pi[pino].poc.resno0 = tcp->res_t - 1; pi[pino].poc.resno1 = tcp->res_t; break; case 'L': pi[pino].poc.layno0 = tcp->lay_t - 1; pi[pino].poc.layno1 = tcp->lay_t; break; case 'P': switch (tcp->prg) { case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prc_t - 1; pi[pino].poc.precno1 = tcp->prc_t; break; default: pi[pino].poc.tx0 = (OPJ_INT32)(tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.tx1 = (OPJ_INT32)tcp->tx0_t ; pi[pino].poc.ty0 = (OPJ_INT32)(tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy)); pi[pino].poc.ty1 = (OPJ_INT32)tcp->ty0_t ; break; } break; } if (incr_top == 1) { switch (prog[i]) { case 'R': if (tcp->res_t == tcp->resE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; incr_top = 1; } else { incr_top = 0; } } else { pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; incr_top = 0; } break; case 'C': if (tcp->comp_t == tcp->compE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; incr_top = 1; } else { incr_top = 0; } } else { pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; incr_top = 0; } break; case 'L': if (tcp->lay_t == tcp->layE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; incr_top = 1; } else { incr_top = 0; } } else { pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; incr_top = 0; } break; case 'P': switch (tcp->prg) { case OPJ_LRCP: case OPJ_RLCP: if (tcp->prc_t == tcp->prcE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; incr_top = 1; } else { incr_top = 0; } } else { pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; incr_top = 0; } break; default: if (tcp->tx0_t >= tcp->txE) { if (tcp->ty0_t >= tcp->tyE) { if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) { tcp->ty0_t = tcp->tyS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top = 1; resetX = 1; } else { incr_top = 0; resetX = 0; } } else { pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top = 0; resetX = 1; } if (resetX == 1) { tcp->tx0_t = tcp->txS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; } } else { pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; incr_top = 0; } break; } break; } } } } } } void opj_pi_destroy(opj_pi_iterator_t *p_pi, OPJ_UINT32 p_nb_elements) { OPJ_UINT32 compno, pino; opj_pi_iterator_t *l_current_pi = p_pi; if (p_pi) { if (p_pi->include) { opj_free(p_pi->include); p_pi->include = 00; } for (pino = 0; pino < p_nb_elements; ++pino) { if (l_current_pi->comps) { opj_pi_comp_t *l_current_component = l_current_pi->comps; for (compno = 0; compno < l_current_pi->numcomps; compno++) { if (l_current_component->resolutions) { opj_free(l_current_component->resolutions); l_current_component->resolutions = 00; } ++l_current_component; } opj_free(l_current_pi->comps); l_current_pi->comps = 0; } ++l_current_pi; } opj_free(p_pi); } } void opj_pi_update_encoding_parameters(const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* encoding parameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0, l_tx1, l_ty0, l_ty1; OPJ_UINT32 l_dx_min, l_dy_min; /* pointers */ opj_tcp_t *l_tcp = 00; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); l_tcp = &(p_cp->tcps[p_tile_no]); /* get encoding parameters */ opj_get_encoding_parameters(p_image, p_cp, p_tile_no, &l_tx0, &l_tx1, &l_ty0, &l_ty1, &l_dx_min, &l_dy_min, &l_max_prec, &l_max_res); if (l_tcp->POC) { opj_pi_update_encode_poc_and_final(p_cp, p_tile_no, l_tx0, l_tx1, l_ty0, l_ty1, l_max_prec, l_max_res, l_dx_min, l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp, p_image->numcomps, p_tile_no, l_tx0, l_tx1, l_ty0, l_ty1, l_max_prec, l_max_res, l_dx_min, l_dy_min); } } OPJ_BOOL opj_pi_next(opj_pi_iterator_t * pi) { switch (pi->poc.prg) { case OPJ_LRCP: return opj_pi_next_lrcp(pi); case OPJ_RLCP: return opj_pi_next_rlcp(pi); case OPJ_RPCL: return opj_pi_next_rpcl(pi); case OPJ_PCRL: return opj_pi_next_pcrl(pi); case OPJ_CPRL: return opj_pi_next_cprl(pi); case OPJ_PROG_UNKNOWN: return OPJ_FALSE; } return OPJ_FALSE; }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_4866_0
crossvul-cpp_data_bad_4853_1
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * Scanline-oriented Read Support */ #include "tiffiop.h" #include <stdio.h> #define TIFF_SIZE_T_MAX ((size_t) ~ ((size_t)0)) #define TIFF_TMSIZE_T_MAX (tmsize_t)(TIFF_SIZE_T_MAX >> 1) int TIFFFillStrip(TIFF* tif, uint32 strip); int TIFFFillTile(TIFF* tif, uint32 tile); static int TIFFStartStrip(TIFF* tif, uint32 strip); static int TIFFStartTile(TIFF* tif, uint32 tile); static int TIFFCheckRead(TIFF*, int); static tmsize_t TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size,const char* module); static tmsize_t TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module); #define NOSTRIP ((uint32)(-1)) /* undefined state */ #define NOTILE ((uint32)(-1)) /* undefined state */ static int TIFFFillStripPartial( TIFF *tif, int strip, tmsize_t read_ahead, int restart ) { static const char module[] = "TIFFFillStripPartial"; register TIFFDirectory *td = &tif->tif_dir; tmsize_t unused_data; uint64 read_offset; tmsize_t cc, to_read; /* tmsize_t bytecountm; */ if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; /* * Expand raw data buffer, if needed, to hold data * strip coming from file (perhaps should set upper * bound on the size of a buffer we'll use?). */ /* bytecountm=(tmsize_t) td->td_stripbytecount[strip]; */ if (read_ahead*2 > tif->tif_rawdatasize) { assert( restart ); tif->tif_curstrip = NOSTRIP; if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Data buffer too small to hold part of strip %lu", (unsigned long) strip); return (0); } if (!TIFFReadBufferSetup(tif, 0, read_ahead*2)) return (0); } if( restart ) { tif->tif_rawdataloaded = 0; tif->tif_rawdataoff = 0; } /* ** If we are reading more data, move any unused data to the ** start of the buffer. */ if( tif->tif_rawdataloaded > 0 ) unused_data = tif->tif_rawdataloaded - (tif->tif_rawcp - tif->tif_rawdata); else unused_data = 0; if( unused_data > 0 ) { assert((tif->tif_flags&TIFF_BUFFERMMAP)==0); memmove( tif->tif_rawdata, tif->tif_rawcp, unused_data ); } /* ** Seek to the point in the file where more data should be read. */ read_offset = td->td_stripoffset[strip] + tif->tif_rawdataoff + tif->tif_rawdataloaded; if (!SeekOK(tif, read_offset)) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at scanline %lu, strip %lu", (unsigned long) tif->tif_row, (unsigned long) strip); return 0; } /* ** How much do we want to read? */ to_read = tif->tif_rawdatasize - unused_data; if( (uint64) to_read > td->td_stripbytecount[strip] - tif->tif_rawdataoff - tif->tif_rawdataloaded ) { to_read = (tmsize_t) td->td_stripbytecount[strip] - tif->tif_rawdataoff - tif->tif_rawdataloaded; } assert((tif->tif_flags&TIFF_BUFFERMMAP)==0); cc = TIFFReadFile(tif, tif->tif_rawdata + unused_data, to_read); if (cc != to_read) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned __int64) cc, (unsigned __int64) to_read); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long long) cc, (unsigned long long) to_read); #endif return 0; } tif->tif_rawdataoff = tif->tif_rawdataoff + tif->tif_rawdataloaded - unused_data ; tif->tif_rawdataloaded = unused_data + to_read; tif->tif_rawcp = tif->tif_rawdata; if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) { assert((tif->tif_flags&TIFF_BUFFERMMAP)==0); TIFFReverseBits(tif->tif_rawdata + unused_data, to_read ); } /* ** When starting a strip from the beginning we need to ** restart the decoder. */ if( restart ) return TIFFStartStrip(tif, strip); else return 1; } /* * Seek to a random row+sample in a file. * * Only used by TIFFReadScanline, and is only used on * strip organized files. We do some tricky stuff to try * and avoid reading the whole compressed raw data for big * strips. */ static int TIFFSeek(TIFF* tif, uint32 row, uint16 sample ) { register TIFFDirectory *td = &tif->tif_dir; uint32 strip; int whole_strip; tmsize_t read_ahead = 0; /* ** Establish what strip we are working from. */ if (row >= td->td_imagelength) { /* out of range */ TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%lu: Row out of range, max %lu", (unsigned long) row, (unsigned long) td->td_imagelength); return (0); } if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { if (sample >= td->td_samplesperpixel) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%lu: Sample out of range, max %lu", (unsigned long) sample, (unsigned long) td->td_samplesperpixel); return (0); } strip = (uint32)sample*td->td_stripsperimage + row/td->td_rowsperstrip; } else strip = row / td->td_rowsperstrip; /* * Do we want to treat this strip as one whole chunk or * read it a few lines at a time? */ #if defined(CHUNKY_STRIP_READ_SUPPORT) if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; whole_strip = tif->tif_dir.td_stripbytecount[strip] < 10 || isMapped(tif); #else whole_strip = 1; #endif if( !whole_strip ) { read_ahead = tif->tif_scanlinesize * 16 + 5000; } /* * If we haven't loaded this strip, do so now, possibly * only reading the first part. */ if (strip != tif->tif_curstrip) { /* different strip, refill */ if( whole_strip ) { if (!TIFFFillStrip(tif, strip)) return (0); } else { if( !TIFFFillStripPartial(tif,strip,read_ahead,1) ) return 0; } } /* ** If we already have some data loaded, do we need to read some more? */ else if( !whole_strip ) { if( ((tif->tif_rawdata + tif->tif_rawdataloaded) - tif->tif_rawcp) < read_ahead && (uint64) tif->tif_rawdataoff+tif->tif_rawdataloaded < td->td_stripbytecount[strip] ) { if( !TIFFFillStripPartial(tif,strip,read_ahead,0) ) return 0; } } if (row < tif->tif_row) { /* * Moving backwards within the same strip: backup * to the start and then decode forward (below). * * NB: If you're planning on lots of random access within a * strip, it's better to just read and decode the entire * strip, and then access the decoded data in a random fashion. */ if( tif->tif_rawdataoff != 0 ) { if( !TIFFFillStripPartial(tif,strip,read_ahead,1) ) return 0; } else { if (!TIFFStartStrip(tif, strip)) return (0); } } if (row != tif->tif_row) { /* * Seek forward to the desired row. */ /* TODO: Will this really work with partial buffers? */ if (!(*tif->tif_seek)(tif, row - tif->tif_row)) return (0); tif->tif_row = row; } return (1); } int TIFFReadScanline(TIFF* tif, void* buf, uint32 row, uint16 sample) { int e; if (!TIFFCheckRead(tif, 0)) return (-1); if( (e = TIFFSeek(tif, row, sample)) != 0) { /* * Decompress desired row into user buffer. */ e = (*tif->tif_decoderow) (tif, (uint8*) buf, tif->tif_scanlinesize, sample); /* we are now poised at the beginning of the next row */ tif->tif_row = row + 1; if (e) (*tif->tif_postdecode)(tif, (uint8*) buf, tif->tif_scanlinesize); } return (e > 0 ? 1 : -1); } /* * Read a strip of data and decompress the specified * amount into the user-supplied buffer. */ tmsize_t TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedStrip"; TIFFDirectory *td = &tif->tif_dir; uint32 rowsperstrip; uint32 stripsperplane; uint32 stripinplane; uint16 plane; uint32 rows; tmsize_t stripsize; if (!TIFFCheckRead(tif,0)) return((tmsize_t)(-1)); if (strip>=td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata,module, "%lu: Strip out of range, max %lu",(unsigned long)strip, (unsigned long)td->td_nstrips); return((tmsize_t)(-1)); } /* * Calculate the strip size according to the number of * rows in the strip (check for truncated last strip on any * of the separations). */ rowsperstrip=td->td_rowsperstrip; if (rowsperstrip>td->td_imagelength) rowsperstrip=td->td_imagelength; stripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip); stripinplane=(strip%stripsperplane); plane=(uint16)(strip/stripsperplane); rows=td->td_imagelength-stripinplane*rowsperstrip; if (rows>rowsperstrip) rows=rowsperstrip; stripsize=TIFFVStripSize(tif,rows); if (stripsize==0) return((tmsize_t)(-1)); /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE && size!=(tmsize_t)(-1) && size >= stripsize && !isMapped(tif) && ((tif->tif_flags&TIFF_NOREADRAW)==0) ) { if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize) return ((tmsize_t)(-1)); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(buf,stripsize); (*tif->tif_postdecode)(tif,buf,stripsize); return (stripsize); } if ((size!=(tmsize_t)(-1))&&(size<stripsize)) stripsize=size; if (!TIFFFillStrip(tif,strip)) return((tmsize_t)(-1)); if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0) return((tmsize_t)(-1)); (*tif->tif_postdecode)(tif,buf,stripsize); return(stripsize); } static tmsize_t TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size, const char* module) { TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif )) return ((tmsize_t)(-1)); assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (!isMapped(tif)) { tmsize_t cc; if (!SeekOK(tif, td->td_stripoffset[strip])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at scanline %lu, strip %lu", (unsigned long) tif->tif_row, (unsigned long) strip); return ((tmsize_t)(-1)); } cc = TIFFReadFile(tif, buf, size); if (cc != size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned __int64) cc, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long long) cc, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } } else { tmsize_t ma,mb; tmsize_t n; ma=(tmsize_t)td->td_stripoffset[strip]; mb=ma+size; if ((td->td_stripoffset[strip] > (uint64)TIFF_TMSIZE_T_MAX)||(ma>tif->tif_size)) n=0; else if ((mb<ma)||(mb<size)||(mb>tif->tif_size)) n=tif->tif_size-ma; else n=size; if (n!=size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu, strip %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned long) strip, (unsigned __int64) n, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu, strip %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) strip, (unsigned long long) n, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } _TIFFmemcpy(buf, tif->tif_base + ma, size); } return (size); } /* * Read a strip of data from the file. */ tmsize_t TIFFReadRawStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadRawStrip"; TIFFDirectory *td = &tif->tif_dir; uint64 bytecount; tmsize_t bytecountm; if (!TIFFCheckRead(tif, 0)) return ((tmsize_t)(-1)); if (strip >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Strip out of range, max %lu", (unsigned long) strip, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } if (tif->tif_flags&TIFF_NOREADRAW) { TIFFErrorExt(tif->tif_clientdata, module, "Compression scheme does not support access to raw uncompressed data"); return ((tmsize_t)(-1)); } bytecount = td->td_stripbytecount[strip]; if ((int64)bytecount <= 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "%I64u: Invalid strip byte count, strip %lu", (unsigned __int64) bytecount, (unsigned long) strip); #else TIFFErrorExt(tif->tif_clientdata, module, "%llu: Invalid strip byte count, strip %lu", (unsigned long long) bytecount, (unsigned long) strip); #endif return ((tmsize_t)(-1)); } bytecountm = (tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata, module, "Integer overflow"); return ((tmsize_t)(-1)); } if (size != (tmsize_t)(-1) && size < bytecountm) bytecountm = size; return (TIFFReadRawStrip1(tif, strip, buf, bytecountm, module)); } /* * Read the specified strip and setup for decoding. The data buffer is * expanded, as necessary, to hold the strip's data. */ int TIFFFillStrip(TIFF* tif, uint32 strip) { static const char module[] = "TIFFFillStrip"; TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; if ((tif->tif_flags&TIFF_NOREADRAW)==0) { uint64 bytecount = td->td_stripbytecount[strip]; if ((int64)bytecount <= 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Invalid strip byte count %I64u, strip %lu", (unsigned __int64) bytecount, (unsigned long) strip); #else TIFFErrorExt(tif->tif_clientdata, module, "Invalid strip byte count %llu, strip %lu", (unsigned long long) bytecount, (unsigned long) strip); #endif return (0); } if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) || (tif->tif_flags & TIFF_NOBITREV))) { /* * The image is mapped into memory and we either don't * need to flip bits or the compression routine is * going to handle this operation itself. In this * case, avoid copying the raw data and instead just * reference the data from the memory mapped file * image. This assumes that the decompression * routines do not modify the contents of the raw data * buffer (if they try to, the application will get a * fault since the file is mapped read-only). */ if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) { _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; tif->tif_rawdatasize = 0; } tif->tif_flags &= ~TIFF_MYBUFFER; /* * We must check for overflow, potentially causing * an OOB read. Instead of simple * * td->td_stripoffset[strip]+bytecount > tif->tif_size * * comparison (which can overflow) we do the following * two comparisons: */ if (bytecount > (uint64)tif->tif_size || td->td_stripoffset[strip] > (uint64)tif->tif_size - bytecount) { /* * This error message might seem strange, but * it's what would happen if a read were done * instead. */ #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error on strip %lu; " "got %I64u bytes, expected %I64u", (unsigned long) strip, (unsigned __int64) tif->tif_size - td->td_stripoffset[strip], (unsigned __int64) bytecount); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error on strip %lu; " "got %llu bytes, expected %llu", (unsigned long) strip, (unsigned long long) tif->tif_size - td->td_stripoffset[strip], (unsigned long long) bytecount); #endif tif->tif_curstrip = NOSTRIP; return (0); } tif->tif_rawdatasize = (tmsize_t)bytecount; tif->tif_rawdata = tif->tif_base + (tmsize_t)td->td_stripoffset[strip]; tif->tif_rawdataoff = 0; tif->tif_rawdataloaded = (tmsize_t) bytecount; /* * When we have tif_rawdata reference directly into the memory mapped file * we need to be pretty careful about how we use the rawdata. It is not * a general purpose working buffer as it normally otherwise is. So we * keep track of this fact to avoid using it improperly. */ tif->tif_flags |= TIFF_BUFFERMMAP; } else { /* * Expand raw data buffer, if needed, to hold data * strip coming from file (perhaps should set upper * bound on the size of a buffer we'll use?). */ tmsize_t bytecountm; bytecountm=(tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return(0); } if (bytecountm > tif->tif_rawdatasize) { tif->tif_curstrip = NOSTRIP; if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Data buffer too small to hold strip %lu", (unsigned long) strip); return (0); } if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (tif->tif_flags&TIFF_BUFFERMMAP) { tif->tif_curstrip = NOSTRIP; if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (TIFFReadRawStrip1(tif, strip, tif->tif_rawdata, bytecountm, module) != bytecountm) return (0); tif->tif_rawdataoff = 0; tif->tif_rawdataloaded = bytecountm; if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(tif->tif_rawdata, bytecountm); } } return (TIFFStartStrip(tif, strip)); } /* * Tile-oriented Read Support * Contributed by Nancy Cam (Silicon Graphics). */ /* * Read and decompress a tile of data. The * tile is selected by the (x,y,z,s) coordinates. */ tmsize_t TIFFReadTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s) { if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s)) return ((tmsize_t)(-1)); return (TIFFReadEncodedTile(tif, TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1))); } /* * Read a tile of data and decompress the specified * amount into the user-supplied buffer. */ tmsize_t TIFFReadEncodedTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedTile"; TIFFDirectory *td = &tif->tif_dir; tmsize_t tilesize = tif->tif_tilesize; if (!TIFFCheckRead(tif, 1)) return ((tmsize_t)(-1)); if (tile >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Tile out of range, max %lu", (unsigned long) tile, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE && size!=(tmsize_t)(-1) && size >= tilesize && !isMapped(tif) && ((tif->tif_flags&TIFF_NOREADRAW)==0) ) { if (TIFFReadRawTile1(tif, tile, buf, tilesize, module) != tilesize) return ((tmsize_t)(-1)); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(buf,tilesize); (*tif->tif_postdecode)(tif,buf,tilesize); return (tilesize); } if (size == (tmsize_t)(-1)) size = tilesize; else if (size > tilesize) size = tilesize; if (TIFFFillTile(tif, tile) && (*tif->tif_decodetile)(tif, (uint8*) buf, size, (uint16)(tile/td->td_stripsperimage))) { (*tif->tif_postdecode)(tif, (uint8*) buf, size); return (size); } else return ((tmsize_t)(-1)); } static tmsize_t TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module) { TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif )) return ((tmsize_t)(-1)); assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (!isMapped(tif)) { tmsize_t cc; if (!SeekOK(tif, td->td_stripoffset[tile])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at row %lu, col %lu, tile %lu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile); return ((tmsize_t)(-1)); } cc = TIFFReadFile(tif, buf, size); if (cc != size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned __int64) cc, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long long) cc, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } } else { tmsize_t ma,mb; tmsize_t n; ma=(tmsize_t)td->td_stripoffset[tile]; mb=ma+size; if ((td->td_stripoffset[tile] > (uint64)TIFF_TMSIZE_T_MAX)||(ma>tif->tif_size)) n=0; else if ((mb<ma)||(mb<size)||(mb>tif->tif_size)) n=tif->tif_size-ma; else n=size; if (n!=size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu, tile %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile, (unsigned __int64) n, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu, tile %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile, (unsigned long long) n, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } _TIFFmemcpy(buf, tif->tif_base + ma, size); } return (size); } /* * Read a tile of data from the file. */ tmsize_t TIFFReadRawTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size) { static const char module[] = "TIFFReadRawTile"; TIFFDirectory *td = &tif->tif_dir; uint64 bytecount64; tmsize_t bytecountm; if (!TIFFCheckRead(tif, 1)) return ((tmsize_t)(-1)); if (tile >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Tile out of range, max %lu", (unsigned long) tile, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } if (tif->tif_flags&TIFF_NOREADRAW) { TIFFErrorExt(tif->tif_clientdata, module, "Compression scheme does not support access to raw uncompressed data"); return ((tmsize_t)(-1)); } bytecount64 = td->td_stripbytecount[tile]; if (size != (tmsize_t)(-1) && (uint64)size < bytecount64) bytecount64 = (uint64)size; bytecountm = (tmsize_t)bytecount64; if ((uint64)bytecountm!=bytecount64) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return ((tmsize_t)(-1)); } return (TIFFReadRawTile1(tif, tile, buf, bytecountm, module)); } /* * Read the specified tile and setup for decoding. The data buffer is * expanded, as necessary, to hold the tile's data. */ int TIFFFillTile(TIFF* tif, uint32 tile) { static const char module[] = "TIFFFillTile"; TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; if ((tif->tif_flags&TIFF_NOREADRAW)==0) { uint64 bytecount = td->td_stripbytecount[tile]; if ((int64)bytecount <= 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "%I64u: Invalid tile byte count, tile %lu", (unsigned __int64) bytecount, (unsigned long) tile); #else TIFFErrorExt(tif->tif_clientdata, module, "%llu: Invalid tile byte count, tile %lu", (unsigned long long) bytecount, (unsigned long) tile); #endif return (0); } if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) || (tif->tif_flags & TIFF_NOBITREV))) { /* * The image is mapped into memory and we either don't * need to flip bits or the compression routine is * going to handle this operation itself. In this * case, avoid copying the raw data and instead just * reference the data from the memory mapped file * image. This assumes that the decompression * routines do not modify the contents of the raw data * buffer (if they try to, the application will get a * fault since the file is mapped read-only). */ if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) { _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; tif->tif_rawdatasize = 0; } tif->tif_flags &= ~TIFF_MYBUFFER; /* * We must check for overflow, potentially causing * an OOB read. Instead of simple * * td->td_stripoffset[tile]+bytecount > tif->tif_size * * comparison (which can overflow) we do the following * two comparisons: */ if (bytecount > (uint64)tif->tif_size || td->td_stripoffset[tile] > (uint64)tif->tif_size - bytecount) { tif->tif_curtile = NOTILE; return (0); } tif->tif_rawdatasize = (tmsize_t)bytecount; tif->tif_rawdata = tif->tif_base + (tmsize_t)td->td_stripoffset[tile]; tif->tif_rawdataoff = 0; tif->tif_rawdataloaded = (tmsize_t) bytecount; tif->tif_flags |= TIFF_BUFFERMMAP; } else { /* * Expand raw data buffer, if needed, to hold data * tile coming from file (perhaps should set upper * bound on the size of a buffer we'll use?). */ tmsize_t bytecountm; bytecountm=(tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return(0); } if (bytecountm > tif->tif_rawdatasize) { tif->tif_curtile = NOTILE; if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Data buffer too small to hold tile %lu", (unsigned long) tile); return (0); } if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (tif->tif_flags&TIFF_BUFFERMMAP) { tif->tif_curtile = NOTILE; if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (TIFFReadRawTile1(tif, tile, tif->tif_rawdata, bytecountm, module) != bytecountm) return (0); tif->tif_rawdataoff = 0; tif->tif_rawdataloaded = bytecountm; if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(tif->tif_rawdata, tif->tif_rawdataloaded); } } return (TIFFStartTile(tif, tile)); } /* * Setup the raw data buffer in preparation for * reading a strip of raw data. If the buffer * is specified as zero, then a buffer of appropriate * size is allocated by the library. Otherwise, * the client must guarantee that the buffer is * large enough to hold any individual strip of * raw data. */ int TIFFReadBufferSetup(TIFF* tif, void* bp, tmsize_t size) { static const char module[] = "TIFFReadBufferSetup"; assert((tif->tif_flags&TIFF_NOREADRAW)==0); tif->tif_flags &= ~TIFF_BUFFERMMAP; if (tif->tif_rawdata) { if (tif->tif_flags & TIFF_MYBUFFER) _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; tif->tif_rawdatasize = 0; } if (bp) { tif->tif_rawdatasize = size; tif->tif_rawdata = (uint8*) bp; tif->tif_flags &= ~TIFF_MYBUFFER; } else { tif->tif_rawdatasize = (tmsize_t)TIFFroundup_64((uint64)size, 1024); if (tif->tif_rawdatasize==0) { TIFFErrorExt(tif->tif_clientdata, module, "Invalid buffer size"); return (0); } tif->tif_rawdata = (uint8*) _TIFFmalloc(tif->tif_rawdatasize); tif->tif_flags |= TIFF_MYBUFFER; } if (tif->tif_rawdata == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for data buffer at scanline %lu", (unsigned long) tif->tif_row); tif->tif_rawdatasize = 0; return (0); } return (1); } /* * Set state to appear as if a * strip has just been read in. */ static int TIFFStartStrip(TIFF* tif, uint32 strip) { TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupdecode)(tif)) return (0); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_curstrip = strip; tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; tif->tif_flags &= ~TIFF_BUF4WRITE; if (tif->tif_flags&TIFF_NOREADRAW) { tif->tif_rawcp = NULL; tif->tif_rawcc = 0; } else { tif->tif_rawcp = tif->tif_rawdata; tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[strip]; } return ((*tif->tif_predecode)(tif, (uint16)(strip / td->td_stripsperimage))); } /* * Set state to appear as if a * tile has just been read in. */ static int TIFFStartTile(TIFF* tif, uint32 tile) { static const char module[] = "TIFFStartTile"; TIFFDirectory *td = &tif->tif_dir; uint32 howmany32; if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupdecode)(tif)) return (0); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_curtile = tile; howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth); if (howmany32 == 0) { TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles"); return 0; } tif->tif_row = (tile % howmany32) * td->td_tilelength; howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength); if (howmany32 == 0) { TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles"); return 0; } tif->tif_col = (tile % howmany32) * td->td_tilewidth; tif->tif_flags &= ~TIFF_BUF4WRITE; if (tif->tif_flags&TIFF_NOREADRAW) { tif->tif_rawcp = NULL; tif->tif_rawcc = 0; } else { tif->tif_rawcp = tif->tif_rawdata; tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[tile]; } return ((*tif->tif_predecode)(tif, (uint16)(tile/td->td_stripsperimage))); } static int TIFFCheckRead(TIFF* tif, int tiles) { if (tif->tif_mode == O_WRONLY) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "File not open for reading"); return (0); } if (tiles ^ isTiled(tif)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, tiles ? "Can not read tiles from a stripped image" : "Can not read scanlines from a tiled image"); return (0); } return (1); } void _TIFFNoPostDecode(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; (void) buf; (void) cc; } void _TIFFSwab16BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 1) == 0); TIFFSwabArrayOfShort((uint16*) buf, cc/2); } void _TIFFSwab24BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc % 3) == 0); TIFFSwabArrayOfTriples((uint8*) buf, cc/3); } void _TIFFSwab32BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 3) == 0); TIFFSwabArrayOfLong((uint32*) buf, cc/4); } void _TIFFSwab64BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 7) == 0); TIFFSwabArrayOfDouble((double*) buf, cc/8); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-369/c/bad_4853_1
crossvul-cpp_data_good_737_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2019 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // dsdiff.c // This module is a helper to the WavPack command-line programs to support DFF files. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" #ifdef _WIN32 #define strdup(x) _strdup(x) #endif #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; #pragma pack(push,2) typedef struct { char ckID [4]; int64_t ckDataSize; } DFFChunkHeader; typedef struct { char ckID [4]; int64_t ckDataSize; char formType [4]; } DFFFileHeader; typedef struct { char ckID [4]; int64_t ckDataSize; uint32_t version; } DFFVersionChunk; typedef struct { char ckID [4]; int64_t ckDataSize; uint32_t sampleRate; } DFFSampleRateChunk; typedef struct { char ckID [4]; int64_t ckDataSize; uint16_t numChannels; } DFFChannelsHeader; typedef struct { char ckID [4]; int64_t ckDataSize; char compressionType [4]; } DFFCompressionHeader; #pragma pack(pop) #define DFFChunkHeaderFormat "4D" #define DFFFileHeaderFormat "4D4" #define DFFVersionChunkFormat "4DL" #define DFFSampleRateChunkFormat "4DL" #define DFFChannelsHeaderFormat "4DS" #define DFFCompressionHeaderFormat "4D4" int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif // loop through all elements of the DSDIFF header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk; if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize); prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels = 0, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (dff_chunk_header.ckDataSize > 0 && dff_chunk_header.ckDataSize <= eptr - cptr) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; if (numChannels < chansSpecified || numChannels < 1 || numChannels > 256) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { if (!config->num_channels) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteDsdiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { uint32_t chan_mask = WavpackGetChannelMask (wpc); int num_channels = WavpackGetNumChannels (wpc); DFFFileHeader file_header, prop_header; DFFChunkHeader data_header; DFFVersionChunk ver_chunk; DFFSampleRateChunk fs_chunk; DFFChannelsHeader chan_header; DFFCompressionHeader cmpr_header; char *cmpr_name = "\016not compressed", *chan_ids; int64_t file_size, prop_chunk_size, data_size; int cmpr_name_size, chan_ids_size; uint32_t bcount; if (debug_logging_mode) error_line ("WriteDsdiffHeader (), total samples = %lld, qmode = 0x%02x\n", (long long) total_samples, qmode); cmpr_name_size = (strlen (cmpr_name) + 1) & ~1; chan_ids_size = num_channels * 4; chan_ids = malloc (chan_ids_size); if (chan_ids) { uint32_t scan_mask = 0x1; char *cptr = chan_ids; int ci, uci = 0; for (ci = 0; ci < num_channels; ++ci) { while (scan_mask && !(scan_mask & chan_mask)) scan_mask <<= 1; if (scan_mask & 0x1) memcpy (cptr, num_channels <= 2 ? "SLFT" : "MLFT", 4); else if (scan_mask & 0x2) memcpy (cptr, num_channels <= 2 ? "SRGT" : "MRGT", 4); else if (scan_mask & 0x4) memcpy (cptr, "C ", 4); else if (scan_mask & 0x8) memcpy (cptr, "LFE ", 4); else if (scan_mask & 0x10) memcpy (cptr, "LS ", 4); else if (scan_mask & 0x20) memcpy (cptr, "RS ", 4); else { cptr [0] = 'C'; cptr [1] = (uci / 100) + '0'; cptr [2] = ((uci % 100) / 10) + '0'; cptr [3] = (uci % 10) + '0'; uci++; } scan_mask <<= 1; cptr += 4; } } else { error_line ("can't allocate memory!"); return FALSE; } data_size = total_samples * num_channels; prop_chunk_size = sizeof (prop_header) + sizeof (fs_chunk) + sizeof (chan_header) + chan_ids_size + sizeof (cmpr_header) + cmpr_name_size; file_size = sizeof (file_header) + sizeof (ver_chunk) + prop_chunk_size + sizeof (data_header) + ((data_size + 1) & ~(int64_t)1); memcpy (file_header.ckID, "FRM8", 4); file_header.ckDataSize = file_size - 12; memcpy (file_header.formType, "DSD ", 4); memcpy (prop_header.ckID, "PROP", 4); prop_header.ckDataSize = prop_chunk_size - 12; memcpy (prop_header.formType, "SND ", 4); memcpy (ver_chunk.ckID, "FVER", 4); ver_chunk.ckDataSize = sizeof (ver_chunk) - 12; ver_chunk.version = 0x01050000; memcpy (fs_chunk.ckID, "FS ", 4); fs_chunk.ckDataSize = sizeof (fs_chunk) - 12; fs_chunk.sampleRate = WavpackGetSampleRate (wpc) * 8; memcpy (chan_header.ckID, "CHNL", 4); chan_header.ckDataSize = sizeof (chan_header) + chan_ids_size - 12; chan_header.numChannels = num_channels; memcpy (cmpr_header.ckID, "CMPR", 4); cmpr_header.ckDataSize = sizeof (cmpr_header) + cmpr_name_size - 12; memcpy (cmpr_header.compressionType, "DSD ", 4); memcpy (data_header.ckID, "DSD ", 4); data_header.ckDataSize = data_size; WavpackNativeToBigEndian (&file_header, DFFFileHeaderFormat); WavpackNativeToBigEndian (&ver_chunk, DFFVersionChunkFormat); WavpackNativeToBigEndian (&prop_header, DFFFileHeaderFormat); WavpackNativeToBigEndian (&fs_chunk, DFFSampleRateChunkFormat); WavpackNativeToBigEndian (&chan_header, DFFChannelsHeaderFormat); WavpackNativeToBigEndian (&cmpr_header, DFFCompressionHeaderFormat); WavpackNativeToBigEndian (&data_header, DFFChunkHeaderFormat); if (!DoWriteFile (outfile, &file_header, sizeof (file_header), &bcount) || bcount != sizeof (file_header) || !DoWriteFile (outfile, &ver_chunk, sizeof (ver_chunk), &bcount) || bcount != sizeof (ver_chunk) || !DoWriteFile (outfile, &prop_header, sizeof (prop_header), &bcount) || bcount != sizeof (prop_header) || !DoWriteFile (outfile, &fs_chunk, sizeof (fs_chunk), &bcount) || bcount != sizeof (fs_chunk) || !DoWriteFile (outfile, &chan_header, sizeof (chan_header), &bcount) || bcount != sizeof (chan_header) || !DoWriteFile (outfile, chan_ids, chan_ids_size, &bcount) || bcount != chan_ids_size || !DoWriteFile (outfile, &cmpr_header, sizeof (cmpr_header), &bcount) || bcount != sizeof (cmpr_header) || !DoWriteFile (outfile, cmpr_name, cmpr_name_size, &bcount) || bcount != cmpr_name_size || !DoWriteFile (outfile, &data_header, sizeof (data_header), &bcount) || bcount != sizeof (data_header)) { error_line ("can't write .DSF data, disk probably full!"); free (chan_ids); return FALSE; } free (chan_ids); return TRUE; }
./CrossVul/dataset_final_sorted/CWE-369/c/good_737_0
crossvul-cpp_data_bad_737_0
//////////////////////////////////////////////////////////////////////////// // **** WAVPACK **** // // Hybrid Lossless Wavefile Compressor // // Copyright (c) 1998 - 2019 David Bryant. // // All Rights Reserved. // // Distributed under the BSD Software License (see license.txt) // //////////////////////////////////////////////////////////////////////////// // dsdiff.c // This module is a helper to the WavPack command-line programs to support DFF files. #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <math.h> #include <stdio.h> #include <ctype.h> #include "wavpack.h" #include "utils.h" #include "md5.h" #ifdef _WIN32 #define strdup(x) _strdup(x) #endif #define WAVPACK_NO_ERROR 0 #define WAVPACK_SOFT_ERROR 1 #define WAVPACK_HARD_ERROR 2 extern int debug_logging_mode; #pragma pack(push,2) typedef struct { char ckID [4]; int64_t ckDataSize; } DFFChunkHeader; typedef struct { char ckID [4]; int64_t ckDataSize; char formType [4]; } DFFFileHeader; typedef struct { char ckID [4]; int64_t ckDataSize; uint32_t version; } DFFVersionChunk; typedef struct { char ckID [4]; int64_t ckDataSize; uint32_t sampleRate; } DFFSampleRateChunk; typedef struct { char ckID [4]; int64_t ckDataSize; uint16_t numChannels; } DFFChannelsHeader; typedef struct { char ckID [4]; int64_t ckDataSize; char compressionType [4]; } DFFCompressionHeader; #pragma pack(pop) #define DFFChunkHeaderFormat "4D" #define DFFFileHeaderFormat "4D4" #define DFFVersionChunkFormat "4DL" #define DFFSampleRateChunkFormat "4DL" #define DFFChannelsHeaderFormat "4DS" #define DFFCompressionHeaderFormat "4D4" int ParseDsdiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, WavpackContext *wpc, WavpackConfig *config) { int64_t infilesize, total_samples; DFFFileHeader dff_file_header; DFFChunkHeader dff_chunk_header; uint32_t bcount; infilesize = DoGetFileSize (infile); memcpy (&dff_file_header, fourcc, 4); if ((!DoReadFile (infile, ((char *) &dff_file_header) + 4, sizeof (DFFFileHeader) - 4, &bcount) || bcount != sizeof (DFFFileHeader) - 4) || strncmp (dff_file_header.formType, "DSD ", 4)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_file_header, sizeof (DFFFileHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } #if 1 // this might be a little too picky... WavpackBigEndianToNative (&dff_file_header, DFFFileHeaderFormat); if (infilesize && !(config->qmode & QMODE_IGNORE_LENGTH) && dff_file_header.ckDataSize && dff_file_header.ckDataSize + 1 && dff_file_header.ckDataSize + 12 != infilesize) { error_line ("%s is not a valid .DFF file (by total size)!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("file header indicated length = %lld", dff_file_header.ckDataSize); #endif // loop through all elements of the DSDIFF header // (until the data chuck) and copy them to the output file while (1) { if (!DoReadFile (infile, &dff_chunk_header, sizeof (DFFChunkHeader), &bcount) || bcount != sizeof (DFFChunkHeader)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &dff_chunk_header, sizeof (DFFChunkHeader))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (debug_logging_mode) error_line ("chunk header indicated length = %lld", dff_chunk_header.ckDataSize); if (!strncmp (dff_chunk_header.ckID, "FVER", 4)) { uint32_t version; if (dff_chunk_header.ckDataSize != sizeof (version) || !DoReadFile (infile, &version, sizeof (version), &bcount) || bcount != sizeof (version)) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, &version, sizeof (version))) { error_line ("%s", WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } WavpackBigEndianToNative (&version, "L"); if (debug_logging_mode) error_line ("dsdiff file version = 0x%08x", version); } else if (!strncmp (dff_chunk_header.ckID, "PROP", 4)) { char *prop_chunk; if (dff_chunk_header.ckDataSize < 4 || dff_chunk_header.ckDataSize > 1024) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } if (debug_logging_mode) error_line ("got PROP chunk of %d bytes total", (int) dff_chunk_header.ckDataSize); prop_chunk = malloc ((size_t) dff_chunk_header.ckDataSize); if (!DoReadFile (infile, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize, &bcount) || bcount != dff_chunk_header.ckDataSize) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, prop_chunk, (uint32_t) dff_chunk_header.ckDataSize)) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (prop_chunk); return WAVPACK_SOFT_ERROR; } if (!strncmp (prop_chunk, "SND ", 4)) { char *cptr = prop_chunk + 4, *eptr = prop_chunk + dff_chunk_header.ckDataSize; uint16_t numChannels, chansSpecified, chanMask = 0; uint32_t sampleRate; while (eptr - cptr >= sizeof (dff_chunk_header)) { memcpy (&dff_chunk_header, cptr, sizeof (dff_chunk_header)); cptr += sizeof (dff_chunk_header); WavpackBigEndianToNative (&dff_chunk_header, DFFChunkHeaderFormat); if (dff_chunk_header.ckDataSize > 0 && dff_chunk_header.ckDataSize <= eptr - cptr) { if (!strncmp (dff_chunk_header.ckID, "FS ", 4) && dff_chunk_header.ckDataSize == 4) { memcpy (&sampleRate, cptr, sizeof (sampleRate)); WavpackBigEndianToNative (&sampleRate, "L"); cptr += dff_chunk_header.ckDataSize; if (debug_logging_mode) error_line ("got sample rate of %u Hz", sampleRate); } else if (!strncmp (dff_chunk_header.ckID, "CHNL", 4) && dff_chunk_header.ckDataSize >= 2) { memcpy (&numChannels, cptr, sizeof (numChannels)); WavpackBigEndianToNative (&numChannels, "S"); cptr += sizeof (numChannels); chansSpecified = (int)(dff_chunk_header.ckDataSize - sizeof (numChannels)) / 4; if (numChannels < chansSpecified || numChannels < 1) { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } while (chansSpecified--) { if (!strncmp (cptr, "SLFT", 4) || !strncmp (cptr, "MLFT", 4)) chanMask |= 0x1; else if (!strncmp (cptr, "SRGT", 4) || !strncmp (cptr, "MRGT", 4)) chanMask |= 0x2; else if (!strncmp (cptr, "LS ", 4)) chanMask |= 0x10; else if (!strncmp (cptr, "RS ", 4)) chanMask |= 0x20; else if (!strncmp (cptr, "C ", 4)) chanMask |= 0x4; else if (!strncmp (cptr, "LFE ", 4)) chanMask |= 0x8; else if (debug_logging_mode) error_line ("undefined channel ID %c%c%c%c", cptr [0], cptr [1], cptr [2], cptr [3]); cptr += 4; } if (debug_logging_mode) error_line ("%d channels, mask = 0x%08x", numChannels, chanMask); } else if (!strncmp (dff_chunk_header.ckID, "CMPR", 4) && dff_chunk_header.ckDataSize >= 4) { if (strncmp (cptr, "DSD ", 4)) { error_line ("DSDIFF files must be uncompressed, not \"%c%c%c%c\"!", cptr [0], cptr [1], cptr [2], cptr [3]); free (prop_chunk); return WAVPACK_SOFT_ERROR; } cptr += dff_chunk_header.ckDataSize; } else { if (debug_logging_mode) error_line ("got PROP/SND chunk type \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); cptr += dff_chunk_header.ckDataSize; } } else { error_line ("%s is not a valid .DFF file!", infilename); free (prop_chunk); return WAVPACK_SOFT_ERROR; } } if (chanMask && (config->channel_mask || (config->qmode & QMODE_CHANS_UNASSIGNED))) { error_line ("this DSDIFF file already has channel order information!"); free (prop_chunk); return WAVPACK_SOFT_ERROR; } else if (chanMask) config->channel_mask = chanMask; config->bits_per_sample = 8; config->bytes_per_sample = 1; config->num_channels = numChannels; config->sample_rate = sampleRate / 8; config->qmode |= QMODE_DSD_MSB_FIRST; } else if (debug_logging_mode) error_line ("got unknown PROP chunk type \"%c%c%c%c\" of %d bytes", prop_chunk [0], prop_chunk [1], prop_chunk [2], prop_chunk [3], dff_chunk_header.ckDataSize); free (prop_chunk); } else if (!strncmp (dff_chunk_header.ckID, "DSD ", 4)) { total_samples = dff_chunk_header.ckDataSize / config->num_channels; break; } else { // just copy unknown chunks to output file int bytes_to_copy = (int)(((dff_chunk_header.ckDataSize) + 1) & ~(int64_t)1); char *buff; if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { error_line ("%s is not a valid .DFF file!", infilename); return WAVPACK_SOFT_ERROR; } buff = malloc (bytes_to_copy); if (debug_logging_mode) error_line ("extra unknown chunk \"%c%c%c%c\" of %d bytes", dff_chunk_header.ckID [0], dff_chunk_header.ckID [1], dff_chunk_header.ckID [2], dff_chunk_header.ckID [3], dff_chunk_header.ckDataSize); if (!DoReadFile (infile, buff, bytes_to_copy, &bcount) || bcount != bytes_to_copy || (!(config->qmode & QMODE_NO_STORE_WRAPPER) && !WavpackAddWrapper (wpc, buff, bytes_to_copy))) { error_line ("%s", WavpackGetErrorMessage (wpc)); free (buff); return WAVPACK_SOFT_ERROR; } free (buff); } } if (debug_logging_mode) error_line ("setting configuration with %lld samples", total_samples); if (!WavpackSetConfiguration64 (wpc, config, total_samples, NULL)) { error_line ("%s: %s", infilename, WavpackGetErrorMessage (wpc)); return WAVPACK_SOFT_ERROR; } return WAVPACK_NO_ERROR; } int WriteDsdiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) { uint32_t chan_mask = WavpackGetChannelMask (wpc); int num_channels = WavpackGetNumChannels (wpc); DFFFileHeader file_header, prop_header; DFFChunkHeader data_header; DFFVersionChunk ver_chunk; DFFSampleRateChunk fs_chunk; DFFChannelsHeader chan_header; DFFCompressionHeader cmpr_header; char *cmpr_name = "\016not compressed", *chan_ids; int64_t file_size, prop_chunk_size, data_size; int cmpr_name_size, chan_ids_size; uint32_t bcount; if (debug_logging_mode) error_line ("WriteDsdiffHeader (), total samples = %lld, qmode = 0x%02x\n", (long long) total_samples, qmode); cmpr_name_size = (strlen (cmpr_name) + 1) & ~1; chan_ids_size = num_channels * 4; chan_ids = malloc (chan_ids_size); if (chan_ids) { uint32_t scan_mask = 0x1; char *cptr = chan_ids; int ci, uci = 0; for (ci = 0; ci < num_channels; ++ci) { while (scan_mask && !(scan_mask & chan_mask)) scan_mask <<= 1; if (scan_mask & 0x1) memcpy (cptr, num_channels <= 2 ? "SLFT" : "MLFT", 4); else if (scan_mask & 0x2) memcpy (cptr, num_channels <= 2 ? "SRGT" : "MRGT", 4); else if (scan_mask & 0x4) memcpy (cptr, "C ", 4); else if (scan_mask & 0x8) memcpy (cptr, "LFE ", 4); else if (scan_mask & 0x10) memcpy (cptr, "LS ", 4); else if (scan_mask & 0x20) memcpy (cptr, "RS ", 4); else { cptr [0] = 'C'; cptr [1] = (uci / 100) + '0'; cptr [2] = ((uci % 100) / 10) + '0'; cptr [3] = (uci % 10) + '0'; uci++; } scan_mask <<= 1; cptr += 4; } } else { error_line ("can't allocate memory!"); return FALSE; } data_size = total_samples * num_channels; prop_chunk_size = sizeof (prop_header) + sizeof (fs_chunk) + sizeof (chan_header) + chan_ids_size + sizeof (cmpr_header) + cmpr_name_size; file_size = sizeof (file_header) + sizeof (ver_chunk) + prop_chunk_size + sizeof (data_header) + ((data_size + 1) & ~(int64_t)1); memcpy (file_header.ckID, "FRM8", 4); file_header.ckDataSize = file_size - 12; memcpy (file_header.formType, "DSD ", 4); memcpy (prop_header.ckID, "PROP", 4); prop_header.ckDataSize = prop_chunk_size - 12; memcpy (prop_header.formType, "SND ", 4); memcpy (ver_chunk.ckID, "FVER", 4); ver_chunk.ckDataSize = sizeof (ver_chunk) - 12; ver_chunk.version = 0x01050000; memcpy (fs_chunk.ckID, "FS ", 4); fs_chunk.ckDataSize = sizeof (fs_chunk) - 12; fs_chunk.sampleRate = WavpackGetSampleRate (wpc) * 8; memcpy (chan_header.ckID, "CHNL", 4); chan_header.ckDataSize = sizeof (chan_header) + chan_ids_size - 12; chan_header.numChannels = num_channels; memcpy (cmpr_header.ckID, "CMPR", 4); cmpr_header.ckDataSize = sizeof (cmpr_header) + cmpr_name_size - 12; memcpy (cmpr_header.compressionType, "DSD ", 4); memcpy (data_header.ckID, "DSD ", 4); data_header.ckDataSize = data_size; WavpackNativeToBigEndian (&file_header, DFFFileHeaderFormat); WavpackNativeToBigEndian (&ver_chunk, DFFVersionChunkFormat); WavpackNativeToBigEndian (&prop_header, DFFFileHeaderFormat); WavpackNativeToBigEndian (&fs_chunk, DFFSampleRateChunkFormat); WavpackNativeToBigEndian (&chan_header, DFFChannelsHeaderFormat); WavpackNativeToBigEndian (&cmpr_header, DFFCompressionHeaderFormat); WavpackNativeToBigEndian (&data_header, DFFChunkHeaderFormat); if (!DoWriteFile (outfile, &file_header, sizeof (file_header), &bcount) || bcount != sizeof (file_header) || !DoWriteFile (outfile, &ver_chunk, sizeof (ver_chunk), &bcount) || bcount != sizeof (ver_chunk) || !DoWriteFile (outfile, &prop_header, sizeof (prop_header), &bcount) || bcount != sizeof (prop_header) || !DoWriteFile (outfile, &fs_chunk, sizeof (fs_chunk), &bcount) || bcount != sizeof (fs_chunk) || !DoWriteFile (outfile, &chan_header, sizeof (chan_header), &bcount) || bcount != sizeof (chan_header) || !DoWriteFile (outfile, chan_ids, chan_ids_size, &bcount) || bcount != chan_ids_size || !DoWriteFile (outfile, &cmpr_header, sizeof (cmpr_header), &bcount) || bcount != sizeof (cmpr_header) || !DoWriteFile (outfile, cmpr_name, cmpr_name_size, &bcount) || bcount != cmpr_name_size || !DoWriteFile (outfile, &data_header, sizeof (data_header), &bcount) || bcount != sizeof (data_header)) { error_line ("can't write .DSF data, disk probably full!"); free (chan_ids); return FALSE; } free (chan_ids); return TRUE; }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_737_0
crossvul-cpp_data_good_5063_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR * Copyright (c) 2012, CS Systemes d'Information, France * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /* ----------------------------------------------------------------------- */ /* TODO MSD: */ #ifdef TODO_MSD void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t * img) { int tileno, compno, resno, bandno, precno;/*, cblkno;*/ fprintf(fd, "image {\n"); fprintf(fd, " tw=%d, th=%d x0=%d x1=%d y0=%d y1=%d\n", img->tw, img->th, tcd->image->x0, tcd->image->x1, tcd->image->y0, tcd->image->y1); for (tileno = 0; tileno < img->th * img->tw; tileno++) { opj_tcd_tile_t *tile = &tcd->tcd_image->tiles[tileno]; fprintf(fd, " tile {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numcomps=%d\n", tile->x0, tile->y0, tile->x1, tile->y1, tile->numcomps); for (compno = 0; compno < tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; fprintf(fd, " tilec {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numresolutions=%d\n", tilec->x0, tilec->y0, tilec->x1, tilec->y1, tilec->numresolutions); for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; fprintf(fd, "\n res {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, pw=%d, ph=%d, numbands=%d\n", res->x0, res->y0, res->x1, res->y1, res->pw, res->ph, res->numbands); for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; fprintf(fd, " band {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, stepsize=%f, numbps=%d\n", band->x0, band->y0, band->x1, band->y1, band->stepsize, band->numbps); for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prec = &band->precincts[precno]; fprintf(fd, " prec {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, cw=%d, ch=%d\n", prec->x0, prec->y0, prec->x1, prec->y1, prec->cw, prec->ch); /* for (cblkno = 0; cblkno < prec->cw * prec->ch; cblkno++) { opj_tcd_cblk_t *cblk = &prec->cblks[cblkno]; fprintf(fd, " cblk {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d\n", cblk->x0, cblk->y0, cblk->x1, cblk->y1); fprintf(fd, " }\n"); } */ fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, "}\n"); } #endif /** * Initializes tile coding/decoding */ static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block, opj_event_mgr_t* manager); /** * Allocates memory for a decoding code block. */ static OPJ_BOOL opj_tcd_code_block_dec_allocate (opj_tcd_cblk_dec_t * p_code_block); /** * Deallocates the decoding data of the given precinct. */ static void opj_tcd_code_block_dec_deallocate (opj_tcd_precinct_t * p_precinct); /** * Allocates memory for an encoding code block (but not data). */ static OPJ_BOOL opj_tcd_code_block_enc_allocate (opj_tcd_cblk_enc_t * p_code_block); /** * Allocates data for an encoding code block */ static OPJ_BOOL opj_tcd_code_block_enc_allocate_data (opj_tcd_cblk_enc_t * p_code_block); /** * Deallocates the encoding data of the given precinct. */ static void opj_tcd_code_block_enc_deallocate (opj_tcd_precinct_t * p_precinct); /** Free the memory allocated for encoding @param tcd TCD handle */ static void opj_tcd_free_tile(opj_tcd_t *tcd); static OPJ_BOOL opj_tcd_t2_decode ( opj_tcd_t *p_tcd, OPJ_BYTE * p_src_data, OPJ_UINT32 * p_data_read, OPJ_UINT32 p_max_src_size, opj_codestream_index_t *p_cstr_index, opj_event_mgr_t *p_manager); static OPJ_BOOL opj_tcd_t1_decode (opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_dwt_decode (opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_mct_decode (opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager); static OPJ_BOOL opj_tcd_dc_level_shift_decode (opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_dc_level_shift_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_mct_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_dwt_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_t1_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_t2_encode ( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ); static OPJ_BOOL opj_tcd_rate_allocate_encode( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ); /* ----------------------------------------------------------------------- */ /** Create a new TCD handle */ opj_tcd_t* opj_tcd_create(OPJ_BOOL p_is_decoder) { opj_tcd_t *l_tcd = 00; /* create the tcd structure */ l_tcd = (opj_tcd_t*) opj_calloc(1,sizeof(opj_tcd_t)); if (!l_tcd) { return 00; } l_tcd->m_is_decoder = p_is_decoder ? 1 : 0; l_tcd->tcd_image = (opj_tcd_image_t*)opj_calloc(1,sizeof(opj_tcd_image_t)); if (!l_tcd->tcd_image) { opj_free(l_tcd); return 00; } return l_tcd; } /* ----------------------------------------------------------------------- */ void opj_tcd_rateallocate_fixed(opj_tcd_t *tcd) { OPJ_UINT32 layno; for (layno = 0; layno < tcd->tcp->numlayers; layno++) { opj_tcd_makelayer_fixed(tcd, layno, 1); } } void opj_tcd_makelayer( opj_tcd_t *tcd, OPJ_UINT32 layno, OPJ_FLOAT64 thresh, OPJ_UINT32 final) { OPJ_UINT32 compno, resno, bandno, precno, cblkno; OPJ_UINT32 passno; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; tcd_tile->distolayer[layno] = 0; /* fixed_quality */ for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; opj_tcd_layer_t *layer = &cblk->layers[layno]; OPJ_UINT32 n; if (layno == 0) { cblk->numpassesinlayers = 0; } n = cblk->numpassesinlayers; for (passno = cblk->numpassesinlayers; passno < cblk->totalpasses; passno++) { OPJ_UINT32 dr; OPJ_FLOAT64 dd; opj_tcd_pass_t *pass = &cblk->passes[passno]; if (n == 0) { dr = pass->rate; dd = pass->distortiondec; } else { dr = pass->rate - cblk->passes[n - 1].rate; dd = pass->distortiondec - cblk->passes[n - 1].distortiondec; } if (!dr) { if (dd != 0) n = passno + 1; continue; } if (thresh - (dd / dr) < DBL_EPSILON) /* do not rely on float equality, check with DBL_EPSILON margin */ n = passno + 1; } layer->numpasses = n - cblk->numpassesinlayers; if (!layer->numpasses) { layer->disto = 0; continue; } if (cblk->numpassesinlayers == 0) { layer->len = cblk->passes[n - 1].rate; layer->data = cblk->data; layer->disto = cblk->passes[n - 1].distortiondec; } else { layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate; layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate; layer->disto = cblk->passes[n - 1].distortiondec - cblk->passes[cblk->numpassesinlayers - 1].distortiondec; } tcd_tile->distolayer[layno] += layer->disto; /* fixed_quality */ if (final) cblk->numpassesinlayers = n; } } } } } } void opj_tcd_makelayer_fixed(opj_tcd_t *tcd, OPJ_UINT32 layno, OPJ_UINT32 final) { OPJ_UINT32 compno, resno, bandno, precno, cblkno; OPJ_INT32 value; /*, matrice[tcd_tcp->numlayers][tcd_tile->comps[0].numresolutions][3]; */ OPJ_INT32 matrice[10][10][3]; OPJ_UINT32 i, j, k; opj_cp_t *cp = tcd->cp; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; opj_tcp_t *tcd_tcp = tcd->tcp; for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; for (i = 0; i < tcd_tcp->numlayers; i++) { for (j = 0; j < tilec->numresolutions; j++) { for (k = 0; k < 3; k++) { matrice[i][j][k] = (OPJ_INT32) ((OPJ_FLOAT32)cp->m_specific_param.m_enc.m_matrice[i * tilec->numresolutions * 3 + j * 3 + k] * (OPJ_FLOAT32) (tcd->image->comps[compno].prec / 16.0)); } } } for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; opj_tcd_layer_t *layer = &cblk->layers[layno]; OPJ_UINT32 n; OPJ_INT32 imsb = (OPJ_INT32)(tcd->image->comps[compno].prec - cblk->numbps); /* number of bit-plan equal to zero */ /* Correction of the matrix of coefficient to include the IMSB information */ if (layno == 0) { value = matrice[layno][resno][bandno]; if (imsb >= value) { value = 0; } else { value -= imsb; } } else { value = matrice[layno][resno][bandno] - matrice[layno - 1][resno][bandno]; if (imsb >= matrice[layno - 1][resno][bandno]) { value -= (imsb - matrice[layno - 1][resno][bandno]); if (value < 0) { value = 0; } } } if (layno == 0) { cblk->numpassesinlayers = 0; } n = cblk->numpassesinlayers; if (cblk->numpassesinlayers == 0) { if (value != 0) { n = 3 * (OPJ_UINT32)value - 2 + cblk->numpassesinlayers; } else { n = cblk->numpassesinlayers; } } else { n = 3 * (OPJ_UINT32)value + cblk->numpassesinlayers; } layer->numpasses = n - cblk->numpassesinlayers; if (!layer->numpasses) continue; if (cblk->numpassesinlayers == 0) { layer->len = cblk->passes[n - 1].rate; layer->data = cblk->data; } else { layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate; layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate; } if (final) cblk->numpassesinlayers = n; } } } } } } OPJ_BOOL opj_tcd_rateallocate( opj_tcd_t *tcd, OPJ_BYTE *dest, OPJ_UINT32 * p_data_written, OPJ_UINT32 len, opj_codestream_info_t *cstr_info) { OPJ_UINT32 compno, resno, bandno, precno, cblkno, layno; OPJ_UINT32 passno; OPJ_FLOAT64 min, max; OPJ_FLOAT64 cumdisto[100]; /* fixed_quality */ const OPJ_FLOAT64 K = 1; /* 1.1; fixed_quality */ OPJ_FLOAT64 maxSE = 0; opj_cp_t *cp = tcd->cp; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; opj_tcp_t *tcd_tcp = tcd->tcp; min = DBL_MAX; max = 0; tcd_tile->numpix = 0; /* fixed_quality */ for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; tilec->numpix = 0; for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; for (passno = 0; passno < cblk->totalpasses; passno++) { opj_tcd_pass_t *pass = &cblk->passes[passno]; OPJ_INT32 dr; OPJ_FLOAT64 dd, rdslope; if (passno == 0) { dr = (OPJ_INT32)pass->rate; dd = pass->distortiondec; } else { dr = (OPJ_INT32)(pass->rate - cblk->passes[passno - 1].rate); dd = pass->distortiondec - cblk->passes[passno - 1].distortiondec; } if (dr == 0) { continue; } rdslope = dd / dr; if (rdslope < min) { min = rdslope; } if (rdslope > max) { max = rdslope; } } /* passno */ /* fixed_quality */ tcd_tile->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0)); tilec->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0)); } /* cbklno */ } /* precno */ } /* bandno */ } /* resno */ maxSE += (((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0) * ((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) -1.0)) * ((OPJ_FLOAT64)(tilec->numpix)); } /* compno */ /* index file */ if(cstr_info) { opj_tile_info_t *tile_info = &cstr_info->tile[tcd->tcd_tileno]; tile_info->numpix = tcd_tile->numpix; tile_info->distotile = tcd_tile->distotile; tile_info->thresh = (OPJ_FLOAT64 *) opj_malloc(tcd_tcp->numlayers * sizeof(OPJ_FLOAT64)); if (!tile_info->thresh) { /* FIXME event manager error callback */ return OPJ_FALSE; } } for (layno = 0; layno < tcd_tcp->numlayers; layno++) { OPJ_FLOAT64 lo = min; OPJ_FLOAT64 hi = max; OPJ_UINT32 maxlen = tcd_tcp->rates[layno] > 0.0f ? opj_uint_min(((OPJ_UINT32) ceil(tcd_tcp->rates[layno])), len) : len; OPJ_FLOAT64 goodthresh = 0; OPJ_FLOAT64 stable_thresh = 0; OPJ_UINT32 i; OPJ_FLOAT64 distotarget; /* fixed_quality */ /* fixed_quality */ distotarget = tcd_tile->distotile - ((K * maxSE) / pow((OPJ_FLOAT32)10, tcd_tcp->distoratio[layno] / 10)); /* Don't try to find an optimal threshold but rather take everything not included yet, if -r xx,yy,zz,0 (disto_alloc == 1 and rates == 0) -q xx,yy,zz,0 (fixed_quality == 1 and distoratio == 0) ==> possible to have some lossy layers and the last layer for sure lossless */ if ( ((cp->m_specific_param.m_enc.m_disto_alloc==1) && (tcd_tcp->rates[layno]>0.0f)) || ((cp->m_specific_param.m_enc.m_fixed_quality==1) && (tcd_tcp->distoratio[layno]>0.0))) { opj_t2_t*t2 = opj_t2_create(tcd->image, cp); OPJ_FLOAT64 thresh = 0; if (t2 == 00) { return OPJ_FALSE; } for (i = 0; i < 128; ++i) { OPJ_FLOAT64 distoachieved = 0; /* fixed_quality */ thresh = (lo + hi) / 2; opj_tcd_makelayer(tcd, layno, thresh, 0); if (cp->m_specific_param.m_enc.m_fixed_quality) { /* fixed_quality */ if(OPJ_IS_CINEMA(cp->rsiz)){ if (! opj_t2_encode_packets(t2,tcd->tcd_tileno, tcd_tile, layno + 1, dest, p_data_written, maxlen, cstr_info,tcd->cur_tp_num,tcd->tp_pos,tcd->cur_pino,THRESH_CALC)) { lo = thresh; continue; } else { distoachieved = layno == 0 ? tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno]; if (distoachieved < distotarget) { hi=thresh; stable_thresh = thresh; continue; }else{ lo=thresh; } } }else{ distoachieved = (layno == 0) ? tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]); if (distoachieved < distotarget) { hi = thresh; stable_thresh = thresh; continue; } lo = thresh; } } else { if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,p_data_written, maxlen, cstr_info,tcd->cur_tp_num,tcd->tp_pos,tcd->cur_pino,THRESH_CALC)) { /* TODO: what to do with l ??? seek / tell ??? */ /* opj_event_msg(tcd->cinfo, EVT_INFO, "rate alloc: len=%d, max=%d\n", l, maxlen); */ lo = thresh; continue; } hi = thresh; stable_thresh = thresh; } } goodthresh = stable_thresh == 0? thresh : stable_thresh; opj_t2_destroy(t2); } else { goodthresh = min; } if(cstr_info) { /* Threshold for Marcela Index */ cstr_info->tile[tcd->tcd_tileno].thresh[layno] = goodthresh; } opj_tcd_makelayer(tcd, layno, goodthresh, 1); /* fixed_quality */ cumdisto[layno] = (layno == 0) ? tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]); } return OPJ_TRUE; } OPJ_BOOL opj_tcd_init( opj_tcd_t *p_tcd, opj_image_t * p_image, opj_cp_t * p_cp ) { p_tcd->image = p_image; p_tcd->cp = p_cp; p_tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(1,sizeof(opj_tcd_tile_t)); if (! p_tcd->tcd_image->tiles) { return OPJ_FALSE; } p_tcd->tcd_image->tiles->comps = (opj_tcd_tilecomp_t *) opj_calloc(p_image->numcomps,sizeof(opj_tcd_tilecomp_t)); if (! p_tcd->tcd_image->tiles->comps ) { return OPJ_FALSE; } p_tcd->tcd_image->tiles->numcomps = p_image->numcomps; p_tcd->tp_pos = p_cp->m_specific_param.m_enc.m_tp_pos; return OPJ_TRUE; } /** Destroy a previously created TCD handle */ void opj_tcd_destroy(opj_tcd_t *tcd) { if (tcd) { opj_tcd_free_tile(tcd); if (tcd->tcd_image) { opj_free(tcd->tcd_image); tcd->tcd_image = 00; } opj_free(tcd); } } OPJ_BOOL opj_alloc_tile_component_data(opj_tcd_tilecomp_t *l_tilec) { if ((l_tilec->data == 00) || ((l_tilec->data_size_needed > l_tilec->data_size) && (l_tilec->ownsData == OPJ_FALSE))) { l_tilec->data = (OPJ_INT32 *) opj_aligned_malloc(l_tilec->data_size_needed); if (! l_tilec->data ) { return OPJ_FALSE; } /*fprintf(stderr, "tAllocate data of tilec (int): %d x OPJ_UINT32n",l_data_size);*/ l_tilec->data_size = l_tilec->data_size_needed; l_tilec->ownsData = OPJ_TRUE; } else if (l_tilec->data_size_needed > l_tilec->data_size) { /* We don't need to keep old data */ opj_aligned_free(l_tilec->data); l_tilec->data = (OPJ_INT32 *) opj_aligned_malloc(l_tilec->data_size_needed); if (! l_tilec->data ) { l_tilec->data_size = 0; l_tilec->data_size_needed = 0; l_tilec->ownsData = OPJ_FALSE; return OPJ_FALSE; } /*fprintf(stderr, "tReallocate data of tilec (int): from %d to %d x OPJ_UINT32n", l_tilec->data_size, l_data_size);*/ l_tilec->data_size = l_tilec->data_size_needed; l_tilec->ownsData = OPJ_TRUE; } return OPJ_TRUE; } /* ----------------------------------------------------------------------- */ static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block, opj_event_mgr_t* manager) { OPJ_UINT32 (*l_gain_ptr)(OPJ_UINT32) = 00; OPJ_UINT32 compno, resno, bandno, precno, cblkno; opj_tcp_t * l_tcp = 00; opj_cp_t * l_cp = 00; opj_tcd_tile_t * l_tile = 00; opj_tccp_t *l_tccp = 00; opj_tcd_tilecomp_t *l_tilec = 00; opj_image_comp_t * l_image_comp = 00; opj_tcd_resolution_t *l_res = 00; opj_tcd_band_t *l_band = 00; opj_stepsize_t * l_step_size = 00; opj_tcd_precinct_t *l_current_precinct = 00; opj_image_t *l_image = 00; OPJ_UINT32 p,q; OPJ_UINT32 l_level_no; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_gain; OPJ_INT32 l_x0b, l_y0b; OPJ_UINT32 l_tx0, l_ty0; /* extent of precincts , top left, bottom right**/ OPJ_INT32 l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end, l_br_prc_y_end; /* number of precinct for a resolution */ OPJ_UINT32 l_nb_precincts; /* room needed to store l_nb_precinct precinct for a resolution */ OPJ_UINT32 l_nb_precinct_size; /* number of code blocks for a precinct*/ OPJ_UINT32 l_nb_code_blocks; /* room needed to store l_nb_code_blocks code blocks for a precinct*/ OPJ_UINT32 l_nb_code_blocks_size; /* size of data for a tile */ OPJ_UINT32 l_data_size; l_cp = p_tcd->cp; l_tcp = &(l_cp->tcps[p_tile_no]); l_tile = p_tcd->tcd_image->tiles; l_tccp = l_tcp->tccps; l_tilec = l_tile->comps; l_image = p_tcd->image; l_image_comp = p_tcd->image->comps; p = p_tile_no % l_cp->tw; /* tile coordinates */ q = p_tile_no / l_cp->tw; /*fprintf(stderr, "Tile coordinate = %d,%d\n", p, q);*/ /* 4 borders of the tile rescale on the image if necessary */ l_tx0 = l_cp->tx0 + p * l_cp->tdx; /* can't be greater than l_image->x1 so won't overflow */ l_tile->x0 = (OPJ_INT32)opj_uint_max(l_tx0, l_image->x0); l_tile->x1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, l_cp->tdx), l_image->x1); l_ty0 = l_cp->ty0 + q * l_cp->tdy; /* can't be greater than l_image->y1 so won't overflow */ l_tile->y0 = (OPJ_INT32)opj_uint_max(l_ty0, l_image->y0); l_tile->y1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, l_cp->tdy), l_image->y1); /* testcase 1888.pdf.asan.35.988 */ if (l_tccp->numresolutions == 0) { opj_event_msg(manager, EVT_ERROR, "tiles require at least one resolution\n"); return OPJ_FALSE; } /*fprintf(stderr, "Tile border = %d,%d,%d,%d\n", l_tile->x0, l_tile->y0,l_tile->x1,l_tile->y1);*/ /*tile->numcomps = image->numcomps; */ for (compno = 0; compno < l_tile->numcomps; ++compno) { /*fprintf(stderr, "compno = %d/%d\n", compno, l_tile->numcomps);*/ l_image_comp->resno_decoded = 0; /* border of each l_tile component (global) */ l_tilec->x0 = opj_int_ceildiv(l_tile->x0, (OPJ_INT32)l_image_comp->dx); l_tilec->y0 = opj_int_ceildiv(l_tile->y0, (OPJ_INT32)l_image_comp->dy); l_tilec->x1 = opj_int_ceildiv(l_tile->x1, (OPJ_INT32)l_image_comp->dx); l_tilec->y1 = opj_int_ceildiv(l_tile->y1, (OPJ_INT32)l_image_comp->dy); /*fprintf(stderr, "\tTile compo border = %d,%d,%d,%d\n", l_tilec->x0, l_tilec->y0,l_tilec->x1,l_tilec->y1);*/ /* compute l_data_size with overflow check */ l_data_size = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0); /* issue 733, l_data_size == 0U, probably something wrong should be checked before getting here */ if ((l_data_size > 0U) && ((((OPJ_UINT32)-1) / l_data_size) < (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0))) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); return OPJ_FALSE; } l_data_size = l_data_size * (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0); if ((((OPJ_UINT32)-1) / (OPJ_UINT32)sizeof(OPJ_UINT32)) < l_data_size) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); return OPJ_FALSE; } l_data_size = l_data_size * (OPJ_UINT32)sizeof(OPJ_UINT32); l_tilec->numresolutions = l_tccp->numresolutions; if (l_tccp->numresolutions < l_cp->m_specific_param.m_dec.m_reduce) { l_tilec->minimum_num_resolutions = 1; } else { l_tilec->minimum_num_resolutions = l_tccp->numresolutions - l_cp->m_specific_param.m_dec.m_reduce; } l_tilec->data_size_needed = l_data_size; if (p_tcd->m_is_decoder && !opj_alloc_tile_component_data(l_tilec)) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n"); return OPJ_FALSE; } l_data_size = l_tilec->numresolutions * (OPJ_UINT32)sizeof(opj_tcd_resolution_t); if (l_tilec->resolutions == 00) { l_tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(l_data_size); if (! l_tilec->resolutions ) { return OPJ_FALSE; } /*fprintf(stderr, "\tAllocate resolutions of tilec (opj_tcd_resolution_t): %d\n",l_data_size);*/ l_tilec->resolutions_size = l_data_size; memset(l_tilec->resolutions,0,l_data_size); } else if (l_data_size > l_tilec->resolutions_size) { opj_tcd_resolution_t* new_resolutions = (opj_tcd_resolution_t *) opj_realloc(l_tilec->resolutions, l_data_size); if (! new_resolutions) { opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile resolutions\n"); opj_free(l_tilec->resolutions); l_tilec->resolutions = NULL; l_tilec->resolutions_size = 0; return OPJ_FALSE; } l_tilec->resolutions = new_resolutions; /*fprintf(stderr, "\tReallocate data of tilec (int): from %d to %d x OPJ_UINT32\n", l_tilec->resolutions_size, l_data_size);*/ memset(((OPJ_BYTE*) l_tilec->resolutions)+l_tilec->resolutions_size,0,l_data_size - l_tilec->resolutions_size); l_tilec->resolutions_size = l_data_size; } l_level_no = l_tilec->numresolutions; l_res = l_tilec->resolutions; l_step_size = l_tccp->stepsizes; if (l_tccp->qmfbid == 0) { l_gain_ptr = &opj_dwt_getgain_real; } else { l_gain_ptr = &opj_dwt_getgain; } /*fprintf(stderr, "\tlevel_no=%d\n",l_level_no);*/ for (resno = 0; resno < l_tilec->numresolutions; ++resno) { /*fprintf(stderr, "\t\tresno = %d/%d\n", resno, l_tilec->numresolutions);*/ OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/; OPJ_UINT32 cbgwidthexpn, cbgheightexpn; OPJ_UINT32 cblkwidthexpn, cblkheightexpn; --l_level_no; /* border for each resolution level (global) */ l_res->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no); l_res->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no); l_res->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no); l_res->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no); /*fprintf(stderr, "\t\t\tres_x0= %d, res_y0 =%d, res_x1=%d, res_y1=%d\n", l_res->x0, l_res->y0, l_res->x1, l_res->y1);*/ /* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; /*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/ /* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */ l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx; l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy; l_br_prc_x_end = opj_int_ceildivpow2(l_res->x1, (OPJ_INT32)l_pdx) << l_pdx; l_br_prc_y_end = opj_int_ceildivpow2(l_res->y1, (OPJ_INT32)l_pdy) << l_pdy; /*fprintf(stderr, "\t\t\tprc_x_start=%d, prc_y_start=%d, br_prc_x_end=%d, br_prc_y_end=%d \n", l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end ,l_br_prc_y_end );*/ l_res->pw = (l_res->x0 == l_res->x1) ? 0 : (OPJ_UINT32)((l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx); l_res->ph = (l_res->y0 == l_res->y1) ? 0 : (OPJ_UINT32)((l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy); /*fprintf(stderr, "\t\t\tres_pw=%d, res_ph=%d\n", l_res->pw, l_res->ph );*/ l_nb_precincts = l_res->pw * l_res->ph; l_nb_precinct_size = l_nb_precincts * (OPJ_UINT32)sizeof(opj_tcd_precinct_t); if (resno == 0) { tlcbgxstart = l_tl_prc_x_start; tlcbgystart = l_tl_prc_y_start; /*brcbgxend = l_br_prc_x_end;*/ /* brcbgyend = l_br_prc_y_end;*/ cbgwidthexpn = l_pdx; cbgheightexpn = l_pdy; l_res->numbands = 1; } else { tlcbgxstart = opj_int_ceildivpow2(l_tl_prc_x_start, 1); tlcbgystart = opj_int_ceildivpow2(l_tl_prc_y_start, 1); /*brcbgxend = opj_int_ceildivpow2(l_br_prc_x_end, 1);*/ /*brcbgyend = opj_int_ceildivpow2(l_br_prc_y_end, 1);*/ cbgwidthexpn = l_pdx - 1; cbgheightexpn = l_pdy - 1; l_res->numbands = 3; } cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn); cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn); l_band = l_res->bands; for (bandno = 0; bandno < l_res->numbands; ++bandno) { OPJ_INT32 numbps; /*fprintf(stderr, "\t\t\tband_no=%d/%d\n", bandno, l_res->numbands );*/ if (resno == 0) { l_band->bandno = 0 ; l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no); l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no); l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no); l_band->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no); } else { l_band->bandno = bandno + 1; /* x0b = 1 if bandno = 1 or 3 */ l_x0b = l_band->bandno&1; /* y0b = 1 if bandno = 2 or 3 */ l_y0b = (OPJ_INT32)((l_band->bandno)>>1); /* l_band border (global) */ l_band->x0 = opj_int64_ceildivpow2(l_tilec->x0 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->y0 = opj_int64_ceildivpow2(l_tilec->y0 - ((OPJ_INT64)l_y0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->x1 = opj_int64_ceildivpow2(l_tilec->x1 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); l_band->y1 = opj_int64_ceildivpow2(l_tilec->y1 - ((OPJ_INT64)l_y0b << l_level_no), (OPJ_INT32)(l_level_no + 1)); } /** avoid an if with storing function pointer */ l_gain = (*l_gain_ptr) (l_band->bandno); numbps = (OPJ_INT32)(l_image_comp->prec + l_gain); l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0, (OPJ_INT32) (numbps - l_step_size->expn)))) * fraction; l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits - 1; /* WHY -1 ? */ if (!l_band->precincts && (l_nb_precincts > 0U)) { l_band->precincts = (opj_tcd_precinct_t *) opj_malloc( /*3 * */ l_nb_precinct_size); if (! l_band->precincts) { return OPJ_FALSE; } /*fprintf(stderr, "\t\t\t\tAllocate precincts of a band (opj_tcd_precinct_t): %d\n",l_nb_precinct_size); */ memset(l_band->precincts,0,l_nb_precinct_size); l_band->precincts_data_size = l_nb_precinct_size; } else if (l_band->precincts_data_size < l_nb_precinct_size) { opj_tcd_precinct_t * new_precincts = (opj_tcd_precinct_t *) opj_realloc(l_band->precincts,/*3 * */ l_nb_precinct_size); if (! new_precincts) { opj_event_msg(manager, EVT_ERROR, "Not enough memory to handle band precints\n"); opj_free(l_band->precincts); l_band->precincts = NULL; l_band->precincts_data_size = 0; return OPJ_FALSE; } l_band->precincts = new_precincts; /*fprintf(stderr, "\t\t\t\tReallocate precincts of a band (opj_tcd_precinct_t): from %d to %d\n",l_band->precincts_data_size, l_nb_precinct_size);*/ memset(((OPJ_BYTE *) l_band->precincts) + l_band->precincts_data_size,0,l_nb_precinct_size - l_band->precincts_data_size); l_band->precincts_data_size = l_nb_precinct_size; } l_current_precinct = l_band->precincts; for (precno = 0; precno < l_nb_precincts; ++precno) { OPJ_INT32 tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend; OPJ_INT32 cbgxstart = tlcbgxstart + (OPJ_INT32)(precno % l_res->pw) * (1 << cbgwidthexpn); OPJ_INT32 cbgystart = tlcbgystart + (OPJ_INT32)(precno / l_res->pw) * (1 << cbgheightexpn); OPJ_INT32 cbgxend = cbgxstart + (1 << cbgwidthexpn); OPJ_INT32 cbgyend = cbgystart + (1 << cbgheightexpn); /*fprintf(stderr, "\t precno=%d; bandno=%d, resno=%d; compno=%d\n", precno, bandno , resno, compno);*/ /*fprintf(stderr, "\t tlcbgxstart(=%d) + (precno(=%d) percent res->pw(=%d)) * (1 << cbgwidthexpn(=%d)) \n",tlcbgxstart,precno,l_res->pw,cbgwidthexpn);*/ /* precinct size (global) */ /*fprintf(stderr, "\t cbgxstart=%d, l_band->x0 = %d \n",cbgxstart, l_band->x0);*/ l_current_precinct->x0 = opj_int_max(cbgxstart, l_band->x0); l_current_precinct->y0 = opj_int_max(cbgystart, l_band->y0); l_current_precinct->x1 = opj_int_min(cbgxend, l_band->x1); l_current_precinct->y1 = opj_int_min(cbgyend, l_band->y1); /*fprintf(stderr, "\t prc_x0=%d; prc_y0=%d, prc_x1=%d; prc_y1=%d\n",l_current_precinct->x0, l_current_precinct->y0 ,l_current_precinct->x1, l_current_precinct->y1);*/ tlcblkxstart = opj_int_floordivpow2(l_current_precinct->x0, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn; /*fprintf(stderr, "\t tlcblkxstart =%d\n",tlcblkxstart );*/ tlcblkystart = opj_int_floordivpow2(l_current_precinct->y0, (OPJ_INT32)cblkheightexpn) << cblkheightexpn; /*fprintf(stderr, "\t tlcblkystart =%d\n",tlcblkystart );*/ brcblkxend = opj_int_ceildivpow2(l_current_precinct->x1, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn; /*fprintf(stderr, "\t brcblkxend =%d\n",brcblkxend );*/ brcblkyend = opj_int_ceildivpow2(l_current_precinct->y1, (OPJ_INT32)cblkheightexpn) << cblkheightexpn; /*fprintf(stderr, "\t brcblkyend =%d\n",brcblkyend );*/ l_current_precinct->cw = (OPJ_UINT32)((brcblkxend - tlcblkxstart) >> cblkwidthexpn); l_current_precinct->ch = (OPJ_UINT32)((brcblkyend - tlcblkystart) >> cblkheightexpn); l_nb_code_blocks = l_current_precinct->cw * l_current_precinct->ch; /*fprintf(stderr, "\t\t\t\t precinct_cw = %d x recinct_ch = %d\n",l_current_precinct->cw, l_current_precinct->ch); */ l_nb_code_blocks_size = l_nb_code_blocks * (OPJ_UINT32)sizeof_block; if (!l_current_precinct->cblks.blocks && (l_nb_code_blocks > 0U)) { l_current_precinct->cblks.blocks = opj_malloc(l_nb_code_blocks_size); if (! l_current_precinct->cblks.blocks ) { return OPJ_FALSE; } /*fprintf(stderr, "\t\t\t\tAllocate cblks of a precinct (opj_tcd_cblk_dec_t): %d\n",l_nb_code_blocks_size);*/ memset(l_current_precinct->cblks.blocks,0,l_nb_code_blocks_size); l_current_precinct->block_size = l_nb_code_blocks_size; } else if (l_nb_code_blocks_size > l_current_precinct->block_size) { void *new_blocks = opj_realloc(l_current_precinct->cblks.blocks, l_nb_code_blocks_size); if (! new_blocks) { opj_free(l_current_precinct->cblks.blocks); l_current_precinct->cblks.blocks = NULL; l_current_precinct->block_size = 0; opj_event_msg(manager, EVT_ERROR, "Not enough memory for current precinct codeblock element\n"); return OPJ_FALSE; } l_current_precinct->cblks.blocks = new_blocks; /*fprintf(stderr, "\t\t\t\tReallocate cblks of a precinct (opj_tcd_cblk_dec_t): from %d to %d\n",l_current_precinct->block_size, l_nb_code_blocks_size); */ memset(((OPJ_BYTE *) l_current_precinct->cblks.blocks) + l_current_precinct->block_size ,0 ,l_nb_code_blocks_size - l_current_precinct->block_size); l_current_precinct->block_size = l_nb_code_blocks_size; } if (! l_current_precinct->incltree) { l_current_precinct->incltree = opj_tgt_create(l_current_precinct->cw, l_current_precinct->ch, manager); } else{ l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree, l_current_precinct->cw, l_current_precinct->ch, manager); } if (! l_current_precinct->incltree) { opj_event_msg(manager, EVT_WARNING, "No incltree created.\n"); /*return OPJ_FALSE;*/ } if (! l_current_precinct->imsbtree) { l_current_precinct->imsbtree = opj_tgt_create(l_current_precinct->cw, l_current_precinct->ch, manager); } else { l_current_precinct->imsbtree = opj_tgt_init(l_current_precinct->imsbtree, l_current_precinct->cw, l_current_precinct->ch, manager); } if (! l_current_precinct->imsbtree) { opj_event_msg(manager, EVT_WARNING, "No imsbtree created.\n"); /*return OPJ_FALSE;*/ } for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { OPJ_INT32 cblkxstart = tlcblkxstart + (OPJ_INT32)(cblkno % l_current_precinct->cw) * (1 << cblkwidthexpn); OPJ_INT32 cblkystart = tlcblkystart + (OPJ_INT32)(cblkno / l_current_precinct->cw) * (1 << cblkheightexpn); OPJ_INT32 cblkxend = cblkxstart + (1 << cblkwidthexpn); OPJ_INT32 cblkyend = cblkystart + (1 << cblkheightexpn); if (isEncoder) { opj_tcd_cblk_enc_t* l_code_block = l_current_precinct->cblks.enc + cblkno; if (! opj_tcd_code_block_enc_allocate(l_code_block)) { return OPJ_FALSE; } /* code-block size (global) */ l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0); l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0); l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1); l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1); if (! opj_tcd_code_block_enc_allocate_data(l_code_block)) { return OPJ_FALSE; } } else { opj_tcd_cblk_dec_t* l_code_block = l_current_precinct->cblks.dec + cblkno; if (! opj_tcd_code_block_dec_allocate(l_code_block)) { return OPJ_FALSE; } /* code-block size (global) */ l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0); l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0); l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1); l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1); } } ++l_current_precinct; } /* precno */ ++l_band; ++l_step_size; } /* bandno */ ++l_res; } /* resno */ ++l_tccp; ++l_tilec; ++l_image_comp; } /* compno */ return OPJ_TRUE; } OPJ_BOOL opj_tcd_init_encode_tile (opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, opj_event_mgr_t* p_manager) { return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_TRUE, 1.0F, sizeof(opj_tcd_cblk_enc_t), p_manager); } OPJ_BOOL opj_tcd_init_decode_tile (opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, opj_event_mgr_t* p_manager) { return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_FALSE, 0.5F, sizeof(opj_tcd_cblk_dec_t), p_manager); } /** * Allocates memory for an encoding code block (but not data memory). */ static OPJ_BOOL opj_tcd_code_block_enc_allocate (opj_tcd_cblk_enc_t * p_code_block) { if (! p_code_block->layers) { /* no memset since data */ p_code_block->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t)); if (! p_code_block->layers) { return OPJ_FALSE; } } if (! p_code_block->passes) { p_code_block->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t)); if (! p_code_block->passes) { return OPJ_FALSE; } } return OPJ_TRUE; } /** * Allocates data memory for an encoding code block. */ static OPJ_BOOL opj_tcd_code_block_enc_allocate_data (opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; l_data_size = (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { opj_free(p_code_block->data - 1); /* again, why -1 */ } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size+1); if(! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; p_code_block->data[0] = 0; p_code_block->data+=1; /*why +1 ?*/ } return OPJ_TRUE; } /** * Allocates memory for a decoding code block. */ static OPJ_BOOL opj_tcd_code_block_dec_allocate (opj_tcd_cblk_dec_t * p_code_block) { if (! p_code_block->data) { p_code_block->data = (OPJ_BYTE*) opj_malloc(OPJ_J2K_DEFAULT_CBLK_DATA_SIZE); if (! p_code_block->data) { return OPJ_FALSE; } p_code_block->data_max_size = OPJ_J2K_DEFAULT_CBLK_DATA_SIZE; /*fprintf(stderr, "Allocate 8192 elements of code_block->data\n");*/ p_code_block->segs = (opj_tcd_seg_t *) opj_calloc(OPJ_J2K_DEFAULT_NB_SEGS,sizeof(opj_tcd_seg_t)); if (! p_code_block->segs) { return OPJ_FALSE; } /*fprintf(stderr, "Allocate %d elements of code_block->data\n", OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));*/ p_code_block->m_current_max_segs = OPJ_J2K_DEFAULT_NB_SEGS; /*fprintf(stderr, "m_current_max_segs of code_block->data = %d\n", p_code_block->m_current_max_segs);*/ } else { /* sanitize */ OPJ_BYTE* l_data = p_code_block->data; OPJ_UINT32 l_data_max_size = p_code_block->data_max_size; opj_tcd_seg_t * l_segs = p_code_block->segs; OPJ_UINT32 l_current_max_segs = p_code_block->m_current_max_segs; memset(p_code_block, 0, sizeof(opj_tcd_cblk_dec_t)); p_code_block->data = l_data; p_code_block->data_max_size = l_data_max_size; p_code_block->segs = l_segs; p_code_block->m_current_max_segs = l_current_max_segs; } return OPJ_TRUE; } OPJ_UINT32 opj_tcd_get_decoded_tile_size ( opj_tcd_t *p_tcd ) { OPJ_UINT32 i; OPJ_UINT32 l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tcd_resolution_t * l_res = 00; OPJ_UINT32 l_size_comp, l_remaining; l_tile_comp = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ if(l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } l_res = l_tile_comp->resolutions + l_tile_comp->minimum_num_resolutions - 1; l_data_size += l_size_comp * (OPJ_UINT32)((l_res->x1 - l_res->x0) * (l_res->y1 - l_res->y0)); ++l_img_comp; ++l_tile_comp; } return l_data_size; } OPJ_BOOL opj_tcd_encode_tile( opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BYTE *p_dest, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_length, opj_codestream_info_t *p_cstr_info) { if (p_tcd->cur_tp_num == 0) { p_tcd->tcd_tileno = p_tile_no; p_tcd->tcp = &p_tcd->cp->tcps[p_tile_no]; /* INDEX >> "Precinct_nb_X et Precinct_nb_Y" */ if(p_cstr_info) { OPJ_UINT32 l_num_packs = 0; OPJ_UINT32 i; opj_tcd_tilecomp_t *l_tilec_idx = &p_tcd->tcd_image->tiles->comps[0]; /* based on component 0 */ opj_tccp_t *l_tccp = p_tcd->tcp->tccps; /* based on component 0 */ for (i = 0; i < l_tilec_idx->numresolutions; i++) { opj_tcd_resolution_t *l_res_idx = &l_tilec_idx->resolutions[i]; p_cstr_info->tile[p_tile_no].pw[i] = (int)l_res_idx->pw; p_cstr_info->tile[p_tile_no].ph[i] = (int)l_res_idx->ph; l_num_packs += l_res_idx->pw * l_res_idx->ph; p_cstr_info->tile[p_tile_no].pdx[i] = (int)l_tccp->prcw[i]; p_cstr_info->tile[p_tile_no].pdy[i] = (int)l_tccp->prch[i]; } p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t*) opj_calloc((size_t)p_cstr_info->numcomps * (size_t)p_cstr_info->numlayers * l_num_packs, sizeof(opj_packet_info_t)); if (!p_cstr_info->tile[p_tile_no].packet) { /* FIXME event manager error callback */ return OPJ_FALSE; } } /* << INDEX */ /* FIXME _ProfStart(PGROUP_DC_SHIFT); */ /*---------------TILE-------------------*/ if (! opj_tcd_dc_level_shift_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DC_SHIFT); */ /* FIXME _ProfStart(PGROUP_MCT); */ if (! opj_tcd_mct_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_MCT); */ /* FIXME _ProfStart(PGROUP_DWT); */ if (! opj_tcd_dwt_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DWT); */ /* FIXME _ProfStart(PGROUP_T1); */ if (! opj_tcd_t1_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T1); */ /* FIXME _ProfStart(PGROUP_RATE); */ if (! opj_tcd_rate_allocate_encode(p_tcd,p_dest,p_max_length,p_cstr_info)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_RATE); */ } /*--------------TIER2------------------*/ /* INDEX */ if (p_cstr_info) { p_cstr_info->index_write = 1; } /* FIXME _ProfStart(PGROUP_T2); */ if (! opj_tcd_t2_encode(p_tcd,p_dest,p_data_written,p_max_length,p_cstr_info)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T2); */ /*---------------CLEAN-------------------*/ return OPJ_TRUE; } OPJ_BOOL opj_tcd_decode_tile( opj_tcd_t *p_tcd, OPJ_BYTE *p_src, OPJ_UINT32 p_max_length, OPJ_UINT32 p_tile_no, opj_codestream_index_t *p_cstr_index, opj_event_mgr_t *p_manager ) { OPJ_UINT32 l_data_read; p_tcd->tcd_tileno = p_tile_no; p_tcd->tcp = &(p_tcd->cp->tcps[p_tile_no]); #ifdef TODO_MSD /* FIXME */ /* INDEX >> */ if(p_cstr_info) { OPJ_UINT32 resno, compno, numprec = 0; for (compno = 0; compno < (OPJ_UINT32) p_cstr_info->numcomps; compno++) { opj_tcp_t *tcp = &p_tcd->cp->tcps[0]; opj_tccp_t *tccp = &tcp->tccps[compno]; opj_tcd_tilecomp_t *tilec_idx = &p_tcd->tcd_image->tiles->comps[compno]; for (resno = 0; resno < tilec_idx->numresolutions; resno++) { opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[resno]; p_cstr_info->tile[p_tile_no].pw[resno] = res_idx->pw; p_cstr_info->tile[p_tile_no].ph[resno] = res_idx->ph; numprec += res_idx->pw * res_idx->ph; p_cstr_info->tile[p_tile_no].pdx[resno] = tccp->prcw[resno]; p_cstr_info->tile[p_tile_no].pdy[resno] = tccp->prch[resno]; } } p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t *) opj_malloc(p_cstr_info->numlayers * numprec * sizeof(opj_packet_info_t)); p_cstr_info->packno = 0; } /* << INDEX */ #endif /*--------------TIER2------------------*/ /* FIXME _ProfStart(PGROUP_T2); */ l_data_read = 0; if (! opj_tcd_t2_decode(p_tcd, p_src, &l_data_read, p_max_length, p_cstr_index, p_manager)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T2); */ /*------------------TIER1-----------------*/ /* FIXME _ProfStart(PGROUP_T1); */ if (! opj_tcd_t1_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T1); */ /*----------------DWT---------------------*/ /* FIXME _ProfStart(PGROUP_DWT); */ if (! opj_tcd_dwt_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DWT); */ /*----------------MCT-------------------*/ /* FIXME _ProfStart(PGROUP_MCT); */ if (! opj_tcd_mct_decode(p_tcd, p_manager)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_MCT); */ /* FIXME _ProfStart(PGROUP_DC_SHIFT); */ if (! opj_tcd_dc_level_shift_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DC_SHIFT); */ /*---------------TILE-------------------*/ return OPJ_TRUE; } OPJ_BOOL opj_tcd_update_tile_data ( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest, OPJ_UINT32 p_dest_length ) { OPJ_UINT32 i,j,k,l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; opj_tcd_resolution_t * l_res; OPJ_UINT32 l_size_comp, l_remaining; OPJ_UINT32 l_stride, l_width,l_height; l_data_size = opj_tcd_get_decoded_tile_size(p_tcd); if (l_data_size > p_dest_length) { return OPJ_FALSE; } l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ l_res = l_tilec->resolutions + l_img_comp->resno_decoded; l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0); l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0); l_stride = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0) - l_width; if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } switch (l_size_comp) { case 1: { OPJ_CHAR * l_dest_ptr = (OPJ_CHAR *) p_dest; const OPJ_INT32 * l_src_ptr = l_tilec->data; if (l_img_comp->sgnd) { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_CHAR) (*(l_src_ptr++)); } l_src_ptr += l_stride; } } else { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_CHAR) ((*(l_src_ptr++))&0xff); } l_src_ptr += l_stride; } } p_dest = (OPJ_BYTE *)l_dest_ptr; } break; case 2: { const OPJ_INT32 * l_src_ptr = l_tilec->data; OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_dest; if (l_img_comp->sgnd) { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_INT16) (*(l_src_ptr++)); } l_src_ptr += l_stride; } } else { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_INT16) ((*(l_src_ptr++))&0xffff); } l_src_ptr += l_stride; } } p_dest = (OPJ_BYTE*) l_dest_ptr; } break; case 4: { OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_dest; OPJ_INT32 * l_src_ptr = l_tilec->data; for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (*(l_src_ptr++)); } l_src_ptr += l_stride; } p_dest = (OPJ_BYTE*) l_dest_ptr; } break; } ++l_img_comp; ++l_tilec; } return OPJ_TRUE; } static void opj_tcd_free_tile(opj_tcd_t *p_tcd) { OPJ_UINT32 compno, resno, bandno, precno; opj_tcd_tile_t *l_tile = 00; opj_tcd_tilecomp_t *l_tile_comp = 00; opj_tcd_resolution_t *l_res = 00; opj_tcd_band_t *l_band = 00; opj_tcd_precinct_t *l_precinct = 00; OPJ_UINT32 l_nb_resolutions, l_nb_precincts; void (* l_tcd_code_block_deallocate) (opj_tcd_precinct_t *) = 00; if (! p_tcd) { return; } if (! p_tcd->tcd_image) { return; } if (p_tcd->m_is_decoder) { l_tcd_code_block_deallocate = opj_tcd_code_block_dec_deallocate; } else { l_tcd_code_block_deallocate = opj_tcd_code_block_enc_deallocate; } l_tile = p_tcd->tcd_image->tiles; if (! l_tile) { return; } l_tile_comp = l_tile->comps; for (compno = 0; compno < l_tile->numcomps; ++compno) { l_res = l_tile_comp->resolutions; if (l_res) { l_nb_resolutions = l_tile_comp->resolutions_size / sizeof(opj_tcd_resolution_t); for (resno = 0; resno < l_nb_resolutions; ++resno) { l_band = l_res->bands; for (bandno = 0; bandno < 3; ++bandno) { l_precinct = l_band->precincts; if (l_precinct) { l_nb_precincts = l_band->precincts_data_size / sizeof(opj_tcd_precinct_t); for (precno = 0; precno < l_nb_precincts; ++precno) { opj_tgt_destroy(l_precinct->incltree); l_precinct->incltree = 00; opj_tgt_destroy(l_precinct->imsbtree); l_precinct->imsbtree = 00; (*l_tcd_code_block_deallocate) (l_precinct); ++l_precinct; } opj_free(l_band->precincts); l_band->precincts = 00; } ++l_band; } /* for (resno */ ++l_res; } opj_free(l_tile_comp->resolutions); l_tile_comp->resolutions = 00; } if (l_tile_comp->ownsData && l_tile_comp->data) { opj_aligned_free(l_tile_comp->data); l_tile_comp->data = 00; l_tile_comp->ownsData = 0; l_tile_comp->data_size = 0; l_tile_comp->data_size_needed = 0; } ++l_tile_comp; } opj_free(l_tile->comps); l_tile->comps = 00; opj_free(p_tcd->tcd_image->tiles); p_tcd->tcd_image->tiles = 00; } static OPJ_BOOL opj_tcd_t2_decode (opj_tcd_t *p_tcd, OPJ_BYTE * p_src_data, OPJ_UINT32 * p_data_read, OPJ_UINT32 p_max_src_size, opj_codestream_index_t *p_cstr_index, opj_event_mgr_t *p_manager ) { opj_t2_t * l_t2; l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp); if (l_t2 == 00) { return OPJ_FALSE; } if (! opj_t2_decode_packets( l_t2, p_tcd->tcd_tileno, p_tcd->tcd_image->tiles, p_src_data, p_data_read, p_max_src_size, p_cstr_index, p_manager)) { opj_t2_destroy(l_t2); return OPJ_FALSE; } opj_t2_destroy(l_t2); /*---------------CLEAN-------------------*/ return OPJ_TRUE; } static OPJ_BOOL opj_tcd_t1_decode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_t1_t * l_t1; opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t* l_tile_comp = l_tile->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; l_t1 = opj_t1_create(OPJ_FALSE); if (l_t1 == 00) { return OPJ_FALSE; } for (compno = 0; compno < l_tile->numcomps; ++compno) { /* The +3 is headroom required by the vectorized DWT */ if (OPJ_FALSE == opj_t1_decode_cblks(l_t1, l_tile_comp, l_tccp)) { opj_t1_destroy(l_t1); return OPJ_FALSE; } ++l_tile_comp; ++l_tccp; } opj_t1_destroy(l_t1); return OPJ_TRUE; } static OPJ_BOOL opj_tcd_dwt_decode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; opj_image_comp_t * l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { /* if (tcd->cp->reduce != 0) { tcd->image->comps[compno].resno_decoded = tile->comps[compno].numresolutions - tcd->cp->reduce - 1; if (tcd->image->comps[compno].resno_decoded < 0) { return false; } } numres2decode = tcd->image->comps[compno].resno_decoded + 1; if(numres2decode > 0){ */ if (l_tccp->qmfbid == 1) { if (! opj_dwt_decode(l_tile_comp, l_img_comp->resno_decoded+1)) { return OPJ_FALSE; } } else { if (! opj_dwt_decode_real(l_tile_comp, l_img_comp->resno_decoded+1)) { return OPJ_FALSE; } } ++l_tile_comp; ++l_img_comp; ++l_tccp; } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_mct_decode ( opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcp_t * l_tcp = p_tcd->tcp; opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps; OPJ_UINT32 l_samples,i; if (! l_tcp->mct) { return OPJ_TRUE; } l_samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); if (l_tile->numcomps >= 3 ){ /* testcase 1336.pdf.asan.47.376 */ if ((l_tile->comps[0].x1 - l_tile->comps[0].x0) * (l_tile->comps[0].y1 - l_tile->comps[0].y0) < (OPJ_INT32)l_samples || (l_tile->comps[1].x1 - l_tile->comps[1].x0) * (l_tile->comps[1].y1 - l_tile->comps[1].y0) < (OPJ_INT32)l_samples || (l_tile->comps[2].x1 - l_tile->comps[2].x0) * (l_tile->comps[2].y1 - l_tile->comps[2].y0) < (OPJ_INT32)l_samples) { opj_event_msg(p_manager, EVT_ERROR, "Tiles don't all have the same dimension. Skip the MCT step.\n"); return OPJ_FALSE; } else if (l_tcp->mct == 2) { OPJ_BYTE ** l_data; if (! l_tcp->m_mct_decoding_matrix) { return OPJ_TRUE; } l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps*sizeof(OPJ_BYTE*)); if (! l_data) { return OPJ_FALSE; } for (i=0;i<l_tile->numcomps;++i) { l_data[i] = (OPJ_BYTE*) l_tile_comp->data; ++l_tile_comp; } if (! opj_mct_decode_custom(/* MCT data */ (OPJ_BYTE*) l_tcp->m_mct_decoding_matrix, /* size of components */ l_samples, /* components */ l_data, /* nb of components (i.e. size of pData) */ l_tile->numcomps, /* tells if the data is signed */ p_tcd->image->comps->sgnd)) { opj_free(l_data); return OPJ_FALSE; } opj_free(l_data); } else { if (l_tcp->tccps->qmfbid == 1) { opj_mct_decode( l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, l_samples); } else { opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data, (OPJ_FLOAT32*)l_tile->comps[1].data, (OPJ_FLOAT32*)l_tile->comps[2].data, l_samples); } } } else { opj_event_msg(p_manager, EVT_ERROR, "Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",l_tile->numcomps); } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_dc_level_shift_decode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tccp_t * l_tccp = 00; opj_image_comp_t * l_img_comp = 00; opj_tcd_resolution_t* l_res = 00; opj_tcd_tile_t * l_tile; OPJ_UINT32 l_width,l_height,i,j; OPJ_INT32 * l_current_ptr; OPJ_INT32 l_min, l_max; OPJ_UINT32 l_stride; l_tile = p_tcd->tcd_image->tiles; l_tile_comp = l_tile->comps; l_tccp = p_tcd->tcp->tccps; l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { l_res = l_tile_comp->resolutions + l_img_comp->resno_decoded; l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0); l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0); l_stride = (OPJ_UINT32)(l_tile_comp->x1 - l_tile_comp->x0) - l_width; assert(l_height == 0 || l_width + l_stride <= l_tile_comp->data_size / l_height); /*MUPDF*/ if (l_img_comp->sgnd) { l_min = -(1 << (l_img_comp->prec - 1)); l_max = (1 << (l_img_comp->prec - 1)) - 1; } else { l_min = 0; l_max = (1 << l_img_comp->prec) - 1; } l_current_ptr = l_tile_comp->data; if (l_tccp->qmfbid == 1) { for (j=0;j<l_height;++j) { for (i = 0; i < l_width; ++i) { *l_current_ptr = opj_int_clamp(*l_current_ptr + l_tccp->m_dc_level_shift, l_min, l_max); ++l_current_ptr; } l_current_ptr += l_stride; } } else { for (j=0;j<l_height;++j) { for (i = 0; i < l_width; ++i) { OPJ_FLOAT32 l_value = *((OPJ_FLOAT32 *) l_current_ptr); *l_current_ptr = opj_int_clamp((OPJ_INT32)opj_lrintf(l_value) + l_tccp->m_dc_level_shift, l_min, l_max); ; ++l_current_ptr; } l_current_ptr += l_stride; } } ++l_img_comp; ++l_tccp; ++l_tile_comp; } return OPJ_TRUE; } /** * Deallocates the encoding data of the given precinct. */ static void opj_tcd_code_block_dec_deallocate (opj_tcd_precinct_t * p_precinct) { OPJ_UINT32 cblkno , l_nb_code_blocks; opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec; if (l_code_block) { /*fprintf(stderr,"deallocate codeblock:{\n");*/ /*fprintf(stderr,"\t x0=%d, y0=%d, x1=%d, y1=%d\n",l_code_block->x0, l_code_block->y0, l_code_block->x1, l_code_block->y1);*/ /*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ", l_code_block->numbps, l_code_block->numlenbits, l_code_block->len, l_code_block->numnewpasses, l_code_block->real_num_segs, l_code_block->m_current_max_segs );*/ l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t); /*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/ for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { if (l_code_block->data) { opj_free(l_code_block->data); l_code_block->data = 00; } if (l_code_block->segs) { opj_free(l_code_block->segs ); l_code_block->segs = 00; } ++l_code_block; } opj_free(p_precinct->cblks.dec); p_precinct->cblks.dec = 00; } } /** * Deallocates the encoding data of the given precinct. */ static void opj_tcd_code_block_enc_deallocate (opj_tcd_precinct_t * p_precinct) { OPJ_UINT32 cblkno , l_nb_code_blocks; opj_tcd_cblk_enc_t * l_code_block = p_precinct->cblks.enc; if (l_code_block) { l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_enc_t); for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { if (l_code_block->data) { opj_free(l_code_block->data - 1); l_code_block->data = 00; } if (l_code_block->layers) { opj_free(l_code_block->layers ); l_code_block->layers = 00; } if (l_code_block->passes) { opj_free(l_code_block->passes ); l_code_block->passes = 00; } ++l_code_block; } opj_free(p_precinct->cblks.enc); p_precinct->cblks.enc = 00; } } OPJ_UINT32 opj_tcd_get_encoded_tile_size ( opj_tcd_t *p_tcd ) { OPJ_UINT32 i,l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; OPJ_UINT32 l_size_comp, l_remaining; l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } l_data_size += l_size_comp * (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 - l_tilec->y0)); ++l_img_comp; ++l_tilec; } return l_data_size; } static OPJ_BOOL opj_tcd_dc_level_shift_encode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tccp_t * l_tccp = 00; opj_image_comp_t * l_img_comp = 00; opj_tcd_tile_t * l_tile; OPJ_UINT32 l_nb_elem,i; OPJ_INT32 * l_current_ptr; l_tile = p_tcd->tcd_image->tiles; l_tile_comp = l_tile->comps; l_tccp = p_tcd->tcp->tccps; l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { l_current_ptr = l_tile_comp->data; l_nb_elem = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); if (l_tccp->qmfbid == 1) { for (i = 0; i < l_nb_elem; ++i) { *l_current_ptr -= l_tccp->m_dc_level_shift ; ++l_current_ptr; } } else { for (i = 0; i < l_nb_elem; ++i) { *l_current_ptr = (*l_current_ptr - l_tccp->m_dc_level_shift) * (1 << 11); ++l_current_ptr; } } ++l_img_comp; ++l_tccp; ++l_tile_comp; } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_mct_encode ( opj_tcd_t *p_tcd ) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps; OPJ_UINT32 samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); OPJ_UINT32 i; OPJ_BYTE ** l_data = 00; opj_tcp_t * l_tcp = p_tcd->tcp; if(!p_tcd->tcp->mct) { return OPJ_TRUE; } if (p_tcd->tcp->mct == 2) { if (! p_tcd->tcp->m_mct_coding_matrix) { return OPJ_TRUE; } l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps*sizeof(OPJ_BYTE*)); if (! l_data) { return OPJ_FALSE; } for (i=0;i<l_tile->numcomps;++i) { l_data[i] = (OPJ_BYTE*) l_tile_comp->data; ++l_tile_comp; } if (! opj_mct_encode_custom(/* MCT data */ (OPJ_BYTE*) p_tcd->tcp->m_mct_coding_matrix, /* size of components */ samples, /* components */ l_data, /* nb of components (i.e. size of pData) */ l_tile->numcomps, /* tells if the data is signed */ p_tcd->image->comps->sgnd) ) { opj_free(l_data); return OPJ_FALSE; } opj_free(l_data); } else if (l_tcp->tccps->qmfbid == 0) { opj_mct_encode_real(l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, samples); } else { opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, samples); } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_dwt_encode ( opj_tcd_t *p_tcd ) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; OPJ_UINT32 compno; for (compno = 0; compno < l_tile->numcomps; ++compno) { if (l_tccp->qmfbid == 1) { if (! opj_dwt_encode(l_tile_comp)) { return OPJ_FALSE; } } else if (l_tccp->qmfbid == 0) { if (! opj_dwt_encode_real(l_tile_comp)) { return OPJ_FALSE; } } ++l_tile_comp; ++l_tccp; } return OPJ_TRUE; } static OPJ_BOOL opj_tcd_t1_encode ( opj_tcd_t *p_tcd ) { opj_t1_t * l_t1; const OPJ_FLOAT64 * l_mct_norms; OPJ_UINT32 l_mct_numcomps = 0U; opj_tcp_t * l_tcp = p_tcd->tcp; l_t1 = opj_t1_create(OPJ_TRUE); if (l_t1 == 00) { return OPJ_FALSE; } if (l_tcp->mct == 1) { l_mct_numcomps = 3U; /* irreversible encoding */ if (l_tcp->tccps->qmfbid == 0) { l_mct_norms = opj_mct_get_mct_norms_real(); } else { l_mct_norms = opj_mct_get_mct_norms(); } } else { l_mct_numcomps = p_tcd->image->numcomps; l_mct_norms = (const OPJ_FLOAT64 *) (l_tcp->mct_norms); } if (! opj_t1_encode_cblks(l_t1, p_tcd->tcd_image->tiles , l_tcp, l_mct_norms, l_mct_numcomps)) { opj_t1_destroy(l_t1); return OPJ_FALSE; } opj_t1_destroy(l_t1); return OPJ_TRUE; } static OPJ_BOOL opj_tcd_t2_encode (opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ) { opj_t2_t * l_t2; l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp); if (l_t2 == 00) { return OPJ_FALSE; } if (! opj_t2_encode_packets( l_t2, p_tcd->tcd_tileno, p_tcd->tcd_image->tiles, p_tcd->tcp->numlayers, p_dest_data, p_data_written, p_max_dest_size, p_cstr_info, p_tcd->tp_num, p_tcd->tp_pos, p_tcd->cur_pino, FINAL_PASS)) { opj_t2_destroy(l_t2); return OPJ_FALSE; } opj_t2_destroy(l_t2); /*---------------CLEAN-------------------*/ return OPJ_TRUE; } static OPJ_BOOL opj_tcd_rate_allocate_encode( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ) { opj_cp_t * l_cp = p_tcd->cp; OPJ_UINT32 l_nb_written = 0; if (p_cstr_info) { p_cstr_info->index_write = 0; } if (l_cp->m_specific_param.m_enc.m_disto_alloc|| l_cp->m_specific_param.m_enc.m_fixed_quality) { /* fixed_quality */ /* Normal Rate/distortion allocation */ if (! opj_tcd_rateallocate(p_tcd, p_dest_data,&l_nb_written, p_max_dest_size, p_cstr_info)) { return OPJ_FALSE; } } else { /* Fixed layer allocation */ opj_tcd_rateallocate_fixed(p_tcd); } return OPJ_TRUE; } OPJ_BOOL opj_tcd_copy_tile_data ( opj_tcd_t *p_tcd, OPJ_BYTE * p_src, OPJ_UINT32 p_src_length ) { OPJ_UINT32 i,j,l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; OPJ_UINT32 l_size_comp, l_remaining; OPJ_UINT32 l_nb_elem; l_data_size = opj_tcd_get_encoded_tile_size(p_tcd); if (l_data_size != p_src_length) { return OPJ_FALSE; } l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ l_nb_elem = (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 - l_tilec->y0)); if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } switch (l_size_comp) { case 1: { OPJ_CHAR * l_src_ptr = (OPJ_CHAR *) p_src; OPJ_INT32 * l_dest_ptr = l_tilec->data; if (l_img_comp->sgnd) { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++)); } } else { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (*(l_src_ptr++))&0xff; } } p_src = (OPJ_BYTE*) l_src_ptr; } break; case 2: { OPJ_INT32 * l_dest_ptr = l_tilec->data; OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_src; if (l_img_comp->sgnd) { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++)); } } else { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (*(l_src_ptr++))&0xffff; } } p_src = (OPJ_BYTE*) l_src_ptr; } break; case 4: { OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_src; OPJ_INT32 * l_dest_ptr = l_tilec->data; for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++)); } p_src = (OPJ_BYTE*) l_src_ptr; } break; } ++l_img_comp; ++l_tilec; } return OPJ_TRUE; }
./CrossVul/dataset_final_sorted/CWE-369/c/good_5063_0
crossvul-cpp_data_bad_1009_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF EEEEE AAA TTTTT U U RRRR EEEEE % % F E A A T U U R R E % % FFF EEE AAAAA T U U RRRR EEE % % F E A A T U U R R E % % F EEEEE A A T UUU R R EEEEE % % % % % % MagickCore Image Feature Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 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://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/animate.h" #include "magick/artifact.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/display.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/feature.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/image-private.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/matrix.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/morphology-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/semaphore.h" #include "magick/signature-private.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/timer.h" #include "magick/token.h" #include "magick/utility.h" #include "magick/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a n n y E d g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CannyEdgeImage() uses a multi-stage algorithm to detect a wide range of % edges in images. % % The format of the CannyEdgeImage method is: % % Image *CannyEdgeImage(const Image *image,const double radius, % const double sigma,const double lower_percent, % const double upper_percent,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the gaussian smoothing filter. % % o sigma: the sigma of the gaussian smoothing filter. % % o lower_percent: percentage of edge pixels in the lower threshold. % % o upper_percent: percentage of edge pixels in the upper threshold. % % o exception: return any errors or warnings in this structure. % */ typedef struct _CannyInfo { double magnitude, intensity; int orientation; ssize_t x, y; } CannyInfo; static inline MagickBooleanType IsAuthenticPixel(const Image *image, const ssize_t x,const ssize_t y) { if ((x < 0) || (x >= (ssize_t) image->columns)) return(MagickFalse); if ((y < 0) || (y >= (ssize_t) image->rows)) return(MagickFalse); return(MagickTrue); } static MagickBooleanType TraceEdges(Image *edge_image,CacheView *edge_view, MatrixInfo *canny_cache,const ssize_t x,const ssize_t y, const double lower_threshold,ExceptionInfo *exception) { CannyInfo edge, pixel; MagickBooleanType status; register PixelPacket *q; register ssize_t i; q=GetCacheViewAuthenticPixels(edge_view,x,y,1,1,exception); if (q == (PixelPacket *) NULL) return(MagickFalse); q->red=QuantumRange; q->green=QuantumRange; q->blue=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); if (GetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); edge.x=x; edge.y=y; if (SetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); for (i=1; i != 0; ) { ssize_t v; i--; status=GetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); for (v=(-1); v <= 1; v++) { ssize_t u; for (u=(-1); u <= 1; u++) { if ((u == 0) && (v == 0)) continue; if (IsAuthenticPixel(edge_image,edge.x+u,edge.y+v) == MagickFalse) continue; /* Not an edge if gradient value is below the lower threshold. */ q=GetCacheViewAuthenticPixels(edge_view,edge.x+u,edge.y+v,1,1, exception); if (q == (PixelPacket *) NULL) return(MagickFalse); status=GetMatrixElement(canny_cache,edge.x+u,edge.y+v,&pixel); if (status == MagickFalse) return(MagickFalse); if ((GetPixelIntensity(edge_image,q) == 0.0) && (pixel.intensity >= lower_threshold)) { q->red=QuantumRange; q->green=QuantumRange; q->blue=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); edge.x+=u; edge.y+=v; status=SetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); i++; } } } } return(MagickTrue); } MagickExport Image *CannyEdgeImage(const Image *image,const double radius, const double sigma,const double lower_percent,const double upper_percent, ExceptionInfo *exception) { #define CannyEdgeImageTag "CannyEdge/Image" CacheView *edge_view; CannyInfo element; char geometry[MaxTextExtent]; double lower_threshold, max, min, upper_threshold; Image *edge_image; KernelInfo *kernel_info; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *canny_cache; ssize_t y; assert(image != (const 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); /* Filter out noise. */ (void) FormatLocaleString(geometry,MaxTextExtent, "blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma); kernel_info=AcquireKernelInfo(geometry); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); edge_image=MorphologyImageChannel(image,DefaultChannels,ConvolveMorphology,1, kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); if (edge_image == (Image *) NULL) return((Image *) NULL); if (TransformImageColorspace(edge_image,GRAYColorspace) == MagickFalse) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } (void) SetImageAlphaChannel(edge_image,DeactivateAlphaChannel); /* Find the intensity gradient of the image. */ canny_cache=AcquireMatrixInfo(edge_image->columns,edge_image->rows, sizeof(CannyInfo),exception); if (canny_cache == (MatrixInfo *) NULL) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } status=MagickTrue; edge_view=AcquireVirtualCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns+1,2, exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; double dx, dy; register const PixelPacket *magick_restrict kernel_pixels; ssize_t v; static double Gx[2][2] = { { -1.0, +1.0 }, { -1.0, +1.0 } }, Gy[2][2] = { { +1.0, +1.0 }, { -1.0, -1.0 } }; (void) memset(&pixel,0,sizeof(pixel)); dx=0.0; dy=0.0; kernel_pixels=p; for (v=0; v < 2; v++) { ssize_t u; for (u=0; u < 2; u++) { double intensity; intensity=GetPixelIntensity(edge_image,kernel_pixels+u); dx+=0.5*Gx[v][u]*intensity; dy+=0.5*Gy[v][u]*intensity; } kernel_pixels+=edge_image->columns+1; } pixel.magnitude=hypot(dx,dy); pixel.orientation=0; if (fabs(dx) > MagickEpsilon) { double slope; slope=dy/dx; if (slope < 0.0) { if (slope < -2.41421356237) pixel.orientation=0; else if (slope < -0.414213562373) pixel.orientation=1; else pixel.orientation=2; } else { if (slope > 2.41421356237) pixel.orientation=0; else if (slope > 0.414213562373) pixel.orientation=3; else pixel.orientation=2; } } if (SetMatrixElement(canny_cache,x,y,&pixel) == MagickFalse) continue; p++; } } edge_view=DestroyCacheView(edge_view); /* Non-maxima suppression, remove pixels that are not considered to be part of an edge. */ progress=0; (void) GetMatrixElement(canny_cache,0,0,&element); max=element.intensity; min=element.intensity; edge_view=AcquireAuthenticCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(edge_view,0,y,edge_image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo alpha_pixel, beta_pixel, pixel; (void) GetMatrixElement(canny_cache,x,y,&pixel); switch (pixel.orientation) { case 0: default: { /* 0 degrees, north and south. */ (void) GetMatrixElement(canny_cache,x,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x,y+1,&beta_pixel); break; } case 1: { /* 45 degrees, northwest and southeast. */ (void) GetMatrixElement(canny_cache,x-1,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y+1,&beta_pixel); break; } case 2: { /* 90 degrees, east and west. */ (void) GetMatrixElement(canny_cache,x-1,y,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y,&beta_pixel); break; } case 3: { /* 135 degrees, northeast and southwest. */ (void) GetMatrixElement(canny_cache,x+1,y-1,&beta_pixel); (void) GetMatrixElement(canny_cache,x-1,y+1,&alpha_pixel); break; } } pixel.intensity=pixel.magnitude; if ((pixel.magnitude < alpha_pixel.magnitude) || (pixel.magnitude < beta_pixel.magnitude)) pixel.intensity=0; (void) SetMatrixElement(canny_cache,x,y,&pixel); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CannyEdgeImage) #endif { if (pixel.intensity < min) min=pixel.intensity; if (pixel.intensity > max) max=pixel.intensity; } q->red=0; q->green=0; q->blue=0; q++; } if (SyncCacheViewAuthenticPixels(edge_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CannyEdgeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } edge_view=DestroyCacheView(edge_view); /* Estimate hysteresis threshold. */ lower_threshold=lower_percent*(max-min)+min; upper_threshold=upper_percent*(max-min)+min; /* Hysteresis threshold. */ edge_view=AcquireAuthenticCacheView(edge_image,exception); for (y=0; y < (ssize_t) edge_image->rows; y++) { register ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; register const PixelPacket *magick_restrict p; /* Edge if pixel gradient higher than upper threshold. */ p=GetCacheViewVirtualPixels(edge_view,x,y,1,1,exception); if (p == (const PixelPacket *) NULL) continue; status=GetMatrixElement(canny_cache,x,y,&pixel); if (status == MagickFalse) continue; if ((GetPixelIntensity(edge_image,p) == 0.0) && (pixel.intensity >= upper_threshold)) status=TraceEdges(edge_image,edge_view,canny_cache,x,y,lower_threshold, exception); } } edge_view=DestroyCacheView(edge_view); /* Free resources. */ canny_cache=DestroyMatrixInfo(canny_cache); return(edge_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l F e a t u r e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelFeatures() returns features for each channel in the image in % each of four directions (horizontal, vertical, left and right diagonals) % for the specified distance. The features include the angular second % moment, contrast, correlation, sum of squares: variance, inverse difference % moment, sum average, sum varience, sum entropy, entropy, difference variance,% difference entropy, information measures of correlation 1, information % measures of correlation 2, and maximum correlation coefficient. You can % access the red channel contrast, for example, like this: % % channel_features=GetImageChannelFeatures(image,1,exception); % contrast=channel_features[RedChannel].contrast[0]; % % Use MagickRelinquishMemory() to free the features buffer. % % The format of the GetImageChannelFeatures method is: % % ChannelFeatures *GetImageChannelFeatures(const Image *image, % const size_t distance,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o distance: the distance. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelFeatures *GetImageChannelFeatures(const Image *image, const size_t distance,ExceptionInfo *exception) { typedef struct _ChannelStatistics { DoublePixelPacket direction[4]; /* horizontal, vertical, left and right diagonals */ } ChannelStatistics; CacheView *image_view; ChannelFeatures *channel_features; ChannelStatistics **cooccurrence, correlation, *density_x, *density_xy, *density_y, entropy_x, entropy_xy, entropy_xy1, entropy_xy2, entropy_y, mean, **Q, *sum, sum_squares, variance; LongPixelPacket gray, *grays; MagickBooleanType status; register ssize_t i; size_t length; ssize_t y; unsigned int number_grays; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns < (distance+1)) || (image->rows < (distance+1))) return((ChannelFeatures *) NULL); length=CompositeChannels+1UL; channel_features=(ChannelFeatures *) AcquireQuantumMemory(length, sizeof(*channel_features)); if (channel_features == (ChannelFeatures *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(channel_features,0,length* sizeof(*channel_features)); /* Form grays. */ grays=(LongPixelPacket *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*grays)); if (grays == (LongPixelPacket *) NULL) { channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } for (i=0; i <= (ssize_t) MaxMap; i++) { grays[i].red=(~0U); grays[i].green=(~0U); grays[i].blue=(~0U); grays[i].opacity=(~0U); grays[i].index=(~0U); } status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { grays[ScaleQuantumToMap(GetPixelRed(p))].red= ScaleQuantumToMap(GetPixelRed(p)); grays[ScaleQuantumToMap(GetPixelGreen(p))].green= ScaleQuantumToMap(GetPixelGreen(p)); grays[ScaleQuantumToMap(GetPixelBlue(p))].blue= ScaleQuantumToMap(GetPixelBlue(p)); if (image->colorspace == CMYKColorspace) grays[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index= ScaleQuantumToMap(GetPixelIndex(indexes+x)); if (image->matte != MagickFalse) grays[ScaleQuantumToMap(GetPixelOpacity(p))].opacity= ScaleQuantumToMap(GetPixelOpacity(p)); p++; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { grays=(LongPixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); return(channel_features); } (void) memset(&gray,0,sizeof(gray)); for (i=0; i <= (ssize_t) MaxMap; i++) { if (grays[i].red != ~0U) grays[(ssize_t) gray.red++].red=grays[i].red; if (grays[i].green != ~0U) grays[(ssize_t) gray.green++].green=grays[i].green; if (grays[i].blue != ~0U) grays[(ssize_t) gray.blue++].blue=grays[i].blue; if (image->colorspace == CMYKColorspace) if (grays[i].index != ~0U) grays[(ssize_t) gray.index++].index=grays[i].index; if (image->matte != MagickFalse) if (grays[i].opacity != ~0U) grays[(ssize_t) gray.opacity++].opacity=grays[i].opacity; } /* Allocate spatial dependence matrix. */ number_grays=gray.red; if (gray.green > number_grays) number_grays=gray.green; if (gray.blue > number_grays) number_grays=gray.blue; if (image->colorspace == CMYKColorspace) if (gray.index > number_grays) number_grays=gray.index; if (image->matte != MagickFalse) if (gray.opacity > number_grays) number_grays=gray.opacity; cooccurrence=(ChannelStatistics **) AcquireQuantumMemory(number_grays, sizeof(*cooccurrence)); density_x=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_x)); density_xy=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_xy)); density_y=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_y)); Q=(ChannelStatistics **) AcquireQuantumMemory(number_grays,sizeof(*Q)); sum=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(*sum)); if ((cooccurrence == (ChannelStatistics **) NULL) || (density_x == (ChannelStatistics *) NULL) || (density_xy == (ChannelStatistics *) NULL) || (density_y == (ChannelStatistics *) NULL) || (Q == (ChannelStatistics **) NULL) || (sum == (ChannelStatistics *) NULL)) { if (Q != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); } if (sum != (ChannelStatistics *) NULL) sum=(ChannelStatistics *) RelinquishMagickMemory(sum); if (density_y != (ChannelStatistics *) NULL) density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); if (density_xy != (ChannelStatistics *) NULL) density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); if (density_x != (ChannelStatistics *) NULL) density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); if (cooccurrence != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory( cooccurrence); } grays=(LongPixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } (void) memset(&correlation,0,sizeof(correlation)); (void) memset(density_x,0,2*(number_grays+1)*sizeof(*density_x)); (void) memset(density_xy,0,2*(number_grays+1)*sizeof(*density_xy)); (void) memset(density_y,0,2*(number_grays+1)*sizeof(*density_y)); (void) memset(&mean,0,sizeof(mean)); (void) memset(sum,0,number_grays*sizeof(*sum)); (void) memset(&sum_squares,0,sizeof(sum_squares)); (void) memset(density_xy,0,2*number_grays*sizeof(*density_xy)); (void) memset(&entropy_x,0,sizeof(entropy_x)); (void) memset(&entropy_xy,0,sizeof(entropy_xy)); (void) memset(&entropy_xy1,0,sizeof(entropy_xy1)); (void) memset(&entropy_xy2,0,sizeof(entropy_xy2)); (void) memset(&entropy_y,0,sizeof(entropy_y)); (void) memset(&variance,0,sizeof(variance)); for (i=0; i < (ssize_t) number_grays; i++) { cooccurrence[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays, sizeof(**cooccurrence)); Q[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(**Q)); if ((cooccurrence[i] == (ChannelStatistics *) NULL) || (Q[i] == (ChannelStatistics *) NULL)) break; (void) memset(cooccurrence[i],0,number_grays* sizeof(**cooccurrence)); (void) memset(Q[i],0,number_grays*sizeof(**Q)); } if (i < (ssize_t) number_grays) { for (i--; i >= 0; i--) { if (Q[i] != (ChannelStatistics *) NULL) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); if (cooccurrence[i] != (ChannelStatistics *) NULL) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); } Q=(ChannelStatistics **) RelinquishMagickMemory(Q); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); sum=(ChannelStatistics *) RelinquishMagickMemory(sum); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); grays=(LongPixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Initialize spatial dependence matrix. */ status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; ssize_t i, offset, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-(ssize_t) distance,y,image->columns+ 2*distance,distance+2,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); p+=distance; indexes+=distance; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < 4; i++) { switch (i) { case 0: default: { /* Horizontal adjacency. */ offset=(ssize_t) distance; break; } case 1: { /* Vertical adjacency. */ offset=(ssize_t) (image->columns+2*distance); break; } case 2: { /* Right diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)-distance); break; } case 3: { /* Left diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)+distance); break; } } u=0; v=0; while (grays[u].red != ScaleQuantumToMap(GetPixelRed(p))) u++; while (grays[v].red != ScaleQuantumToMap(GetPixelRed(p+offset))) v++; cooccurrence[u][v].direction[i].red++; cooccurrence[v][u].direction[i].red++; u=0; v=0; while (grays[u].green != ScaleQuantumToMap(GetPixelGreen(p))) u++; while (grays[v].green != ScaleQuantumToMap(GetPixelGreen(p+offset))) v++; cooccurrence[u][v].direction[i].green++; cooccurrence[v][u].direction[i].green++; u=0; v=0; while (grays[u].blue != ScaleQuantumToMap(GetPixelBlue(p))) u++; while (grays[v].blue != ScaleQuantumToMap((p+offset)->blue)) v++; cooccurrence[u][v].direction[i].blue++; cooccurrence[v][u].direction[i].blue++; if (image->colorspace == CMYKColorspace) { u=0; v=0; while (grays[u].index != ScaleQuantumToMap(GetPixelIndex(indexes+x))) u++; while (grays[v].index != ScaleQuantumToMap(GetPixelIndex(indexes+x+offset))) v++; cooccurrence[u][v].direction[i].index++; cooccurrence[v][u].direction[i].index++; } if (image->matte != MagickFalse) { u=0; v=0; while (grays[u].opacity != ScaleQuantumToMap(GetPixelOpacity(p))) u++; while (grays[v].opacity != ScaleQuantumToMap((p+offset)->opacity)) v++; cooccurrence[u][v].direction[i].opacity++; cooccurrence[v][u].direction[i].opacity++; } } p++; } } grays=(LongPixelPacket *) RelinquishMagickMemory(grays); image_view=DestroyCacheView(image_view); if (status == MagickFalse) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Normalize spatial dependence matrix. */ for (i=0; i < 4; i++) { double normalize; register ssize_t y; switch (i) { case 0: default: { /* Horizontal adjacency. */ normalize=2.0*image->rows*(image->columns-distance); break; } case 1: { /* Vertical adjacency. */ normalize=2.0*(image->rows-distance)*image->columns; break; } case 2: { /* Right diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } case 3: { /* Left diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } } normalize=PerceptibleReciprocal(normalize); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { cooccurrence[x][y].direction[i].red*=normalize; cooccurrence[x][y].direction[i].green*=normalize; cooccurrence[x][y].direction[i].blue*=normalize; if (image->colorspace == CMYKColorspace) cooccurrence[x][y].direction[i].index*=normalize; if (image->matte != MagickFalse) cooccurrence[x][y].direction[i].opacity*=normalize; } } } /* Compute texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Angular second moment: measure of homogeneity of the image. */ channel_features[RedChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].red* cooccurrence[x][y].direction[i].red; channel_features[GreenChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].green* cooccurrence[x][y].direction[i].green; channel_features[BlueChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].blue* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].index* cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) channel_features[OpacityChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].opacity* cooccurrence[x][y].direction[i].opacity; /* Correlation: measure of linear-dependencies in the image. */ sum[y].direction[i].red+=cooccurrence[x][y].direction[i].red; sum[y].direction[i].green+=cooccurrence[x][y].direction[i].green; sum[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) sum[y].direction[i].index+=cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) sum[y].direction[i].opacity+=cooccurrence[x][y].direction[i].opacity; correlation.direction[i].red+=x*y*cooccurrence[x][y].direction[i].red; correlation.direction[i].green+=x*y* cooccurrence[x][y].direction[i].green; correlation.direction[i].blue+=x*y* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) correlation.direction[i].index+=x*y* cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) correlation.direction[i].opacity+=x*y* cooccurrence[x][y].direction[i].opacity; /* Inverse Difference Moment. */ channel_features[RedChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].red/((y-x)*(y-x)+1); channel_features[GreenChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].green/((y-x)*(y-x)+1); channel_features[BlueChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].blue/((y-x)*(y-x)+1); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].index/((y-x)*(y-x)+1); if (image->matte != MagickFalse) channel_features[OpacityChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].opacity/((y-x)*(y-x)+1); /* Sum average. */ density_xy[y+x+2].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[y+x+2].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[y+x+2].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[y+x+2].direction[i].index+= cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) density_xy[y+x+2].direction[i].opacity+= cooccurrence[x][y].direction[i].opacity; /* Entropy. */ channel_features[RedChannel].entropy[i]-= cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); channel_features[GreenChannel].entropy[i]-= cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); channel_features[BlueChannel].entropy[i]-= cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].entropy[i]-= cooccurrence[x][y].direction[i].index* MagickLog10(cooccurrence[x][y].direction[i].index); if (image->matte != MagickFalse) channel_features[OpacityChannel].entropy[i]-= cooccurrence[x][y].direction[i].opacity* MagickLog10(cooccurrence[x][y].direction[i].opacity); /* Information Measures of Correlation. */ density_x[x].direction[i].red+=cooccurrence[x][y].direction[i].red; density_x[x].direction[i].green+=cooccurrence[x][y].direction[i].green; density_x[x].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_x[x].direction[i].index+= cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) density_x[x].direction[i].opacity+= cooccurrence[x][y].direction[i].opacity; density_y[y].direction[i].red+=cooccurrence[x][y].direction[i].red; density_y[y].direction[i].green+=cooccurrence[x][y].direction[i].green; density_y[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_y[y].direction[i].index+= cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) density_y[y].direction[i].opacity+= cooccurrence[x][y].direction[i].opacity; } mean.direction[i].red+=y*sum[y].direction[i].red; sum_squares.direction[i].red+=y*y*sum[y].direction[i].red; mean.direction[i].green+=y*sum[y].direction[i].green; sum_squares.direction[i].green+=y*y*sum[y].direction[i].green; mean.direction[i].blue+=y*sum[y].direction[i].blue; sum_squares.direction[i].blue+=y*y*sum[y].direction[i].blue; if (image->colorspace == CMYKColorspace) { mean.direction[i].index+=y*sum[y].direction[i].index; sum_squares.direction[i].index+=y*y*sum[y].direction[i].index; } if (image->matte != MagickFalse) { mean.direction[i].opacity+=y*sum[y].direction[i].opacity; sum_squares.direction[i].opacity+=y*y*sum[y].direction[i].opacity; } } /* Correlation: measure of linear-dependencies in the image. */ channel_features[RedChannel].correlation[i]= (correlation.direction[i].red-mean.direction[i].red* mean.direction[i].red)/(sqrt(sum_squares.direction[i].red- (mean.direction[i].red*mean.direction[i].red))*sqrt( sum_squares.direction[i].red-(mean.direction[i].red* mean.direction[i].red))); channel_features[GreenChannel].correlation[i]= (correlation.direction[i].green-mean.direction[i].green* mean.direction[i].green)/(sqrt(sum_squares.direction[i].green- (mean.direction[i].green*mean.direction[i].green))*sqrt( sum_squares.direction[i].green-(mean.direction[i].green* mean.direction[i].green))); channel_features[BlueChannel].correlation[i]= (correlation.direction[i].blue-mean.direction[i].blue* mean.direction[i].blue)/(sqrt(sum_squares.direction[i].blue- (mean.direction[i].blue*mean.direction[i].blue))*sqrt( sum_squares.direction[i].blue-(mean.direction[i].blue* mean.direction[i].blue))); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].correlation[i]= (correlation.direction[i].index-mean.direction[i].index* mean.direction[i].index)/(sqrt(sum_squares.direction[i].index- (mean.direction[i].index*mean.direction[i].index))*sqrt( sum_squares.direction[i].index-(mean.direction[i].index* mean.direction[i].index))); if (image->matte != MagickFalse) channel_features[OpacityChannel].correlation[i]= (correlation.direction[i].opacity-mean.direction[i].opacity* mean.direction[i].opacity)/(sqrt(sum_squares.direction[i].opacity- (mean.direction[i].opacity*mean.direction[i].opacity))*sqrt( sum_squares.direction[i].opacity-(mean.direction[i].opacity* mean.direction[i].opacity))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=2; x < (ssize_t) (2*number_grays); x++) { /* Sum average. */ channel_features[RedChannel].sum_average[i]+= x*density_xy[x].direction[i].red; channel_features[GreenChannel].sum_average[i]+= x*density_xy[x].direction[i].green; channel_features[BlueChannel].sum_average[i]+= x*density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].sum_average[i]+= x*density_xy[x].direction[i].index; if (image->matte != MagickFalse) channel_features[OpacityChannel].sum_average[i]+= x*density_xy[x].direction[i].opacity; /* Sum entropy. */ channel_features[RedChannel].sum_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenChannel].sum_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BlueChannel].sum_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].sum_entropy[i]-= density_xy[x].direction[i].index* MagickLog10(density_xy[x].direction[i].index); if (image->matte != MagickFalse) channel_features[OpacityChannel].sum_entropy[i]-= density_xy[x].direction[i].opacity* MagickLog10(density_xy[x].direction[i].opacity); /* Sum variance. */ channel_features[RedChannel].sum_variance[i]+= (x-channel_features[RedChannel].sum_entropy[i])* (x-channel_features[RedChannel].sum_entropy[i])* density_xy[x].direction[i].red; channel_features[GreenChannel].sum_variance[i]+= (x-channel_features[GreenChannel].sum_entropy[i])* (x-channel_features[GreenChannel].sum_entropy[i])* density_xy[x].direction[i].green; channel_features[BlueChannel].sum_variance[i]+= (x-channel_features[BlueChannel].sum_entropy[i])* (x-channel_features[BlueChannel].sum_entropy[i])* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].sum_variance[i]+= (x-channel_features[IndexChannel].sum_entropy[i])* (x-channel_features[IndexChannel].sum_entropy[i])* density_xy[x].direction[i].index; if (image->matte != MagickFalse) channel_features[OpacityChannel].sum_variance[i]+= (x-channel_features[OpacityChannel].sum_entropy[i])* (x-channel_features[OpacityChannel].sum_entropy[i])* density_xy[x].direction[i].opacity; } } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Sum of Squares: Variance */ variance.direction[i].red+=(y-mean.direction[i].red+1)* (y-mean.direction[i].red+1)*cooccurrence[x][y].direction[i].red; variance.direction[i].green+=(y-mean.direction[i].green+1)* (y-mean.direction[i].green+1)*cooccurrence[x][y].direction[i].green; variance.direction[i].blue+=(y-mean.direction[i].blue+1)* (y-mean.direction[i].blue+1)*cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].index+=(y-mean.direction[i].index+1)* (y-mean.direction[i].index+1)*cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) variance.direction[i].opacity+=(y-mean.direction[i].opacity+1)* (y-mean.direction[i].opacity+1)* cooccurrence[x][y].direction[i].opacity; /* Sum average / Difference Variance. */ density_xy[MagickAbsoluteValue(y-x)].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[MagickAbsoluteValue(y-x)].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[MagickAbsoluteValue(y-x)].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[MagickAbsoluteValue(y-x)].direction[i].index+= cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) density_xy[MagickAbsoluteValue(y-x)].direction[i].opacity+= cooccurrence[x][y].direction[i].opacity; /* Information Measures of Correlation. */ entropy_xy.direction[i].red-=cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); entropy_xy.direction[i].green-=cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); entropy_xy.direction[i].blue-=cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) entropy_xy.direction[i].index-=cooccurrence[x][y].direction[i].index* MagickLog10(cooccurrence[x][y].direction[i].index); if (image->matte != MagickFalse) entropy_xy.direction[i].opacity-= cooccurrence[x][y].direction[i].opacity*MagickLog10( cooccurrence[x][y].direction[i].opacity); entropy_xy1.direction[i].red-=(cooccurrence[x][y].direction[i].red* MagickLog10(density_x[x].direction[i].red* density_y[y].direction[i].red)); entropy_xy1.direction[i].green-=(cooccurrence[x][y].direction[i].green* MagickLog10(density_x[x].direction[i].green* density_y[y].direction[i].green)); entropy_xy1.direction[i].blue-=(cooccurrence[x][y].direction[i].blue* MagickLog10(density_x[x].direction[i].blue* density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy1.direction[i].index-=( cooccurrence[x][y].direction[i].index*MagickLog10( density_x[x].direction[i].index*density_y[y].direction[i].index)); if (image->matte != MagickFalse) entropy_xy1.direction[i].opacity-=( cooccurrence[x][y].direction[i].opacity*MagickLog10( density_x[x].direction[i].opacity* density_y[y].direction[i].opacity)); entropy_xy2.direction[i].red-=(density_x[x].direction[i].red* density_y[y].direction[i].red*MagickLog10( density_x[x].direction[i].red*density_y[y].direction[i].red)); entropy_xy2.direction[i].green-=(density_x[x].direction[i].green* density_y[y].direction[i].green*MagickLog10( density_x[x].direction[i].green*density_y[y].direction[i].green)); entropy_xy2.direction[i].blue-=(density_x[x].direction[i].blue* density_y[y].direction[i].blue*MagickLog10( density_x[x].direction[i].blue*density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy2.direction[i].index-=(density_x[x].direction[i].index* density_y[y].direction[i].index*MagickLog10( density_x[x].direction[i].index*density_y[y].direction[i].index)); if (image->matte != MagickFalse) entropy_xy2.direction[i].opacity-=(density_x[x].direction[i].opacity* density_y[y].direction[i].opacity*MagickLog10( density_x[x].direction[i].opacity* density_y[y].direction[i].opacity)); } } channel_features[RedChannel].variance_sum_of_squares[i]= variance.direction[i].red; channel_features[GreenChannel].variance_sum_of_squares[i]= variance.direction[i].green; channel_features[BlueChannel].variance_sum_of_squares[i]= variance.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[RedChannel].variance_sum_of_squares[i]= variance.direction[i].index; if (image->matte != MagickFalse) channel_features[RedChannel].variance_sum_of_squares[i]= variance.direction[i].opacity; } /* Compute more texture features. */ (void) memset(&variance,0,sizeof(variance)); (void) memset(&sum_squares,0,sizeof(sum_squares)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Difference variance. */ variance.direction[i].red+=density_xy[x].direction[i].red; variance.direction[i].green+=density_xy[x].direction[i].green; variance.direction[i].blue+=density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].index+=density_xy[x].direction[i].index; if (image->matte != MagickFalse) variance.direction[i].opacity+=density_xy[x].direction[i].opacity; sum_squares.direction[i].red+=density_xy[x].direction[i].red* density_xy[x].direction[i].red; sum_squares.direction[i].green+=density_xy[x].direction[i].green* density_xy[x].direction[i].green; sum_squares.direction[i].blue+=density_xy[x].direction[i].blue* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) sum_squares.direction[i].index+=density_xy[x].direction[i].index* density_xy[x].direction[i].index; if (image->matte != MagickFalse) sum_squares.direction[i].opacity+=density_xy[x].direction[i].opacity* density_xy[x].direction[i].opacity; /* Difference entropy. */ channel_features[RedChannel].difference_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenChannel].difference_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BlueChannel].difference_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].difference_entropy[i]-= density_xy[x].direction[i].index* MagickLog10(density_xy[x].direction[i].index); if (image->matte != MagickFalse) channel_features[OpacityChannel].difference_entropy[i]-= density_xy[x].direction[i].opacity* MagickLog10(density_xy[x].direction[i].opacity); /* Information Measures of Correlation. */ entropy_x.direction[i].red-=(density_x[x].direction[i].red* MagickLog10(density_x[x].direction[i].red)); entropy_x.direction[i].green-=(density_x[x].direction[i].green* MagickLog10(density_x[x].direction[i].green)); entropy_x.direction[i].blue-=(density_x[x].direction[i].blue* MagickLog10(density_x[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_x.direction[i].index-=(density_x[x].direction[i].index* MagickLog10(density_x[x].direction[i].index)); if (image->matte != MagickFalse) entropy_x.direction[i].opacity-=(density_x[x].direction[i].opacity* MagickLog10(density_x[x].direction[i].opacity)); entropy_y.direction[i].red-=(density_y[x].direction[i].red* MagickLog10(density_y[x].direction[i].red)); entropy_y.direction[i].green-=(density_y[x].direction[i].green* MagickLog10(density_y[x].direction[i].green)); entropy_y.direction[i].blue-=(density_y[x].direction[i].blue* MagickLog10(density_y[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_y.direction[i].index-=(density_y[x].direction[i].index* MagickLog10(density_y[x].direction[i].index)); if (image->matte != MagickFalse) entropy_y.direction[i].opacity-=(density_y[x].direction[i].opacity* MagickLog10(density_y[x].direction[i].opacity)); } /* Difference variance. */ channel_features[RedChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].red)- (variance.direction[i].red*variance.direction[i].red))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[GreenChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].green)- (variance.direction[i].green*variance.direction[i].green))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[BlueChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].blue)- (variance.direction[i].blue*variance.direction[i].blue))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->matte != MagickFalse) channel_features[OpacityChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].opacity)- (variance.direction[i].opacity*variance.direction[i].opacity))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].index)- (variance.direction[i].index*variance.direction[i].index))/ ((double) number_grays*number_grays*number_grays*number_grays); /* Information Measures of Correlation. */ channel_features[RedChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].red-entropy_xy1.direction[i].red)/ (entropy_x.direction[i].red > entropy_y.direction[i].red ? entropy_x.direction[i].red : entropy_y.direction[i].red); channel_features[GreenChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].green-entropy_xy1.direction[i].green)/ (entropy_x.direction[i].green > entropy_y.direction[i].green ? entropy_x.direction[i].green : entropy_y.direction[i].green); channel_features[BlueChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].blue-entropy_xy1.direction[i].blue)/ (entropy_x.direction[i].blue > entropy_y.direction[i].blue ? entropy_x.direction[i].blue : entropy_y.direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].index-entropy_xy1.direction[i].index)/ (entropy_x.direction[i].index > entropy_y.direction[i].index ? entropy_x.direction[i].index : entropy_y.direction[i].index); if (image->matte != MagickFalse) channel_features[OpacityChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].opacity-entropy_xy1.direction[i].opacity)/ (entropy_x.direction[i].opacity > entropy_y.direction[i].opacity ? entropy_x.direction[i].opacity : entropy_y.direction[i].opacity); channel_features[RedChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].red- entropy_xy.direction[i].red))))); channel_features[GreenChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].green- entropy_xy.direction[i].green))))); channel_features[BlueChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].blue- entropy_xy.direction[i].blue))))); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].index- entropy_xy.direction[i].index))))); if (image->matte != MagickFalse) channel_features[OpacityChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(entropy_xy2.direction[i].opacity- entropy_xy.direction[i].opacity))))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t z; for (z=0; z < (ssize_t) number_grays; z++) { register ssize_t y; ChannelStatistics pixel; (void) memset(&pixel,0,sizeof(pixel)); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Contrast: amount of local variations present in an image. */ if (((y-x) == z) || ((x-y) == z)) { pixel.direction[i].red+=cooccurrence[x][y].direction[i].red; pixel.direction[i].green+=cooccurrence[x][y].direction[i].green; pixel.direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) pixel.direction[i].index+=cooccurrence[x][y].direction[i].index; if (image->matte != MagickFalse) pixel.direction[i].opacity+= cooccurrence[x][y].direction[i].opacity; } /* Maximum Correlation Coefficient. */ Q[z][y].direction[i].red+=cooccurrence[z][x].direction[i].red* cooccurrence[y][x].direction[i].red/density_x[z].direction[i].red/ density_y[x].direction[i].red; Q[z][y].direction[i].green+=cooccurrence[z][x].direction[i].green* cooccurrence[y][x].direction[i].green/ density_x[z].direction[i].green/density_y[x].direction[i].red; Q[z][y].direction[i].blue+=cooccurrence[z][x].direction[i].blue* cooccurrence[y][x].direction[i].blue/density_x[z].direction[i].blue/ density_y[x].direction[i].blue; if (image->colorspace == CMYKColorspace) Q[z][y].direction[i].index+=cooccurrence[z][x].direction[i].index* cooccurrence[y][x].direction[i].index/ density_x[z].direction[i].index/density_y[x].direction[i].index; if (image->matte != MagickFalse) Q[z][y].direction[i].opacity+= cooccurrence[z][x].direction[i].opacity* cooccurrence[y][x].direction[i].opacity/ density_x[z].direction[i].opacity/ density_y[x].direction[i].opacity; } } channel_features[RedChannel].contrast[i]+=z*z*pixel.direction[i].red; channel_features[GreenChannel].contrast[i]+=z*z*pixel.direction[i].green; channel_features[BlueChannel].contrast[i]+=z*z*pixel.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackChannel].contrast[i]+=z*z* pixel.direction[i].index; if (image->matte != MagickFalse) channel_features[OpacityChannel].contrast[i]+=z*z* pixel.direction[i].opacity; } /* Maximum Correlation Coefficient. Future: return second largest eigenvalue of Q. */ channel_features[RedChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[GreenChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[BlueChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->colorspace == CMYKColorspace) channel_features[IndexChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->matte != MagickFalse) channel_features[OpacityChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); } /* Relinquish resources. */ sum=(ChannelStatistics *) RelinquishMagickMemory(sum); for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); return(channel_features); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H o u g h L i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Use HoughLineImage() in conjunction with any binary edge extracted image (we % recommand Canny) to identify lines in the image. The algorithm accumulates % counts for every white pixel for every possible orientation (for angles from % 0 to 179 in 1 degree increments) and distance from the center of the image to % the corner (in 1 px increments) and stores the counts in an accumulator % matrix of angle vs distance. The size of the accumulator is 180x(diagonal/2).% Next it searches this space for peaks in counts and converts the locations % of the peaks to slope and intercept in the normal x,y input image space. Use % the slope/intercepts to find the endpoints clipped to the bounds of the % image. The lines are then drawn. The counts are a measure of the length of % the lines. % % The format of the HoughLineImage method is: % % Image *HoughLineImage(const Image *image,const size_t width, % const size_t height,const size_t threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find line pairs as local maxima in this neighborhood. % % o threshold: the line count threshold. % % o exception: return any errors or warnings in this structure. % */ 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)); } static Image *RenderHoughLines(const ImageInfo *image_info,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define BoundingBox "viewbox" DrawInfo *draw_info; Image *image; MagickBooleanType status; /* Open image. */ image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->columns=columns; image->rows=rows; draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->affine.sx=image->x_resolution == 0.0 ? 1.0 : image->x_resolution/ DefaultResolution; draw_info->affine.sy=image->y_resolution == 0.0 ? 1.0 : image->y_resolution/ DefaultResolution; image->columns=(size_t) (draw_info->affine.sx*image->columns); image->rows=(size_t) (draw_info->affine.sy*image->rows); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Render drawing. */ if (GetBlobStreamData(image) == (unsigned char *) NULL) draw_info->primitive=FileToString(image->filename,~0UL,exception); else { draw_info->primitive=(char *) AcquireMagickMemory((size_t) GetBlobSize(image)+1); if (draw_info->primitive != (char *) NULL) { (void) memcpy(draw_info->primitive,GetBlobStreamData(image), (size_t) GetBlobSize(image)); draw_info->primitive[GetBlobSize(image)]='\0'; } } (void) DrawImage(image,draw_info); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } MagickExport Image *HoughLineImage(const Image *image,const size_t width, const size_t height,const size_t threshold,ExceptionInfo *exception) { #define HoughLineImageTag "HoughLine/Image" CacheView *image_view; char message[MaxTextExtent], path[MaxTextExtent]; const char *artifact; double hough_height; Image *lines_image = NULL; ImageInfo *image_info; int file; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *accumulator; PointInfo center; register ssize_t y; size_t accumulator_height, accumulator_width, line_count; /* Create the accumulator. */ assert(image != (const 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); accumulator_width=180; hough_height=((sqrt(2.0)*(double) (image->rows > image->columns ? image->rows : image->columns))/2.0); accumulator_height=(size_t) (2.0*hough_height); accumulator=AcquireMatrixInfo(accumulator_width,accumulator_height, sizeof(double),exception); if (accumulator == (MatrixInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); if (NullMatrix(accumulator) == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Populate the accumulator. */ status=MagickTrue; progress=0; center.x=(double) image->columns/2.0; center.y=(double) image->rows/2.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; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelIntensity(image,p) > (QuantumRange/2.0)) { register ssize_t i; for (i=0; i < 180; i++) { double count, radius; radius=(((double) x-center.x)*cos(DegreesToRadians((double) i)))+ (((double) y-center.y)*sin(DegreesToRadians((double) i))); (void) GetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); count++; (void) SetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); } } p++; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,HoughLineImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } /* Generate line segments from accumulator. */ file=AcquireUniqueFileResource(path); if (file == -1) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } (void) FormatLocaleString(message,MaxTextExtent, "# Hough line transform: %.20gx%.20g%+.20g\n",(double) width, (double) height,(double) threshold); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; (void) FormatLocaleString(message,MaxTextExtent,"viewbox 0 0 %.20g %.20g\n", (double) image->columns,(double) image->rows); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; (void) FormatLocaleString(message,MaxTextExtent, "# x1,y1 x2,y2 # count angle distance\n"); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; line_count=image->columns > image->rows ? image->columns/4 : image->rows/4; if (threshold != 0) line_count=threshold; for (y=0; y < (ssize_t) accumulator_height; y++) { register ssize_t x; for (x=0; x < (ssize_t) accumulator_width; x++) { double count; (void) GetMatrixElement(accumulator,x,y,&count); if (count >= (double) line_count) { double maxima; SegmentInfo line; ssize_t v; /* Is point a local maxima? */ maxima=count; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((u != 0) || (v !=0)) { (void) GetMatrixElement(accumulator,x+u,y+v,&count); if (count > maxima) { maxima=count; break; } } } if (u < (ssize_t) (width/2)) break; } (void) GetMatrixElement(accumulator,x,y,&count); if (maxima > count) continue; if ((x >= 45) && (x <= 135)) { /* y = (r-x cos(t))/sin(t) */ line.x1=0.0; line.y1=((double) (y-(accumulator_height/2.0))-((line.x1- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); line.x2=(double) image->columns; line.y2=((double) (y-(accumulator_height/2.0))-((line.x2- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); } else { /* x = (r-y cos(t))/sin(t) */ line.y1=0.0; line.x1=((double) (y-(accumulator_height/2.0))-((line.y1- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); line.y2=(double) image->rows; line.x2=((double) (y-(accumulator_height/2.0))-((line.y2- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); } (void) FormatLocaleString(message,MaxTextExtent, "line %g,%g %g,%g # %g %g %g\n",line.x1,line.y1,line.x2,line.y2, maxima,(double) x,(double) y); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; } } } (void) close(file); /* Render lines to image canvas. */ image_info=AcquireImageInfo(); image_info->background_color=image->background_color; (void) FormatLocaleString(image_info->filename,MaxTextExtent,"%s",path); artifact=GetImageArtifact(image,"background"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"background",artifact); artifact=GetImageArtifact(image,"fill"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"fill",artifact); artifact=GetImageArtifact(image,"stroke"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"stroke",artifact); artifact=GetImageArtifact(image,"strokewidth"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"strokewidth",artifact); lines_image=RenderHoughLines(image_info,image->columns,image->rows,exception); artifact=GetImageArtifact(image,"hough-lines:accumulator"); if ((lines_image != (Image *) NULL) && (IsMagickTrue(artifact) != MagickFalse)) { Image *accumulator_image; accumulator_image=MatrixToImage(accumulator,exception); if (accumulator_image != (Image *) NULL) AppendImageToList(&lines_image,accumulator_image); } /* Free resources. */ accumulator=DestroyMatrixInfo(accumulator); image_info=DestroyImageInfo(image_info); (void) RelinquishUniqueFileResource(path); return(GetFirstImageInList(lines_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e a n S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MeanShiftImage() delineate arbitrarily shaped clusters in the image. For % each pixel, it visits all the pixels in the neighborhood specified by % the window centered at the pixel and excludes those that are outside the % radius=(window-1)/2 surrounding the pixel. From those pixels, it finds those % that are within the specified color distance from the current mean, and % computes a new x,y centroid from those coordinates and a new mean. This new % x,y centroid is used as the center for a new window. This process iterates % until it converges and the final mean is replaces the (original window % center) pixel value. It repeats this process for the next pixel, etc., % until it processes all pixels in the image. Results are typically better with % colorspaces other than sRGB. We recommend YIQ, YUV or YCbCr. % % The format of the MeanShiftImage method is: % % Image *MeanShiftImage(const Image *image,const size_t width, % const size_t height,const double color_distance, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find pixels in this neighborhood. % % o color_distance: the color distance. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MeanShiftImage(const Image *image,const size_t width, const size_t height,const double color_distance,ExceptionInfo *exception) { #define MaxMeanShiftIterations 100 #define MeanShiftImageTag "MeanShift/Image" CacheView *image_view, *mean_view, *pixel_view; Image *mean_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (const 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); mean_image=CloneImage(image,0,0,MagickTrue,exception); if (mean_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(mean_image,DirectClass) == MagickFalse) { InheritException(exception,&mean_image->exception); mean_image=DestroyImage(mean_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); pixel_view=AcquireVirtualCacheView(image,exception); mean_view=AcquireAuthenticCacheView(mean_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,progress) \ magick_number_threads(mean_image,mean_image,mean_image->rows,1) #endif for (y=0; y < (ssize_t) mean_image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) mean_image->columns; x++) { MagickPixelPacket mean_pixel, previous_pixel; PointInfo mean_location, previous_location; register ssize_t i; GetMagickPixelPacket(image,&mean_pixel); SetMagickPixelPacket(image,p,indexes+x,&mean_pixel); mean_location.x=(double) x; mean_location.y=(double) y; for (i=0; i < MaxMeanShiftIterations; i++) { double distance, gamma; MagickPixelPacket sum_pixel; PointInfo sum_location; ssize_t count, v; sum_location.x=0.0; sum_location.y=0.0; GetMagickPixelPacket(image,&sum_pixel); previous_location=mean_location; previous_pixel=mean_pixel; count=0; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) { PixelPacket pixel; status=GetOneCacheViewVirtualPixel(pixel_view,(ssize_t) MagickRound(mean_location.x+u),(ssize_t) MagickRound( mean_location.y+v),&pixel,exception); distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); if (distance <= (color_distance*color_distance)) { sum_location.x+=mean_location.x+u; sum_location.y+=mean_location.y+v; sum_pixel.red+=pixel.red; sum_pixel.green+=pixel.green; sum_pixel.blue+=pixel.blue; sum_pixel.opacity+=pixel.opacity; count++; } } } } gamma=1.0/count; mean_location.x=gamma*sum_location.x; mean_location.y=gamma*sum_location.y; mean_pixel.red=gamma*sum_pixel.red; mean_pixel.green=gamma*sum_pixel.green; mean_pixel.blue=gamma*sum_pixel.blue; mean_pixel.opacity=gamma*sum_pixel.opacity; distance=(mean_location.x-previous_location.x)* (mean_location.x-previous_location.x)+ (mean_location.y-previous_location.y)* (mean_location.y-previous_location.y)+ 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); if (distance <= 3.0) break; } q->red=ClampToQuantum(mean_pixel.red); q->green=ClampToQuantum(mean_pixel.green); q->blue=ClampToQuantum(mean_pixel.blue); q->opacity=ClampToQuantum(mean_pixel.opacity); p++; q++; } if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } mean_view=DestroyCacheView(mean_view); pixel_view=DestroyCacheView(pixel_view); image_view=DestroyCacheView(image_view); return(mean_image); }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_1009_0
crossvul-cpp_data_good_2303_1
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library UNIX-specific Routines. These are should also work with the * Windows Common RunTime Library. */ #include "tif_config.h" #ifdef HAVE_SYS_TYPES_H # include <sys/types.h> #endif #include <errno.h> #include <stdarg.h> #include <stdlib.h> #include <sys/stat.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_IO_H # include <io.h> #endif #include "tiffiop.h" static tmsize_t _tiffReadProc(thandle_t fd, void* buf, tmsize_t size) { size_t size_io = (size_t) size; if ((tmsize_t) size_io != size) { errno=EINVAL; return (tmsize_t) -1; } return ((tmsize_t) read((int) fd, buf, size_io)); } static tmsize_t _tiffWriteProc(thandle_t fd, void* buf, tmsize_t size) { size_t size_io = (size_t) size; if ((tmsize_t) size_io != size) { errno=EINVAL; return (tmsize_t) -1; } return ((tmsize_t) write((int) fd, buf, size_io)); } static uint64 _tiffSeekProc(thandle_t fd, uint64 off, int whence) { off_t off_io = (off_t) off; if ((uint64) off_io != off) { errno=EINVAL; return (uint64) -1; /* this is really gross */ } return((uint64)lseek((int)fd,off_io,whence)); } static int _tiffCloseProc(thandle_t fd) { return(close((int)fd)); } static uint64 _tiffSizeProc(thandle_t fd) { struct stat sb; if (fstat((int)fd,&sb)<0) return(0); else return((uint64)sb.st_size); } #ifdef HAVE_MMAP #include <sys/mman.h> static int _tiffMapProc(thandle_t fd, void** pbase, toff_t* psize) { uint64 size64 = _tiffSizeProc(fd); tmsize_t sizem = (tmsize_t)size64; if ((uint64)sizem==size64) { *pbase = (void*) mmap(0, (size_t)sizem, PROT_READ, MAP_SHARED, (int) fd, 0); if (*pbase != (void*) -1) { *psize = (tmsize_t)sizem; return (1); } } return (0); } static void _tiffUnmapProc(thandle_t fd, void* base, toff_t size) { (void) fd; (void) munmap(base, (off_t) size); } #else /* !HAVE_MMAP */ static int _tiffMapProc(thandle_t fd, void** pbase, toff_t* psize) { (void) fd; (void) pbase; (void) psize; return (0); } static void _tiffUnmapProc(thandle_t fd, void* base, toff_t size) { (void) fd; (void) base; (void) size; } #endif /* !HAVE_MMAP */ /* * Open a TIFF file descriptor for read/writing. */ TIFF* TIFFFdOpen(int fd, const char* name, const char* mode) { TIFF* tif; tif = TIFFClientOpen(name, mode, (thandle_t) fd, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); if (tif) tif->tif_fd = fd; return (tif); } /* * Open a TIFF file for read/writing. */ TIFF* TIFFOpen(const char* name, const char* mode) { static const char module[] = "TIFFOpen"; int m, fd; TIFF* tif; m = _TIFFgetMode(mode, module); if (m == -1) return ((TIFF*)0); /* for cygwin and mingw */ #ifdef O_BINARY m |= O_BINARY; #endif fd = open(name, m, 0666); if (fd < 0) { if (errno > 0 && strerror(errno) != NULL ) { TIFFErrorExt(0, module, "%s: %s", name, strerror(errno) ); } else { TIFFErrorExt(0, module, "%s: Cannot open", name); } return ((TIFF *)0); } tif = TIFFFdOpen((int)fd, name, mode); if(!tif) close(fd); return tif; } #ifdef __WIN32__ #include <windows.h> /* * Open a TIFF file with a Unicode filename, for read/writing. */ TIFF* TIFFOpenW(const wchar_t* name, const char* mode) { static const char module[] = "TIFFOpenW"; int m, fd; int mbsize; char *mbname; TIFF* tif; m = _TIFFgetMode(mode, module); if (m == -1) return ((TIFF*)0); /* for cygwin and mingw */ #ifdef O_BINARY m |= O_BINARY; #endif fd = _wopen(name, m, 0666); if (fd < 0) { TIFFErrorExt(0, module, "%s: Cannot open", name); return ((TIFF *)0); } mbname = NULL; mbsize = WideCharToMultiByte(CP_ACP, 0, name, -1, NULL, 0, NULL, NULL); if (mbsize > 0) { mbname = _TIFFmalloc(mbsize); if (!mbname) { TIFFErrorExt(0, module, "Can't allocate space for filename conversion buffer"); return ((TIFF*)0); } WideCharToMultiByte(CP_ACP, 0, name, -1, mbname, mbsize, NULL, NULL); } tif = TIFFFdOpen((int)fd, (mbname != NULL) ? mbname : "<unknown>", mode); _TIFFfree(mbname); if(!tif) close(fd); return tif; } #endif void* _TIFFmalloc(tmsize_t s) { if (s == 0) return ((void *) NULL); return (malloc((size_t) s)); } void _TIFFfree(void* p) { free(p); } void* _TIFFrealloc(void* p, tmsize_t s) { return (realloc(p, (size_t) s)); } void _TIFFmemset(void* p, int v, tmsize_t c) { memset(p, v, (size_t) c); } void _TIFFmemcpy(void* d, const void* s, tmsize_t c) { memcpy(d, s, (size_t) c); } int _TIFFmemcmp(const void* p1, const void* p2, tmsize_t c) { return (memcmp(p1, p2, (size_t) c)); } static void unixWarningHandler(const char* module, const char* fmt, va_list ap) { if (module != NULL) fprintf(stderr, "%s: ", module); fprintf(stderr, "Warning, "); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); } TIFFErrorHandler _TIFFwarningHandler = unixWarningHandler; static void unixErrorHandler(const char* module, const char* fmt, va_list ap) { if (module != NULL) fprintf(stderr, "%s: ", module); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); } TIFFErrorHandler _TIFFerrorHandler = unixErrorHandler; /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-369/c/good_2303_1
crossvul-cpp_data_good_3035_0
/* * Edgeport USB Serial Converter driver * * Copyright (C) 2000-2002 Inside Out Networks, All rights reserved. * Copyright (C) 2001-2002 Greg Kroah-Hartman <greg@kroah.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. * * Supports the following devices: * EP/1 EP/2 EP/4 EP/21 EP/22 EP/221 EP/42 EP/421 WATCHPORT * * For questions or problems with this driver, contact Inside Out * Networks technical support, or Peter Berger <pberger@brimson.com>, * or Al Borchers <alborchers@steinerpoint.com>. */ #include <linux/kernel.h> #include <linux/jiffies.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/mutex.h> #include <linux/serial.h> #include <linux/swab.h> #include <linux/kfifo.h> #include <linux/ioctl.h> #include <linux/firmware.h> #include <linux/uaccess.h> #include <linux/usb.h> #include <linux/usb/serial.h> #include "io_16654.h" #include "io_usbvend.h" #include "io_ti.h" #define DRIVER_AUTHOR "Greg Kroah-Hartman <greg@kroah.com> and David Iacovelli" #define DRIVER_DESC "Edgeport USB Serial Driver" #define EPROM_PAGE_SIZE 64 /* different hardware types */ #define HARDWARE_TYPE_930 0 #define HARDWARE_TYPE_TIUMP 1 /* IOCTL_PRIVATE_TI_GET_MODE Definitions */ #define TI_MODE_CONFIGURING 0 /* Device has not entered start device */ #define TI_MODE_BOOT 1 /* Staying in boot mode */ #define TI_MODE_DOWNLOAD 2 /* Made it to download mode */ #define TI_MODE_TRANSITIONING 3 /* * Currently in boot mode but * transitioning to download mode */ /* read urb state */ #define EDGE_READ_URB_RUNNING 0 #define EDGE_READ_URB_STOPPING 1 #define EDGE_READ_URB_STOPPED 2 #define EDGE_CLOSING_WAIT 4000 /* in .01 sec */ /* Product information read from the Edgeport */ struct product_info { int TiMode; /* Current TI Mode */ __u8 hardware_type; /* Type of hardware */ } __attribute__((packed)); /* * Edgeport firmware header * * "build_number" has been set to 0 in all three of the images I have * seen, and Digi Tech Support suggests that it is safe to ignore it. * * "length" is the number of bytes of actual data following the header. * * "checksum" is the low order byte resulting from adding the values of * all the data bytes. */ struct edgeport_fw_hdr { u8 major_version; u8 minor_version; __le16 build_number; __le16 length; u8 checksum; } __packed; struct edgeport_port { __u16 uart_base; __u16 dma_address; __u8 shadow_msr; __u8 shadow_mcr; __u8 shadow_lsr; __u8 lsr_mask; __u32 ump_read_timeout; /* * Number of milliseconds the UMP will * wait without data before completing * a read short */ int baud_rate; int close_pending; int lsr_event; struct edgeport_serial *edge_serial; struct usb_serial_port *port; __u8 bUartMode; /* Port type, 0: RS232, etc. */ spinlock_t ep_lock; int ep_read_urb_state; int ep_write_urb_in_use; }; struct edgeport_serial { struct product_info product_info; u8 TI_I2C_Type; /* Type of I2C in UMP */ u8 TiReadI2C; /* * Set to TRUE if we have read the * I2c in Boot Mode */ struct mutex es_lock; int num_ports_open; struct usb_serial *serial; struct delayed_work heartbeat_work; int fw_version; bool use_heartbeat; }; /* Devices that this driver supports */ static const struct usb_device_id edgeport_1port_id_table[] = { { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROXIMITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOTION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOISTURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_TEMPERATURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_HUMIDITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_POWER) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_LIGHT) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_RADIATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_DISTANCE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_ACCELERATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROX_DIST) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_HP4CD) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_PCI) }, { } }; static const struct usb_device_id edgeport_2port_id_table[] = { { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_421) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_42) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_221C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21C) }, /* The 4, 8 and 16 port devices show up as multiple 2 port devices */ { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416B) }, { } }; /* Devices that this driver supports */ static const struct usb_device_id id_table_combined[] = { { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROXIMITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOTION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOISTURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_TEMPERATURE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_HUMIDITY) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_POWER) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_LIGHT) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_RADIATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_DISTANCE) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_ACCELERATION) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROX_DIST) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_HP4CD) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_PCI) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_421) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_42) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22I) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_221C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21C) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8S) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416) }, { USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416B) }, { } }; MODULE_DEVICE_TABLE(usb, id_table_combined); static int closing_wait = EDGE_CLOSING_WAIT; static bool ignore_cpu_rev; static int default_uart_mode; /* RS232 */ static void edge_tty_recv(struct usb_serial_port *port, unsigned char *data, int length); static void stop_read(struct edgeport_port *edge_port); static int restart_read(struct edgeport_port *edge_port); static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios); static void edge_send(struct usb_serial_port *port, struct tty_struct *tty); static int do_download_mode(struct edgeport_serial *serial, const struct firmware *fw); static int do_boot_mode(struct edgeport_serial *serial, const struct firmware *fw); /* sysfs attributes */ static int edge_create_sysfs_attrs(struct usb_serial_port *port); static int edge_remove_sysfs_attrs(struct usb_serial_port *port); /* * Some release of Edgeport firmware "down3.bin" after version 4.80 * introduced code to automatically disconnect idle devices on some * Edgeport models after periods of inactivity, typically ~60 seconds. * This occurs without regard to whether ports on the device are open * or not. Digi International Tech Support suggested: * * 1. Adding driver "heartbeat" code to reset the firmware timer by * requesting a descriptor record every 15 seconds, which should be * effective with newer firmware versions that require it, and benign * with older versions that do not. In practice 40 seconds seems often * enough. * 2. The heartbeat code is currently required only on Edgeport/416 models. */ #define FW_HEARTBEAT_VERSION_CUTOFF ((4 << 8) + 80) #define FW_HEARTBEAT_SECS 40 /* Timeouts in msecs: firmware downloads take longer */ #define TI_VSEND_TIMEOUT_DEFAULT 1000 #define TI_VSEND_TIMEOUT_FW_DOWNLOAD 10000 static int ti_vread_sync(struct usb_device *dev, __u8 request, __u16 value, __u16 index, u8 *data, int size) { int status; status = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), request, (USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN), value, index, data, size, 1000); if (status < 0) return status; if (status != size) { dev_dbg(&dev->dev, "%s - wanted to write %d, but only wrote %d\n", __func__, size, status); return -ECOMM; } return 0; } static int ti_vsend_sync(struct usb_device *dev, u8 request, u16 value, u16 index, u8 *data, int size, int timeout) { int status; status = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), request, (USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT), value, index, data, size, timeout); if (status < 0) return status; if (status != size) { dev_dbg(&dev->dev, "%s - wanted to write %d, but only wrote %d\n", __func__, size, status); return -ECOMM; } return 0; } static int send_cmd(struct usb_device *dev, __u8 command, __u8 moduleid, __u16 value, u8 *data, int size) { return ti_vsend_sync(dev, command, value, moduleid, data, size, TI_VSEND_TIMEOUT_DEFAULT); } /* clear tx/rx buffers and fifo in TI UMP */ static int purge_port(struct usb_serial_port *port, __u16 mask) { int port_number = port->port_number; dev_dbg(&port->dev, "%s - port %d, mask %x\n", __func__, port_number, mask); return send_cmd(port->serial->dev, UMPC_PURGE_PORT, (__u8)(UMPM_UART1_PORT + port_number), mask, NULL, 0); } /** * read_download_mem - Read edgeport memory from TI chip * @dev: usb device pointer * @start_address: Device CPU address at which to read * @length: Length of above data * @address_type: Can read both XDATA and I2C * @buffer: pointer to input data buffer */ static int read_download_mem(struct usb_device *dev, int start_address, int length, __u8 address_type, __u8 *buffer) { int status = 0; __u8 read_length; u16 be_start_address; dev_dbg(&dev->dev, "%s - @ %x for %d\n", __func__, start_address, length); /* * Read in blocks of 64 bytes * (TI firmware can't handle more than 64 byte reads) */ while (length) { if (length > 64) read_length = 64; else read_length = (__u8)length; if (read_length > 1) { dev_dbg(&dev->dev, "%s - @ %x for %d\n", __func__, start_address, read_length); } /* * NOTE: Must use swab as wIndex is sent in little-endian * byte order regardless of host byte order. */ be_start_address = swab16((u16)start_address); status = ti_vread_sync(dev, UMPC_MEMORY_READ, (__u16)address_type, be_start_address, buffer, read_length); if (status) { dev_dbg(&dev->dev, "%s - ERROR %x\n", __func__, status); return status; } if (read_length > 1) usb_serial_debug_data(&dev->dev, __func__, read_length, buffer); /* Update pointers/length */ start_address += read_length; buffer += read_length; length -= read_length; } return status; } static int read_ram(struct usb_device *dev, int start_address, int length, __u8 *buffer) { return read_download_mem(dev, start_address, length, DTK_ADDR_SPACE_XDATA, buffer); } /* Read edgeport memory to a given block */ static int read_boot_mem(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { int status = 0; int i; for (i = 0; i < length; i++) { status = ti_vread_sync(serial->serial->dev, UMPC_MEMORY_READ, serial->TI_I2C_Type, (__u16)(start_address+i), &buffer[i], 0x01); if (status) { dev_dbg(&serial->serial->dev->dev, "%s - ERROR %x\n", __func__, status); return status; } } dev_dbg(&serial->serial->dev->dev, "%s - start_address = %x, length = %d\n", __func__, start_address, length); usb_serial_debug_data(&serial->serial->dev->dev, __func__, length, buffer); serial->TiReadI2C = 1; return status; } /* Write given block to TI EPROM memory */ static int write_boot_mem(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { int status = 0; int i; u8 *temp; /* Must do a read before write */ if (!serial->TiReadI2C) { temp = kmalloc(1, GFP_KERNEL); if (!temp) return -ENOMEM; status = read_boot_mem(serial, 0, 1, temp); kfree(temp); if (status) return status; } for (i = 0; i < length; ++i) { status = ti_vsend_sync(serial->serial->dev, UMPC_MEMORY_WRITE, buffer[i], (u16)(i + start_address), NULL, 0, TI_VSEND_TIMEOUT_DEFAULT); if (status) return status; } dev_dbg(&serial->serial->dev->dev, "%s - start_sddr = %x, length = %d\n", __func__, start_address, length); usb_serial_debug_data(&serial->serial->dev->dev, __func__, length, buffer); return status; } /* Write edgeport I2C memory to TI chip */ static int write_i2c_mem(struct edgeport_serial *serial, int start_address, int length, __u8 address_type, __u8 *buffer) { struct device *dev = &serial->serial->dev->dev; int status = 0; int write_length; u16 be_start_address; /* We can only send a maximum of 1 aligned byte page at a time */ /* calculate the number of bytes left in the first page */ write_length = EPROM_PAGE_SIZE - (start_address & (EPROM_PAGE_SIZE - 1)); if (write_length > length) write_length = length; dev_dbg(dev, "%s - BytesInFirstPage Addr = %x, length = %d\n", __func__, start_address, write_length); usb_serial_debug_data(dev, __func__, write_length, buffer); /* * Write first page. * * NOTE: Must use swab as wIndex is sent in little-endian byte order * regardless of host byte order. */ be_start_address = swab16((u16)start_address); status = ti_vsend_sync(serial->serial->dev, UMPC_MEMORY_WRITE, (u16)address_type, be_start_address, buffer, write_length, TI_VSEND_TIMEOUT_DEFAULT); if (status) { dev_dbg(dev, "%s - ERROR %d\n", __func__, status); return status; } length -= write_length; start_address += write_length; buffer += write_length; /* * We should be aligned now -- can write max page size bytes at a * time. */ while (length) { if (length > EPROM_PAGE_SIZE) write_length = EPROM_PAGE_SIZE; else write_length = length; dev_dbg(dev, "%s - Page Write Addr = %x, length = %d\n", __func__, start_address, write_length); usb_serial_debug_data(dev, __func__, write_length, buffer); /* * Write next page. * * NOTE: Must use swab as wIndex is sent in little-endian byte * order regardless of host byte order. */ be_start_address = swab16((u16)start_address); status = ti_vsend_sync(serial->serial->dev, UMPC_MEMORY_WRITE, (u16)address_type, be_start_address, buffer, write_length, TI_VSEND_TIMEOUT_DEFAULT); if (status) { dev_err(dev, "%s - ERROR %d\n", __func__, status); return status; } length -= write_length; start_address += write_length; buffer += write_length; } return status; } /* * Examine the UMP DMA registers and LSR * * Check the MSBit of the X and Y DMA byte count registers. * A zero in this bit indicates that the TX DMA buffers are empty * then check the TX Empty bit in the UART. */ static int tx_active(struct edgeport_port *port) { int status; struct out_endpoint_desc_block *oedb; __u8 *lsr; int bytes_left = 0; oedb = kmalloc(sizeof(*oedb), GFP_KERNEL); if (!oedb) return -ENOMEM; /* * Sigh, that's right, just one byte, as not all platforms can * do DMA from stack */ lsr = kmalloc(1, GFP_KERNEL); if (!lsr) { kfree(oedb); return -ENOMEM; } /* Read the DMA Count Registers */ status = read_ram(port->port->serial->dev, port->dma_address, sizeof(*oedb), (void *)oedb); if (status) goto exit_is_tx_active; dev_dbg(&port->port->dev, "%s - XByteCount 0x%X\n", __func__, oedb->XByteCount); /* and the LSR */ status = read_ram(port->port->serial->dev, port->uart_base + UMPMEM_OFFS_UART_LSR, 1, lsr); if (status) goto exit_is_tx_active; dev_dbg(&port->port->dev, "%s - LSR = 0x%X\n", __func__, *lsr); /* If either buffer has data or we are transmitting then return TRUE */ if ((oedb->XByteCount & 0x80) != 0) bytes_left += 64; if ((*lsr & UMP_UART_LSR_TX_MASK) == 0) bytes_left += 1; /* We return Not Active if we get any kind of error */ exit_is_tx_active: dev_dbg(&port->port->dev, "%s - return %d\n", __func__, bytes_left); kfree(lsr); kfree(oedb); return bytes_left; } static int choose_config(struct usb_device *dev) { /* * There may be multiple configurations on this device, in which case * we would need to read and parse all of them to find out which one * we want. However, we just support one config at this point, * configuration # 1, which is Config Descriptor 0. */ dev_dbg(&dev->dev, "%s - Number of Interfaces = %d\n", __func__, dev->config->desc.bNumInterfaces); dev_dbg(&dev->dev, "%s - MAX Power = %d\n", __func__, dev->config->desc.bMaxPower * 2); if (dev->config->desc.bNumInterfaces != 1) { dev_err(&dev->dev, "%s - bNumInterfaces is not 1, ERROR!\n", __func__); return -ENODEV; } return 0; } static int read_rom(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { int status; if (serial->product_info.TiMode == TI_MODE_DOWNLOAD) { status = read_download_mem(serial->serial->dev, start_address, length, serial->TI_I2C_Type, buffer); } else { status = read_boot_mem(serial, start_address, length, buffer); } return status; } static int write_rom(struct edgeport_serial *serial, int start_address, int length, __u8 *buffer) { if (serial->product_info.TiMode == TI_MODE_BOOT) return write_boot_mem(serial, start_address, length, buffer); if (serial->product_info.TiMode == TI_MODE_DOWNLOAD) return write_i2c_mem(serial, start_address, length, serial->TI_I2C_Type, buffer); return -EINVAL; } /* Read a descriptor header from I2C based on type */ static int get_descriptor_addr(struct edgeport_serial *serial, int desc_type, struct ti_i2c_desc *rom_desc) { int start_address; int status; /* Search for requested descriptor in I2C */ start_address = 2; do { status = read_rom(serial, start_address, sizeof(struct ti_i2c_desc), (__u8 *)rom_desc); if (status) return 0; if (rom_desc->Type == desc_type) return start_address; start_address = start_address + sizeof(struct ti_i2c_desc) + le16_to_cpu(rom_desc->Size); } while ((start_address < TI_MAX_I2C_SIZE) && rom_desc->Type); return 0; } /* Validate descriptor checksum */ static int valid_csum(struct ti_i2c_desc *rom_desc, __u8 *buffer) { __u16 i; __u8 cs = 0; for (i = 0; i < le16_to_cpu(rom_desc->Size); i++) cs = (__u8)(cs + buffer[i]); if (cs != rom_desc->CheckSum) { pr_debug("%s - Mismatch %x - %x", __func__, rom_desc->CheckSum, cs); return -EINVAL; } return 0; } /* Make sure that the I2C image is good */ static int check_i2c_image(struct edgeport_serial *serial) { struct device *dev = &serial->serial->dev->dev; int status = 0; struct ti_i2c_desc *rom_desc; int start_address = 2; __u8 *buffer; __u16 ttype; rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL); if (!rom_desc) return -ENOMEM; buffer = kmalloc(TI_MAX_I2C_SIZE, GFP_KERNEL); if (!buffer) { kfree(rom_desc); return -ENOMEM; } /* Read the first byte (Signature0) must be 0x52 or 0x10 */ status = read_rom(serial, 0, 1, buffer); if (status) goto out; if (*buffer != UMP5152 && *buffer != UMP3410) { dev_err(dev, "%s - invalid buffer signature\n", __func__); status = -ENODEV; goto out; } do { /* Validate the I2C */ status = read_rom(serial, start_address, sizeof(struct ti_i2c_desc), (__u8 *)rom_desc); if (status) break; if ((start_address + sizeof(struct ti_i2c_desc) + le16_to_cpu(rom_desc->Size)) > TI_MAX_I2C_SIZE) { status = -ENODEV; dev_dbg(dev, "%s - structure too big, erroring out.\n", __func__); break; } dev_dbg(dev, "%s Type = 0x%x\n", __func__, rom_desc->Type); /* Skip type 2 record */ ttype = rom_desc->Type & 0x0f; if (ttype != I2C_DESC_TYPE_FIRMWARE_BASIC && ttype != I2C_DESC_TYPE_FIRMWARE_AUTO) { /* Read the descriptor data */ status = read_rom(serial, start_address + sizeof(struct ti_i2c_desc), le16_to_cpu(rom_desc->Size), buffer); if (status) break; status = valid_csum(rom_desc, buffer); if (status) break; } start_address = start_address + sizeof(struct ti_i2c_desc) + le16_to_cpu(rom_desc->Size); } while ((rom_desc->Type != I2C_DESC_TYPE_ION) && (start_address < TI_MAX_I2C_SIZE)); if ((rom_desc->Type != I2C_DESC_TYPE_ION) || (start_address > TI_MAX_I2C_SIZE)) status = -ENODEV; out: kfree(buffer); kfree(rom_desc); return status; } static int get_manuf_info(struct edgeport_serial *serial, __u8 *buffer) { int status; int start_address; struct ti_i2c_desc *rom_desc; struct edge_ti_manuf_descriptor *desc; struct device *dev = &serial->serial->dev->dev; rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL); if (!rom_desc) return -ENOMEM; start_address = get_descriptor_addr(serial, I2C_DESC_TYPE_ION, rom_desc); if (!start_address) { dev_dbg(dev, "%s - Edge Descriptor not found in I2C\n", __func__); status = -ENODEV; goto exit; } /* Read the descriptor data */ status = read_rom(serial, start_address+sizeof(struct ti_i2c_desc), le16_to_cpu(rom_desc->Size), buffer); if (status) goto exit; status = valid_csum(rom_desc, buffer); desc = (struct edge_ti_manuf_descriptor *)buffer; dev_dbg(dev, "%s - IonConfig 0x%x\n", __func__, desc->IonConfig); dev_dbg(dev, "%s - Version %d\n", __func__, desc->Version); dev_dbg(dev, "%s - Cpu/Board 0x%x\n", __func__, desc->CpuRev_BoardRev); dev_dbg(dev, "%s - NumPorts %d\n", __func__, desc->NumPorts); dev_dbg(dev, "%s - NumVirtualPorts %d\n", __func__, desc->NumVirtualPorts); dev_dbg(dev, "%s - TotalPorts %d\n", __func__, desc->TotalPorts); exit: kfree(rom_desc); return status; } /* Build firmware header used for firmware update */ static int build_i2c_fw_hdr(u8 *header, const struct firmware *fw) { __u8 *buffer; int buffer_size; int i; __u8 cs = 0; struct ti_i2c_desc *i2c_header; struct ti_i2c_image_header *img_header; struct ti_i2c_firmware_rec *firmware_rec; struct edgeport_fw_hdr *fw_hdr = (struct edgeport_fw_hdr *)fw->data; /* * In order to update the I2C firmware we must change the type 2 record * to type 0xF2. This will force the UMP to come up in Boot Mode. * Then while in boot mode, the driver will download the latest * firmware (padded to 15.5k) into the UMP ram. And finally when the * device comes back up in download mode the driver will cause the new * firmware to be copied from the UMP Ram to I2C and the firmware will * update the record type from 0xf2 to 0x02. */ /* * Allocate a 15.5k buffer + 2 bytes for version number (Firmware * Record) */ buffer_size = (((1024 * 16) - 512 ) + sizeof(struct ti_i2c_firmware_rec)); buffer = kmalloc(buffer_size, GFP_KERNEL); if (!buffer) return -ENOMEM; /* Set entire image of 0xffs */ memset(buffer, 0xff, buffer_size); /* Copy version number into firmware record */ firmware_rec = (struct ti_i2c_firmware_rec *)buffer; firmware_rec->Ver_Major = fw_hdr->major_version; firmware_rec->Ver_Minor = fw_hdr->minor_version; /* Pointer to fw_down memory image */ img_header = (struct ti_i2c_image_header *)&fw->data[4]; memcpy(buffer + sizeof(struct ti_i2c_firmware_rec), &fw->data[4 + sizeof(struct ti_i2c_image_header)], le16_to_cpu(img_header->Length)); for (i=0; i < buffer_size; i++) { cs = (__u8)(cs + buffer[i]); } kfree(buffer); /* Build new header */ i2c_header = (struct ti_i2c_desc *)header; firmware_rec = (struct ti_i2c_firmware_rec*)i2c_header->Data; i2c_header->Type = I2C_DESC_TYPE_FIRMWARE_BLANK; i2c_header->Size = cpu_to_le16(buffer_size); i2c_header->CheckSum = cs; firmware_rec->Ver_Major = fw_hdr->major_version; firmware_rec->Ver_Minor = fw_hdr->minor_version; return 0; } /* Try to figure out what type of I2c we have */ static int i2c_type_bootmode(struct edgeport_serial *serial) { struct device *dev = &serial->serial->dev->dev; int status; u8 *data; data = kmalloc(1, GFP_KERNEL); if (!data) return -ENOMEM; /* Try to read type 2 */ status = ti_vread_sync(serial->serial->dev, UMPC_MEMORY_READ, DTK_ADDR_SPACE_I2C_TYPE_II, 0, data, 0x01); if (status) dev_dbg(dev, "%s - read 2 status error = %d\n", __func__, status); else dev_dbg(dev, "%s - read 2 data = 0x%x\n", __func__, *data); if ((!status) && (*data == UMP5152 || *data == UMP3410)) { dev_dbg(dev, "%s - ROM_TYPE_II\n", __func__); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; goto out; } /* Try to read type 3 */ status = ti_vread_sync(serial->serial->dev, UMPC_MEMORY_READ, DTK_ADDR_SPACE_I2C_TYPE_III, 0, data, 0x01); if (status) dev_dbg(dev, "%s - read 3 status error = %d\n", __func__, status); else dev_dbg(dev, "%s - read 2 data = 0x%x\n", __func__, *data); if ((!status) && (*data == UMP5152 || *data == UMP3410)) { dev_dbg(dev, "%s - ROM_TYPE_III\n", __func__); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_III; goto out; } dev_dbg(dev, "%s - Unknown\n", __func__); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; status = -ENODEV; out: kfree(data); return status; } static int bulk_xfer(struct usb_serial *serial, void *buffer, int length, int *num_sent) { int status; status = usb_bulk_msg(serial->dev, usb_sndbulkpipe(serial->dev, serial->port[0]->bulk_out_endpointAddress), buffer, length, num_sent, 1000); return status; } /* Download given firmware image to the device (IN BOOT MODE) */ static int download_code(struct edgeport_serial *serial, __u8 *image, int image_length) { int status = 0; int pos; int transfer; int done; /* Transfer firmware image */ for (pos = 0; pos < image_length; ) { /* Read the next buffer from file */ transfer = image_length - pos; if (transfer > EDGE_FW_BULK_MAX_PACKET_SIZE) transfer = EDGE_FW_BULK_MAX_PACKET_SIZE; /* Transfer data */ status = bulk_xfer(serial->serial, &image[pos], transfer, &done); if (status) break; /* Advance buffer pointer */ pos += done; } return status; } /* FIXME!!! */ static int config_boot_dev(struct usb_device *dev) { return 0; } static int ti_cpu_rev(struct edge_ti_manuf_descriptor *desc) { return TI_GET_CPU_REVISION(desc->CpuRev_BoardRev); } static int check_fw_sanity(struct edgeport_serial *serial, const struct firmware *fw) { u16 length_total; u8 checksum = 0; int pos; struct device *dev = &serial->serial->interface->dev; struct edgeport_fw_hdr *fw_hdr = (struct edgeport_fw_hdr *)fw->data; if (fw->size < sizeof(struct edgeport_fw_hdr)) { dev_err(dev, "incomplete fw header\n"); return -EINVAL; } length_total = le16_to_cpu(fw_hdr->length) + sizeof(struct edgeport_fw_hdr); if (fw->size != length_total) { dev_err(dev, "bad fw size (expected: %u, got: %zu)\n", length_total, fw->size); return -EINVAL; } for (pos = sizeof(struct edgeport_fw_hdr); pos < fw->size; ++pos) checksum += fw->data[pos]; if (checksum != fw_hdr->checksum) { dev_err(dev, "bad fw checksum (expected: 0x%x, got: 0x%x)\n", fw_hdr->checksum, checksum); return -EINVAL; } return 0; } /* * DownloadTIFirmware - Download run-time operating firmware to the TI5052 * * This routine downloads the main operating code into the TI5052, using the * boot code already burned into E2PROM or ROM. */ static int download_fw(struct edgeport_serial *serial) { struct device *dev = &serial->serial->interface->dev; int status = 0; struct usb_interface_descriptor *interface; const struct firmware *fw; const char *fw_name = "edgeport/down3.bin"; struct edgeport_fw_hdr *fw_hdr; status = request_firmware(&fw, fw_name, dev); if (status) { dev_err(dev, "Failed to load image \"%s\" err %d\n", fw_name, status); return status; } if (check_fw_sanity(serial, fw)) { status = -EINVAL; goto out; } fw_hdr = (struct edgeport_fw_hdr *)fw->data; /* If on-board version is newer, "fw_version" will be updated later. */ serial->fw_version = (fw_hdr->major_version << 8) + fw_hdr->minor_version; /* * This routine is entered by both the BOOT mode and the Download mode * We can determine which code is running by the reading the config * descriptor and if we have only one bulk pipe it is in boot mode */ serial->product_info.hardware_type = HARDWARE_TYPE_TIUMP; /* Default to type 2 i2c */ serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; status = choose_config(serial->serial->dev); if (status) goto out; interface = &serial->serial->interface->cur_altsetting->desc; if (!interface) { dev_err(dev, "%s - no interface set, error!\n", __func__); status = -ENODEV; goto out; } /* * Setup initial mode -- the default mode 0 is TI_MODE_CONFIGURING * if we have more than one endpoint we are definitely in download * mode */ if (interface->bNumEndpoints > 1) { serial->product_info.TiMode = TI_MODE_DOWNLOAD; status = do_download_mode(serial, fw); } else { /* Otherwise we will remain in configuring mode */ serial->product_info.TiMode = TI_MODE_CONFIGURING; status = do_boot_mode(serial, fw); } out: release_firmware(fw); return status; } static int do_download_mode(struct edgeport_serial *serial, const struct firmware *fw) { struct device *dev = &serial->serial->interface->dev; int status = 0; int start_address; struct edge_ti_manuf_descriptor *ti_manuf_desc; int download_cur_ver; int download_new_ver; struct edgeport_fw_hdr *fw_hdr = (struct edgeport_fw_hdr *)fw->data; struct ti_i2c_desc *rom_desc; dev_dbg(dev, "%s - RUNNING IN DOWNLOAD MODE\n", __func__); status = check_i2c_image(serial); if (status) { dev_dbg(dev, "%s - DOWNLOAD MODE -- BAD I2C\n", __func__); return status; } /* * Validate Hardware version number * Read Manufacturing Descriptor from TI Based Edgeport */ ti_manuf_desc = kmalloc(sizeof(*ti_manuf_desc), GFP_KERNEL); if (!ti_manuf_desc) return -ENOMEM; status = get_manuf_info(serial, (__u8 *)ti_manuf_desc); if (status) { kfree(ti_manuf_desc); return status; } /* Check version number of ION descriptor */ if (!ignore_cpu_rev && ti_cpu_rev(ti_manuf_desc) < 2) { dev_dbg(dev, "%s - Wrong CPU Rev %d (Must be 2)\n", __func__, ti_cpu_rev(ti_manuf_desc)); kfree(ti_manuf_desc); return -EINVAL; } rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL); if (!rom_desc) { kfree(ti_manuf_desc); return -ENOMEM; } /* Search for type 2 record (firmware record) */ start_address = get_descriptor_addr(serial, I2C_DESC_TYPE_FIRMWARE_BASIC, rom_desc); if (start_address != 0) { struct ti_i2c_firmware_rec *firmware_version; u8 *record; dev_dbg(dev, "%s - Found Type FIRMWARE (Type 2) record\n", __func__); firmware_version = kmalloc(sizeof(*firmware_version), GFP_KERNEL); if (!firmware_version) { kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } /* * Validate version number * Read the descriptor data */ status = read_rom(serial, start_address + sizeof(struct ti_i2c_desc), sizeof(struct ti_i2c_firmware_rec), (__u8 *)firmware_version); if (status) { kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return status; } /* * Check version number of download with current * version in I2c */ download_cur_ver = (firmware_version->Ver_Major << 8) + (firmware_version->Ver_Minor); download_new_ver = (fw_hdr->major_version << 8) + (fw_hdr->minor_version); dev_dbg(dev, "%s - >> FW Versions Device %d.%d Driver %d.%d\n", __func__, firmware_version->Ver_Major, firmware_version->Ver_Minor, fw_hdr->major_version, fw_hdr->minor_version); /* * Check if we have an old version in the I2C and * update if necessary */ if (download_cur_ver < download_new_ver) { dev_dbg(dev, "%s - Update I2C dld from %d.%d to %d.%d\n", __func__, firmware_version->Ver_Major, firmware_version->Ver_Minor, fw_hdr->major_version, fw_hdr->minor_version); record = kmalloc(1, GFP_KERNEL); if (!record) { kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } /* * In order to update the I2C firmware we must * change the type 2 record to type 0xF2. This * will force the UMP to come up in Boot Mode. * Then while in boot mode, the driver will * download the latest firmware (padded to * 15.5k) into the UMP ram. Finally when the * device comes back up in download mode the * driver will cause the new firmware to be * copied from the UMP Ram to I2C and the * firmware will update the record type from * 0xf2 to 0x02. */ *record = I2C_DESC_TYPE_FIRMWARE_BLANK; /* * Change the I2C Firmware record type to * 0xf2 to trigger an update */ status = write_rom(serial, start_address, sizeof(*record), record); if (status) { kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return status; } /* * verify the write -- must do this in order * for write to complete before we do the * hardware reset */ status = read_rom(serial, start_address, sizeof(*record), record); if (status) { kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return status; } if (*record != I2C_DESC_TYPE_FIRMWARE_BLANK) { dev_err(dev, "%s - error resetting device\n", __func__); kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return -ENODEV; } dev_dbg(dev, "%s - HARDWARE RESET\n", __func__); /* Reset UMP -- Back to BOOT MODE */ status = ti_vsend_sync(serial->serial->dev, UMPC_HARDWARE_RESET, 0, 0, NULL, 0, TI_VSEND_TIMEOUT_DEFAULT); dev_dbg(dev, "%s - HARDWARE RESET return %d\n", __func__, status); /* return an error on purpose. */ kfree(record); kfree(firmware_version); kfree(rom_desc); kfree(ti_manuf_desc); return -ENODEV; } /* Same or newer fw version is already loaded */ serial->fw_version = download_cur_ver; kfree(firmware_version); } /* Search for type 0xF2 record (firmware blank record) */ else { start_address = get_descriptor_addr(serial, I2C_DESC_TYPE_FIRMWARE_BLANK, rom_desc); if (start_address != 0) { #define HEADER_SIZE (sizeof(struct ti_i2c_desc) + \ sizeof(struct ti_i2c_firmware_rec)) __u8 *header; __u8 *vheader; header = kmalloc(HEADER_SIZE, GFP_KERNEL); if (!header) { kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } vheader = kmalloc(HEADER_SIZE, GFP_KERNEL); if (!vheader) { kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -ENOMEM; } dev_dbg(dev, "%s - Found Type BLANK FIRMWARE (Type F2) record\n", __func__); /* * In order to update the I2C firmware we must change * the type 2 record to type 0xF2. This will force the * UMP to come up in Boot Mode. Then while in boot * mode, the driver will download the latest firmware * (padded to 15.5k) into the UMP ram. Finally when the * device comes back up in download mode the driver * will cause the new firmware to be copied from the * UMP Ram to I2C and the firmware will update the * record type from 0xf2 to 0x02. */ status = build_i2c_fw_hdr(header, fw); if (status) { kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -EINVAL; } /* * Update I2C with type 0xf2 record with correct * size and checksum */ status = write_rom(serial, start_address, HEADER_SIZE, header); if (status) { kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -EINVAL; } /* * verify the write -- must do this in order for * write to complete before we do the hardware reset */ status = read_rom(serial, start_address, HEADER_SIZE, vheader); if (status) { dev_dbg(dev, "%s - can't read header back\n", __func__); kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return status; } if (memcmp(vheader, header, HEADER_SIZE)) { dev_dbg(dev, "%s - write download record failed\n", __func__); kfree(vheader); kfree(header); kfree(rom_desc); kfree(ti_manuf_desc); return -EINVAL; } kfree(vheader); kfree(header); dev_dbg(dev, "%s - Start firmware update\n", __func__); /* Tell firmware to copy download image into I2C */ status = ti_vsend_sync(serial->serial->dev, UMPC_COPY_DNLD_TO_I2C, 0, 0, NULL, 0, TI_VSEND_TIMEOUT_FW_DOWNLOAD); dev_dbg(dev, "%s - Update complete 0x%x\n", __func__, status); if (status) { dev_err(dev, "%s - UMPC_COPY_DNLD_TO_I2C failed\n", __func__); kfree(rom_desc); kfree(ti_manuf_desc); return status; } } } /* The device is running the download code */ kfree(rom_desc); kfree(ti_manuf_desc); return 0; } static int do_boot_mode(struct edgeport_serial *serial, const struct firmware *fw) { struct device *dev = &serial->serial->interface->dev; int status = 0; struct edge_ti_manuf_descriptor *ti_manuf_desc; struct edgeport_fw_hdr *fw_hdr = (struct edgeport_fw_hdr *)fw->data; dev_dbg(dev, "%s - RUNNING IN BOOT MODE\n", __func__); /* Configure the TI device so we can use the BULK pipes for download */ status = config_boot_dev(serial->serial->dev); if (status) return status; if (le16_to_cpu(serial->serial->dev->descriptor.idVendor) != USB_VENDOR_ID_ION) { dev_dbg(dev, "%s - VID = 0x%x\n", __func__, le16_to_cpu(serial->serial->dev->descriptor.idVendor)); serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II; goto stayinbootmode; } /* * We have an ION device (I2c Must be programmed) * Determine I2C image type */ if (i2c_type_bootmode(serial)) goto stayinbootmode; /* Check for ION Vendor ID and that the I2C is valid */ if (!check_i2c_image(serial)) { struct ti_i2c_image_header *header; int i; __u8 cs = 0; __u8 *buffer; int buffer_size; /* * Validate Hardware version number * Read Manufacturing Descriptor from TI Based Edgeport */ ti_manuf_desc = kmalloc(sizeof(*ti_manuf_desc), GFP_KERNEL); if (!ti_manuf_desc) return -ENOMEM; status = get_manuf_info(serial, (__u8 *)ti_manuf_desc); if (status) { kfree(ti_manuf_desc); goto stayinbootmode; } /* Check for version 2 */ if (!ignore_cpu_rev && ti_cpu_rev(ti_manuf_desc) < 2) { dev_dbg(dev, "%s - Wrong CPU Rev %d (Must be 2)\n", __func__, ti_cpu_rev(ti_manuf_desc)); kfree(ti_manuf_desc); goto stayinbootmode; } kfree(ti_manuf_desc); /* * In order to update the I2C firmware we must change the type * 2 record to type 0xF2. This will force the UMP to come up * in Boot Mode. Then while in boot mode, the driver will * download the latest firmware (padded to 15.5k) into the * UMP ram. Finally when the device comes back up in download * mode the driver will cause the new firmware to be copied * from the UMP Ram to I2C and the firmware will update the * record type from 0xf2 to 0x02. * * Do we really have to copy the whole firmware image, * or could we do this in place! */ /* Allocate a 15.5k buffer + 3 byte header */ buffer_size = (((1024 * 16) - 512) + sizeof(struct ti_i2c_image_header)); buffer = kmalloc(buffer_size, GFP_KERNEL); if (!buffer) return -ENOMEM; /* Initialize the buffer to 0xff (pad the buffer) */ memset(buffer, 0xff, buffer_size); memcpy(buffer, &fw->data[4], fw->size - 4); for (i = sizeof(struct ti_i2c_image_header); i < buffer_size; i++) { cs = (__u8)(cs + buffer[i]); } header = (struct ti_i2c_image_header *)buffer; /* update length and checksum after padding */ header->Length = cpu_to_le16((__u16)(buffer_size - sizeof(struct ti_i2c_image_header))); header->CheckSum = cs; /* Download the operational code */ dev_dbg(dev, "%s - Downloading operational code image version %d.%d (TI UMP)\n", __func__, fw_hdr->major_version, fw_hdr->minor_version); status = download_code(serial, buffer, buffer_size); kfree(buffer); if (status) { dev_dbg(dev, "%s - Error downloading operational code image\n", __func__); return status; } /* Device will reboot */ serial->product_info.TiMode = TI_MODE_TRANSITIONING; dev_dbg(dev, "%s - Download successful -- Device rebooting...\n", __func__); return 1; } stayinbootmode: /* Eprom is invalid or blank stay in boot mode */ dev_dbg(dev, "%s - STAYING IN BOOT MODE\n", __func__); serial->product_info.TiMode = TI_MODE_BOOT; return 1; } static int ti_do_config(struct edgeport_port *port, int feature, int on) { int port_number = port->port->port_number; on = !!on; /* 1 or 0 not bitmask */ return send_cmd(port->port->serial->dev, feature, (__u8)(UMPM_UART1_PORT + port_number), on, NULL, 0); } static int restore_mcr(struct edgeport_port *port, __u8 mcr) { int status = 0; dev_dbg(&port->port->dev, "%s - %x\n", __func__, mcr); status = ti_do_config(port, UMPC_SET_CLR_DTR, mcr & MCR_DTR); if (status) return status; status = ti_do_config(port, UMPC_SET_CLR_RTS, mcr & MCR_RTS); if (status) return status; return ti_do_config(port, UMPC_SET_CLR_LOOPBACK, mcr & MCR_LOOPBACK); } /* Convert TI LSR to standard UART flags */ static __u8 map_line_status(__u8 ti_lsr) { __u8 lsr = 0; #define MAP_FLAG(flagUmp, flagUart) \ if (ti_lsr & flagUmp) \ lsr |= flagUart; MAP_FLAG(UMP_UART_LSR_OV_MASK, LSR_OVER_ERR) /* overrun */ MAP_FLAG(UMP_UART_LSR_PE_MASK, LSR_PAR_ERR) /* parity error */ MAP_FLAG(UMP_UART_LSR_FE_MASK, LSR_FRM_ERR) /* framing error */ MAP_FLAG(UMP_UART_LSR_BR_MASK, LSR_BREAK) /* break detected */ MAP_FLAG(UMP_UART_LSR_RX_MASK, LSR_RX_AVAIL) /* rx data available */ MAP_FLAG(UMP_UART_LSR_TX_MASK, LSR_TX_EMPTY) /* tx hold reg empty */ #undef MAP_FLAG return lsr; } static void handle_new_msr(struct edgeport_port *edge_port, __u8 msr) { struct async_icount *icount; struct tty_struct *tty; dev_dbg(&edge_port->port->dev, "%s - %02x\n", __func__, msr); if (msr & (EDGEPORT_MSR_DELTA_CTS | EDGEPORT_MSR_DELTA_DSR | EDGEPORT_MSR_DELTA_RI | EDGEPORT_MSR_DELTA_CD)) { icount = &edge_port->port->icount; /* update input line counters */ if (msr & EDGEPORT_MSR_DELTA_CTS) icount->cts++; if (msr & EDGEPORT_MSR_DELTA_DSR) icount->dsr++; if (msr & EDGEPORT_MSR_DELTA_CD) icount->dcd++; if (msr & EDGEPORT_MSR_DELTA_RI) icount->rng++; wake_up_interruptible(&edge_port->port->port.delta_msr_wait); } /* Save the new modem status */ edge_port->shadow_msr = msr & 0xf0; tty = tty_port_tty_get(&edge_port->port->port); /* handle CTS flow control */ if (tty && C_CRTSCTS(tty)) { if (msr & EDGEPORT_MSR_CTS) tty_wakeup(tty); } tty_kref_put(tty); } static void handle_new_lsr(struct edgeport_port *edge_port, int lsr_data, __u8 lsr, __u8 data) { struct async_icount *icount; __u8 new_lsr = (__u8)(lsr & (__u8)(LSR_OVER_ERR | LSR_PAR_ERR | LSR_FRM_ERR | LSR_BREAK)); dev_dbg(&edge_port->port->dev, "%s - %02x\n", __func__, new_lsr); edge_port->shadow_lsr = lsr; if (new_lsr & LSR_BREAK) /* * Parity and Framing errors only count if they * occur exclusive of a break being received. */ new_lsr &= (__u8)(LSR_OVER_ERR | LSR_BREAK); /* Place LSR data byte into Rx buffer */ if (lsr_data) edge_tty_recv(edge_port->port, &data, 1); /* update input line counters */ icount = &edge_port->port->icount; if (new_lsr & LSR_BREAK) icount->brk++; if (new_lsr & LSR_OVER_ERR) icount->overrun++; if (new_lsr & LSR_PAR_ERR) icount->parity++; if (new_lsr & LSR_FRM_ERR) icount->frame++; } static void edge_interrupt_callback(struct urb *urb) { struct edgeport_serial *edge_serial = urb->context; struct usb_serial_port *port; struct edgeport_port *edge_port; struct device *dev; unsigned char *data = urb->transfer_buffer; int length = urb->actual_length; int port_number; int function; int retval; __u8 lsr; __u8 msr; int status = urb->status; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_err(&urb->dev->dev, "%s - nonzero urb status received: " "%d\n", __func__, status); goto exit; } if (!length) { dev_dbg(&urb->dev->dev, "%s - no data in urb\n", __func__); goto exit; } dev = &edge_serial->serial->dev->dev; usb_serial_debug_data(dev, __func__, length, data); if (length != 2) { dev_dbg(dev, "%s - expecting packet of size 2, got %d\n", __func__, length); goto exit; } port_number = TIUMP_GET_PORT_FROM_CODE(data[0]); function = TIUMP_GET_FUNC_FROM_CODE(data[0]); dev_dbg(dev, "%s - port_number %d, function %d, info 0x%x\n", __func__, port_number, function, data[1]); if (port_number >= edge_serial->serial->num_ports) { dev_err(dev, "bad port number %d\n", port_number); goto exit; } port = edge_serial->serial->port[port_number]; edge_port = usb_get_serial_port_data(port); if (!edge_port) { dev_dbg(dev, "%s - edge_port not found\n", __func__); return; } switch (function) { case TIUMP_INTERRUPT_CODE_LSR: lsr = map_line_status(data[1]); if (lsr & UMP_UART_LSR_DATA_MASK) { /* * Save the LSR event for bulk read completion routine */ dev_dbg(dev, "%s - LSR Event Port %u LSR Status = %02x\n", __func__, port_number, lsr); edge_port->lsr_event = 1; edge_port->lsr_mask = lsr; } else { dev_dbg(dev, "%s - ===== Port %d LSR Status = %02x ======\n", __func__, port_number, lsr); handle_new_lsr(edge_port, 0, lsr, 0); } break; case TIUMP_INTERRUPT_CODE_MSR: /* MSR */ /* Copy MSR from UMP */ msr = data[1]; dev_dbg(dev, "%s - ===== Port %u MSR Status = %02x ======\n", __func__, port_number, msr); handle_new_msr(edge_port, msr); break; default: dev_err(&urb->dev->dev, "%s - Unknown Interrupt code from UMP %x\n", __func__, data[1]); break; } exit: retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval) dev_err(&urb->dev->dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval); } static void edge_bulk_in_callback(struct urb *urb) { struct edgeport_port *edge_port = urb->context; struct device *dev = &edge_port->port->dev; unsigned char *data = urb->transfer_buffer; int retval = 0; int port_number; int status = urb->status; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_err(&urb->dev->dev, "%s - nonzero read bulk status received: %d\n", __func__, status); } if (status == -EPIPE) goto exit; if (status) { dev_err(&urb->dev->dev, "%s - stopping read!\n", __func__); return; } port_number = edge_port->port->port_number; if (urb->actual_length > 0 && edge_port->lsr_event) { edge_port->lsr_event = 0; dev_dbg(dev, "%s ===== Port %u LSR Status = %02x, Data = %02x ======\n", __func__, port_number, edge_port->lsr_mask, *data); handle_new_lsr(edge_port, 1, edge_port->lsr_mask, *data); /* Adjust buffer length/pointer */ --urb->actual_length; ++data; } if (urb->actual_length) { usb_serial_debug_data(dev, __func__, urb->actual_length, data); if (edge_port->close_pending) dev_dbg(dev, "%s - close pending, dropping data on the floor\n", __func__); else edge_tty_recv(edge_port->port, data, urb->actual_length); edge_port->port->icount.rx += urb->actual_length; } exit: /* continue read unless stopped */ spin_lock(&edge_port->ep_lock); if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING) retval = usb_submit_urb(urb, GFP_ATOMIC); else if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPING) edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPED; spin_unlock(&edge_port->ep_lock); if (retval) dev_err(dev, "%s - usb_submit_urb failed with result %d\n", __func__, retval); } static void edge_tty_recv(struct usb_serial_port *port, unsigned char *data, int length) { int queued; queued = tty_insert_flip_string(&port->port, data, length); if (queued < length) dev_err(&port->dev, "%s - dropping data, %d bytes lost\n", __func__, length - queued); tty_flip_buffer_push(&port->port); } static void edge_bulk_out_callback(struct urb *urb) { struct usb_serial_port *port = urb->context; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status = urb->status; struct tty_struct *tty; edge_port->ep_write_urb_in_use = 0; switch (status) { case 0: /* success */ break; case -ECONNRESET: case -ENOENT: case -ESHUTDOWN: /* this urb is terminated, clean up */ dev_dbg(&urb->dev->dev, "%s - urb shutting down with status: %d\n", __func__, status); return; default: dev_err_console(port, "%s - nonzero write bulk status " "received: %d\n", __func__, status); } /* send any buffered data */ tty = tty_port_tty_get(&port->port); edge_send(port, tty); tty_kref_put(tty); } static int edge_open(struct tty_struct *tty, struct usb_serial_port *port) { struct edgeport_port *edge_port = usb_get_serial_port_data(port); struct edgeport_serial *edge_serial; struct usb_device *dev; struct urb *urb; int port_number; int status; u16 open_settings; u8 transaction_timeout; if (edge_port == NULL) return -ENODEV; port_number = port->port_number; dev = port->serial->dev; /* turn off loopback */ status = ti_do_config(edge_port, UMPC_SET_CLR_LOOPBACK, 0); if (status) { dev_err(&port->dev, "%s - cannot send clear loopback command, %d\n", __func__, status); return status; } /* set up the port settings */ if (tty) edge_set_termios(tty, port, &tty->termios); /* open up the port */ /* milliseconds to timeout for DMA transfer */ transaction_timeout = 2; edge_port->ump_read_timeout = max(20, ((transaction_timeout * 3) / 2)); /* milliseconds to timeout for DMA transfer */ open_settings = (u8)(UMP_DMA_MODE_CONTINOUS | UMP_PIPE_TRANS_TIMEOUT_ENA | (transaction_timeout << 2)); dev_dbg(&port->dev, "%s - Sending UMPC_OPEN_PORT\n", __func__); /* Tell TI to open and start the port */ status = send_cmd(dev, UMPC_OPEN_PORT, (u8)(UMPM_UART1_PORT + port_number), open_settings, NULL, 0); if (status) { dev_err(&port->dev, "%s - cannot send open command, %d\n", __func__, status); return status; } /* Start the DMA? */ status = send_cmd(dev, UMPC_START_PORT, (u8)(UMPM_UART1_PORT + port_number), 0, NULL, 0); if (status) { dev_err(&port->dev, "%s - cannot send start DMA command, %d\n", __func__, status); return status; } /* Clear TX and RX buffers in UMP */ status = purge_port(port, UMP_PORT_DIR_OUT | UMP_PORT_DIR_IN); if (status) { dev_err(&port->dev, "%s - cannot send clear buffers command, %d\n", __func__, status); return status; } /* Read Initial MSR */ status = ti_vread_sync(dev, UMPC_READ_MSR, 0, (__u16)(UMPM_UART1_PORT + port_number), &edge_port->shadow_msr, 1); if (status) { dev_err(&port->dev, "%s - cannot send read MSR command, %d\n", __func__, status); return status; } dev_dbg(&port->dev, "ShadowMSR 0x%X\n", edge_port->shadow_msr); /* Set Initial MCR */ edge_port->shadow_mcr = MCR_RTS | MCR_DTR; dev_dbg(&port->dev, "ShadowMCR 0x%X\n", edge_port->shadow_mcr); edge_serial = edge_port->edge_serial; if (mutex_lock_interruptible(&edge_serial->es_lock)) return -ERESTARTSYS; if (edge_serial->num_ports_open == 0) { /* we are the first port to open, post the interrupt urb */ urb = edge_serial->serial->port[0]->interrupt_in_urb; urb->context = edge_serial; status = usb_submit_urb(urb, GFP_KERNEL); if (status) { dev_err(&port->dev, "%s - usb_submit_urb failed with value %d\n", __func__, status); goto release_es_lock; } } /* * reset the data toggle on the bulk endpoints to work around bug in * host controllers where things get out of sync some times */ usb_clear_halt(dev, port->write_urb->pipe); usb_clear_halt(dev, port->read_urb->pipe); /* start up our bulk read urb */ urb = port->read_urb; edge_port->ep_read_urb_state = EDGE_READ_URB_RUNNING; urb->context = edge_port; status = usb_submit_urb(urb, GFP_KERNEL); if (status) { dev_err(&port->dev, "%s - read bulk usb_submit_urb failed with value %d\n", __func__, status); goto unlink_int_urb; } ++edge_serial->num_ports_open; goto release_es_lock; unlink_int_urb: if (edge_port->edge_serial->num_ports_open == 0) usb_kill_urb(port->serial->port[0]->interrupt_in_urb); release_es_lock: mutex_unlock(&edge_serial->es_lock); return status; } static void edge_close(struct usb_serial_port *port) { struct edgeport_serial *edge_serial; struct edgeport_port *edge_port; struct usb_serial *serial = port->serial; unsigned long flags; int port_number; edge_serial = usb_get_serial_data(port->serial); edge_port = usb_get_serial_port_data(port); if (edge_serial == NULL || edge_port == NULL) return; /* * The bulkreadcompletion routine will check * this flag and dump add read data */ edge_port->close_pending = 1; usb_kill_urb(port->read_urb); usb_kill_urb(port->write_urb); edge_port->ep_write_urb_in_use = 0; spin_lock_irqsave(&edge_port->ep_lock, flags); kfifo_reset_out(&port->write_fifo); spin_unlock_irqrestore(&edge_port->ep_lock, flags); dev_dbg(&port->dev, "%s - send umpc_close_port\n", __func__); port_number = port->port_number; send_cmd(serial->dev, UMPC_CLOSE_PORT, (__u8)(UMPM_UART1_PORT + port_number), 0, NULL, 0); mutex_lock(&edge_serial->es_lock); --edge_port->edge_serial->num_ports_open; if (edge_port->edge_serial->num_ports_open <= 0) { /* last port is now closed, let's shut down our interrupt urb */ usb_kill_urb(port->serial->port[0]->interrupt_in_urb); edge_port->edge_serial->num_ports_open = 0; } mutex_unlock(&edge_serial->es_lock); edge_port->close_pending = 0; } static int edge_write(struct tty_struct *tty, struct usb_serial_port *port, const unsigned char *data, int count) { struct edgeport_port *edge_port = usb_get_serial_port_data(port); if (count == 0) { dev_dbg(&port->dev, "%s - write request of 0 bytes\n", __func__); return 0; } if (edge_port == NULL) return -ENODEV; if (edge_port->close_pending == 1) return -ENODEV; count = kfifo_in_locked(&port->write_fifo, data, count, &edge_port->ep_lock); edge_send(port, tty); return count; } static void edge_send(struct usb_serial_port *port, struct tty_struct *tty) { int count, result; struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); if (edge_port->ep_write_urb_in_use) { spin_unlock_irqrestore(&edge_port->ep_lock, flags); return; } count = kfifo_out(&port->write_fifo, port->write_urb->transfer_buffer, port->bulk_out_size); if (count == 0) { spin_unlock_irqrestore(&edge_port->ep_lock, flags); return; } edge_port->ep_write_urb_in_use = 1; spin_unlock_irqrestore(&edge_port->ep_lock, flags); usb_serial_debug_data(&port->dev, __func__, count, port->write_urb->transfer_buffer); /* set up our urb */ port->write_urb->transfer_buffer_length = count; /* send the data out the bulk port */ result = usb_submit_urb(port->write_urb, GFP_ATOMIC); if (result) { dev_err_console(port, "%s - failed submitting write urb, error %d\n", __func__, result); edge_port->ep_write_urb_in_use = 0; /* TODO: reschedule edge_send */ } else edge_port->port->icount.tx += count; /* * wakeup any process waiting for writes to complete * there is now more room in the buffer for new writes */ if (tty) tty_wakeup(tty); } static int edge_write_room(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int room = 0; unsigned long flags; if (edge_port == NULL) return 0; if (edge_port->close_pending == 1) return 0; spin_lock_irqsave(&edge_port->ep_lock, flags); room = kfifo_avail(&port->write_fifo); spin_unlock_irqrestore(&edge_port->ep_lock, flags); dev_dbg(&port->dev, "%s - returns %d\n", __func__, room); return room; } static int edge_chars_in_buffer(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int chars = 0; unsigned long flags; if (edge_port == NULL) return 0; spin_lock_irqsave(&edge_port->ep_lock, flags); chars = kfifo_len(&port->write_fifo); spin_unlock_irqrestore(&edge_port->ep_lock, flags); dev_dbg(&port->dev, "%s - returns %d\n", __func__, chars); return chars; } static bool edge_tx_empty(struct usb_serial_port *port) { struct edgeport_port *edge_port = usb_get_serial_port_data(port); int ret; ret = tx_active(edge_port); if (ret > 0) return false; return true; } static void edge_throttle(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status; if (edge_port == NULL) return; /* if we are implementing XON/XOFF, send the stop character */ if (I_IXOFF(tty)) { unsigned char stop_char = STOP_CHAR(tty); status = edge_write(tty, port, &stop_char, 1); if (status <= 0) { dev_err(&port->dev, "%s - failed to write stop character, %d\n", __func__, status); } } /* * if we are implementing RTS/CTS, stop reads * and the Edgeport will clear the RTS line */ if (C_CRTSCTS(tty)) stop_read(edge_port); } static void edge_unthrottle(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status; if (edge_port == NULL) return; /* if we are implementing XON/XOFF, send the start character */ if (I_IXOFF(tty)) { unsigned char start_char = START_CHAR(tty); status = edge_write(tty, port, &start_char, 1); if (status <= 0) { dev_err(&port->dev, "%s - failed to write start character, %d\n", __func__, status); } } /* * if we are implementing RTS/CTS, restart reads * are the Edgeport will assert the RTS line */ if (C_CRTSCTS(tty)) { status = restart_read(edge_port); if (status) dev_err(&port->dev, "%s - read bulk usb_submit_urb failed: %d\n", __func__, status); } } static void stop_read(struct edgeport_port *edge_port) { unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING) edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPING; edge_port->shadow_mcr &= ~MCR_RTS; spin_unlock_irqrestore(&edge_port->ep_lock, flags); } static int restart_read(struct edgeport_port *edge_port) { struct urb *urb; int status = 0; unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPED) { urb = edge_port->port->read_urb; status = usb_submit_urb(urb, GFP_ATOMIC); } edge_port->ep_read_urb_state = EDGE_READ_URB_RUNNING; edge_port->shadow_mcr |= MCR_RTS; spin_unlock_irqrestore(&edge_port->ep_lock, flags); return status; } static void change_port_settings(struct tty_struct *tty, struct edgeport_port *edge_port, struct ktermios *old_termios) { struct device *dev = &edge_port->port->dev; struct ump_uart_config *config; int baud; unsigned cflag; int status; int port_number = edge_port->port->port_number; config = kmalloc (sizeof (*config), GFP_KERNEL); if (!config) { tty->termios = *old_termios; return; } cflag = tty->termios.c_cflag; config->wFlags = 0; /* These flags must be set */ config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT; config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR; config->bUartMode = (__u8)(edge_port->bUartMode); switch (cflag & CSIZE) { case CS5: config->bDataBits = UMP_UART_CHAR5BITS; dev_dbg(dev, "%s - data bits = 5\n", __func__); break; case CS6: config->bDataBits = UMP_UART_CHAR6BITS; dev_dbg(dev, "%s - data bits = 6\n", __func__); break; case CS7: config->bDataBits = UMP_UART_CHAR7BITS; dev_dbg(dev, "%s - data bits = 7\n", __func__); break; default: case CS8: config->bDataBits = UMP_UART_CHAR8BITS; dev_dbg(dev, "%s - data bits = 8\n", __func__); break; } if (cflag & PARENB) { if (cflag & PARODD) { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_ODDPARITY; dev_dbg(dev, "%s - parity = odd\n", __func__); } else { config->wFlags |= UMP_MASK_UART_FLAGS_PARITY; config->bParity = UMP_UART_EVENPARITY; dev_dbg(dev, "%s - parity = even\n", __func__); } } else { config->bParity = UMP_UART_NOPARITY; dev_dbg(dev, "%s - parity = none\n", __func__); } if (cflag & CSTOPB) { config->bStopBits = UMP_UART_STOPBIT2; dev_dbg(dev, "%s - stop bits = 2\n", __func__); } else { config->bStopBits = UMP_UART_STOPBIT1; dev_dbg(dev, "%s - stop bits = 1\n", __func__); } /* figure out the flow control settings */ if (cflag & CRTSCTS) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW; config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW; dev_dbg(dev, "%s - RTS/CTS is enabled\n", __func__); } else { dev_dbg(dev, "%s - RTS/CTS is disabled\n", __func__); restart_read(edge_port); } /* * if we are implementing XON/XOFF, set the start and stop * character in the device */ config->cXon = START_CHAR(tty); config->cXoff = STOP_CHAR(tty); /* if we are implementing INBOUND XON/XOFF */ if (I_IXOFF(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_IN_X; dev_dbg(dev, "%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - INBOUND XON/XOFF is disabled\n", __func__); /* if we are implementing OUTBOUND XON/XOFF */ if (I_IXON(tty)) { config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X; dev_dbg(dev, "%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x\n", __func__, config->cXon, config->cXoff); } else dev_dbg(dev, "%s - OUTBOUND XON/XOFF is disabled\n", __func__); tty->termios.c_cflag &= ~CMSPAR; /* Round the baud rate */ baud = tty_get_baud_rate(tty); if (!baud) { /* pick a default, any default... */ baud = 9600; } else { /* Avoid a zero divisor. */ baud = min(baud, 461550); tty_encode_baud_rate(tty, baud, baud); } edge_port->baud_rate = baud; config->wBaudRate = (__u16)((461550L + baud/2) / baud); /* FIXME: Recompute actual baud from divisor here */ dev_dbg(dev, "%s - baud rate = %d, wBaudRate = %d\n", __func__, baud, config->wBaudRate); dev_dbg(dev, "wBaudRate: %d\n", (int)(461550L / config->wBaudRate)); dev_dbg(dev, "wFlags: 0x%x\n", config->wFlags); dev_dbg(dev, "bDataBits: %d\n", config->bDataBits); dev_dbg(dev, "bParity: %d\n", config->bParity); dev_dbg(dev, "bStopBits: %d\n", config->bStopBits); dev_dbg(dev, "cXon: %d\n", config->cXon); dev_dbg(dev, "cXoff: %d\n", config->cXoff); dev_dbg(dev, "bUartMode: %d\n", config->bUartMode); /* move the word values into big endian mode */ cpu_to_be16s(&config->wFlags); cpu_to_be16s(&config->wBaudRate); status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG, (__u8)(UMPM_UART1_PORT + port_number), 0, (__u8 *)config, sizeof(*config)); if (status) dev_dbg(dev, "%s - error %d when trying to write config to device\n", __func__, status); kfree(config); } static void edge_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios) { struct edgeport_port *edge_port = usb_get_serial_port_data(port); if (edge_port == NULL) return; /* change the port settings to the new ones specified */ change_port_settings(tty, edge_port, old_termios); } static int edge_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int mcr; unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); mcr = edge_port->shadow_mcr; if (set & TIOCM_RTS) mcr |= MCR_RTS; if (set & TIOCM_DTR) mcr |= MCR_DTR; if (set & TIOCM_LOOP) mcr |= MCR_LOOPBACK; if (clear & TIOCM_RTS) mcr &= ~MCR_RTS; if (clear & TIOCM_DTR) mcr &= ~MCR_DTR; if (clear & TIOCM_LOOP) mcr &= ~MCR_LOOPBACK; edge_port->shadow_mcr = mcr; spin_unlock_irqrestore(&edge_port->ep_lock, flags); restore_mcr(edge_port, mcr); return 0; } static int edge_tiocmget(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int result = 0; unsigned int msr; unsigned int mcr; unsigned long flags; spin_lock_irqsave(&edge_port->ep_lock, flags); msr = edge_port->shadow_msr; mcr = edge_port->shadow_mcr; result = ((mcr & MCR_DTR) ? TIOCM_DTR: 0) /* 0x002 */ | ((mcr & MCR_RTS) ? TIOCM_RTS: 0) /* 0x004 */ | ((msr & EDGEPORT_MSR_CTS) ? TIOCM_CTS: 0) /* 0x020 */ | ((msr & EDGEPORT_MSR_CD) ? TIOCM_CAR: 0) /* 0x040 */ | ((msr & EDGEPORT_MSR_RI) ? TIOCM_RI: 0) /* 0x080 */ | ((msr & EDGEPORT_MSR_DSR) ? TIOCM_DSR: 0); /* 0x100 */ dev_dbg(&port->dev, "%s -- %x\n", __func__, result); spin_unlock_irqrestore(&edge_port->ep_lock, flags); return result; } static int get_serial_info(struct edgeport_port *edge_port, struct serial_struct __user *retinfo) { struct serial_struct tmp; unsigned cwait; cwait = edge_port->port->port.closing_wait; if (cwait != ASYNC_CLOSING_WAIT_NONE) cwait = jiffies_to_msecs(cwait) / 10; memset(&tmp, 0, sizeof(tmp)); tmp.type = PORT_16550A; tmp.line = edge_port->port->minor; tmp.port = edge_port->port->port_number; tmp.irq = 0; tmp.xmit_fifo_size = edge_port->port->bulk_out_size; tmp.baud_base = 9600; tmp.close_delay = 5*HZ; tmp.closing_wait = cwait; if (copy_to_user(retinfo, &tmp, sizeof(*retinfo))) return -EFAULT; return 0; } static int edge_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); switch (cmd) { case TIOCGSERIAL: dev_dbg(&port->dev, "%s - TIOCGSERIAL\n", __func__); return get_serial_info(edge_port, (struct serial_struct __user *) arg); } return -ENOIOCTLCMD; } static void edge_break(struct tty_struct *tty, int break_state) { struct usb_serial_port *port = tty->driver_data; struct edgeport_port *edge_port = usb_get_serial_port_data(port); int status; int bv = 0; /* Off */ if (break_state == -1) bv = 1; /* On */ status = ti_do_config(edge_port, UMPC_SET_CLR_BREAK, bv); if (status) dev_dbg(&port->dev, "%s - error %d sending break set/clear command.\n", __func__, status); } static void edge_heartbeat_schedule(struct edgeport_serial *edge_serial) { if (!edge_serial->use_heartbeat) return; schedule_delayed_work(&edge_serial->heartbeat_work, FW_HEARTBEAT_SECS * HZ); } static void edge_heartbeat_work(struct work_struct *work) { struct edgeport_serial *serial; struct ti_i2c_desc *rom_desc; serial = container_of(work, struct edgeport_serial, heartbeat_work.work); rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL); /* Descriptor address request is enough to reset the firmware timer */ if (!rom_desc || !get_descriptor_addr(serial, I2C_DESC_TYPE_ION, rom_desc)) { dev_err(&serial->serial->interface->dev, "%s - Incomplete heartbeat\n", __func__); } kfree(rom_desc); edge_heartbeat_schedule(serial); } static int edge_calc_num_ports(struct usb_serial *serial, struct usb_serial_endpoints *epds) { struct device *dev = &serial->interface->dev; unsigned char num_ports = serial->type->num_ports; /* Make sure we have the required endpoints when in download mode. */ if (serial->interface->cur_altsetting->desc.bNumEndpoints > 1) { if (epds->num_bulk_in < num_ports || epds->num_bulk_out < num_ports || epds->num_interrupt_in < 1) { dev_err(dev, "required endpoints missing\n"); return -ENODEV; } } return num_ports; } static int edge_startup(struct usb_serial *serial) { struct edgeport_serial *edge_serial; int status; u16 product_id; /* create our private serial structure */ edge_serial = kzalloc(sizeof(struct edgeport_serial), GFP_KERNEL); if (!edge_serial) return -ENOMEM; mutex_init(&edge_serial->es_lock); edge_serial->serial = serial; INIT_DELAYED_WORK(&edge_serial->heartbeat_work, edge_heartbeat_work); usb_set_serial_data(serial, edge_serial); status = download_fw(edge_serial); if (status < 0) { kfree(edge_serial); return status; } if (status > 0) return 1; /* bind but do not register any ports */ product_id = le16_to_cpu( edge_serial->serial->dev->descriptor.idProduct); /* Currently only the EP/416 models require heartbeat support */ if (edge_serial->fw_version > FW_HEARTBEAT_VERSION_CUTOFF) { if (product_id == ION_DEVICE_ID_TI_EDGEPORT_416 || product_id == ION_DEVICE_ID_TI_EDGEPORT_416B) { edge_serial->use_heartbeat = true; } } edge_heartbeat_schedule(edge_serial); return 0; } static void edge_disconnect(struct usb_serial *serial) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); cancel_delayed_work_sync(&edge_serial->heartbeat_work); } static void edge_release(struct usb_serial *serial) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); cancel_delayed_work_sync(&edge_serial->heartbeat_work); kfree(edge_serial); } static int edge_port_probe(struct usb_serial_port *port) { struct edgeport_port *edge_port; int ret; edge_port = kzalloc(sizeof(*edge_port), GFP_KERNEL); if (!edge_port) return -ENOMEM; spin_lock_init(&edge_port->ep_lock); edge_port->port = port; edge_port->edge_serial = usb_get_serial_data(port->serial); edge_port->bUartMode = default_uart_mode; switch (port->port_number) { case 0: edge_port->uart_base = UMPMEM_BASE_UART1; edge_port->dma_address = UMPD_OEDB1_ADDRESS; break; case 1: edge_port->uart_base = UMPMEM_BASE_UART2; edge_port->dma_address = UMPD_OEDB2_ADDRESS; break; default: dev_err(&port->dev, "unknown port number\n"); ret = -ENODEV; goto err; } dev_dbg(&port->dev, "%s - port_number = %d, uart_base = %04x, dma_address = %04x\n", __func__, port->port_number, edge_port->uart_base, edge_port->dma_address); usb_set_serial_port_data(port, edge_port); ret = edge_create_sysfs_attrs(port); if (ret) goto err; port->port.closing_wait = msecs_to_jiffies(closing_wait * 10); port->port.drain_delay = 1; return 0; err: kfree(edge_port); return ret; } static int edge_port_remove(struct usb_serial_port *port) { struct edgeport_port *edge_port; edge_port = usb_get_serial_port_data(port); edge_remove_sysfs_attrs(port); kfree(edge_port); return 0; } /* Sysfs Attributes */ static ssize_t uart_mode_show(struct device *dev, struct device_attribute *attr, char *buf) { struct usb_serial_port *port = to_usb_serial_port(dev); struct edgeport_port *edge_port = usb_get_serial_port_data(port); return sprintf(buf, "%d\n", edge_port->bUartMode); } static ssize_t uart_mode_store(struct device *dev, struct device_attribute *attr, const char *valbuf, size_t count) { struct usb_serial_port *port = to_usb_serial_port(dev); struct edgeport_port *edge_port = usb_get_serial_port_data(port); unsigned int v = simple_strtoul(valbuf, NULL, 0); dev_dbg(dev, "%s: setting uart_mode = %d\n", __func__, v); if (v < 256) edge_port->bUartMode = v; else dev_err(dev, "%s - uart_mode %d is invalid\n", __func__, v); return count; } static DEVICE_ATTR_RW(uart_mode); static int edge_create_sysfs_attrs(struct usb_serial_port *port) { return device_create_file(&port->dev, &dev_attr_uart_mode); } static int edge_remove_sysfs_attrs(struct usb_serial_port *port) { device_remove_file(&port->dev, &dev_attr_uart_mode); return 0; } #ifdef CONFIG_PM static int edge_suspend(struct usb_serial *serial, pm_message_t message) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); cancel_delayed_work_sync(&edge_serial->heartbeat_work); return 0; } static int edge_resume(struct usb_serial *serial) { struct edgeport_serial *edge_serial = usb_get_serial_data(serial); edge_heartbeat_schedule(edge_serial); return 0; } #endif static struct usb_serial_driver edgeport_1port_device = { .driver = { .owner = THIS_MODULE, .name = "edgeport_ti_1", }, .description = "Edgeport TI 1 port adapter", .id_table = edgeport_1port_id_table, .num_ports = 1, .num_bulk_out = 1, .open = edge_open, .close = edge_close, .throttle = edge_throttle, .unthrottle = edge_unthrottle, .attach = edge_startup, .calc_num_ports = edge_calc_num_ports, .disconnect = edge_disconnect, .release = edge_release, .port_probe = edge_port_probe, .port_remove = edge_port_remove, .ioctl = edge_ioctl, .set_termios = edge_set_termios, .tiocmget = edge_tiocmget, .tiocmset = edge_tiocmset, .tiocmiwait = usb_serial_generic_tiocmiwait, .get_icount = usb_serial_generic_get_icount, .write = edge_write, .write_room = edge_write_room, .chars_in_buffer = edge_chars_in_buffer, .tx_empty = edge_tx_empty, .break_ctl = edge_break, .read_int_callback = edge_interrupt_callback, .read_bulk_callback = edge_bulk_in_callback, .write_bulk_callback = edge_bulk_out_callback, #ifdef CONFIG_PM .suspend = edge_suspend, .resume = edge_resume, #endif }; static struct usb_serial_driver edgeport_2port_device = { .driver = { .owner = THIS_MODULE, .name = "edgeport_ti_2", }, .description = "Edgeport TI 2 port adapter", .id_table = edgeport_2port_id_table, .num_ports = 2, .num_bulk_out = 1, .open = edge_open, .close = edge_close, .throttle = edge_throttle, .unthrottle = edge_unthrottle, .attach = edge_startup, .calc_num_ports = edge_calc_num_ports, .disconnect = edge_disconnect, .release = edge_release, .port_probe = edge_port_probe, .port_remove = edge_port_remove, .ioctl = edge_ioctl, .set_termios = edge_set_termios, .tiocmget = edge_tiocmget, .tiocmset = edge_tiocmset, .tiocmiwait = usb_serial_generic_tiocmiwait, .get_icount = usb_serial_generic_get_icount, .write = edge_write, .write_room = edge_write_room, .chars_in_buffer = edge_chars_in_buffer, .tx_empty = edge_tx_empty, .break_ctl = edge_break, .read_int_callback = edge_interrupt_callback, .read_bulk_callback = edge_bulk_in_callback, .write_bulk_callback = edge_bulk_out_callback, #ifdef CONFIG_PM .suspend = edge_suspend, .resume = edge_resume, #endif }; static struct usb_serial_driver * const serial_drivers[] = { &edgeport_1port_device, &edgeport_2port_device, NULL }; module_usb_serial_driver(serial_drivers, id_table_combined); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); MODULE_FIRMWARE("edgeport/down3.bin"); module_param(closing_wait, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(closing_wait, "Maximum wait for data to drain, in .01 secs"); module_param(ignore_cpu_rev, bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(ignore_cpu_rev, "Ignore the cpu revision when connecting to a device"); module_param(default_uart_mode, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(default_uart_mode, "Default uart_mode, 0=RS232, ...");
./CrossVul/dataset_final_sorted/CWE-369/c/good_3035_0
crossvul-cpp_data_bad_257_0
/* * MOV, 3GP, MP4 muxer * Copyright (c) 2003 Thomas Raivio * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org> * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com> * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdint.h> #include <inttypes.h> #include "movenc.h" #include "avformat.h" #include "avio_internal.h" #include "riff.h" #include "avio.h" #include "isom.h" #include "avc.h" #include "libavcodec/ac3_parser_internal.h" #include "libavcodec/dnxhddata.h" #include "libavcodec/flac.h" #include "libavcodec/get_bits.h" #include "libavcodec/internal.h" #include "libavcodec/put_bits.h" #include "libavcodec/vc1_common.h" #include "libavcodec/raw.h" #include "internal.h" #include "libavutil/avstring.h" #include "libavutil/intfloat.h" #include "libavutil/mathematics.h" #include "libavutil/libm.h" #include "libavutil/opt.h" #include "libavutil/dict.h" #include "libavutil/pixdesc.h" #include "libavutil/stereo3d.h" #include "libavutil/timecode.h" #include "libavutil/color_utils.h" #include "hevc.h" #include "rtpenc.h" #include "mov_chan.h" #include "vpcc.h" static const AVOption options[] = { { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 }, { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags), { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "empty_hdlr_name", "write zero-length name string in hdlr atoms within mdia and minf atoms", offsetof(MOVMuxContext, empty_hdlr_name), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { NULL }, }; #define MOV_CLASS(flavor)\ static const AVClass flavor ## _muxer_class = {\ .class_name = #flavor " muxer",\ .item_name = av_default_item_name,\ .option = options,\ .version = LIBAVUTIL_VERSION_INT,\ }; static int get_moov_size(AVFormatContext *s); static int utf8len(const uint8_t *b) { int len = 0; int val; while (*b) { GET_UTF8(val, *b++, return -1;) len++; } return len; } //FIXME support 64 bit variant with wide placeholders static int64_t update_size(AVIOContext *pb, int64_t pos) { int64_t curpos = avio_tell(pb); avio_seek(pb, pos, SEEK_SET); avio_wb32(pb, curpos - pos); /* rewrite size */ avio_seek(pb, curpos, SEEK_SET); return curpos - pos; } static int co64_required(const MOVTrack *track) { if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX) return 1; return 0; } static int is_cover_image(const AVStream *st) { /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS * is encoded as sparse video track */ return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC; } static int rtp_hinting_needed(const AVStream *st) { /* Add hint tracks for each real audio and video stream */ if (is_cover_image(st)) return 0; return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO; } /* Chunk offset atom */ static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track) { int i; int mode64 = co64_required(track); // use 32 bit size variant if possible int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ if (mode64) ffio_wfourcc(pb, "co64"); else ffio_wfourcc(pb, "stco"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->chunkCount); /* entry count */ for (i = 0; i < track->entry; i++) { if (!track->cluster[i].chunkNum) continue; if (mode64 == 1) avio_wb64(pb, track->cluster[i].pos + track->data_offset); else avio_wb32(pb, track->cluster[i].pos + track->data_offset); } return update_size(pb, pos); } /* Sample size atom */ static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track) { int equalChunks = 1; int i, j, entries = 0, tst = -1, oldtst = -1; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsz"); avio_wb32(pb, 0); /* version & flags */ for (i = 0; i < track->entry; i++) { tst = track->cluster[i].size / track->cluster[i].entries; if (oldtst != -1 && tst != oldtst) equalChunks = 0; oldtst = tst; entries += track->cluster[i].entries; } if (equalChunks && track->entry) { int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0; sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0 avio_wb32(pb, sSize); // sample size avio_wb32(pb, entries); // sample count } else { avio_wb32(pb, 0); // sample size avio_wb32(pb, entries); // sample count for (i = 0; i < track->entry; i++) { for (j = 0; j < track->cluster[i].entries; j++) { avio_wb32(pb, track->cluster[i].size / track->cluster[i].entries); } } } return update_size(pb, pos); } /* Sample to chunk atom */ static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track) { int index = 0, oldval = -1, i; int64_t entryPos, curpos; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsc"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->chunkCount); // entry count for (i = 0; i < track->entry; i++) { if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) { avio_wb32(pb, track->cluster[i].chunkNum); // first chunk avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk avio_wb32(pb, 0x1); // sample description index oldval = track->cluster[i].samples_in_chunk; index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sync sample atom */ static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag) { int64_t curpos, entryPos; int i, index = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->entry); // entry count for (i = 0; i < track->entry; i++) { if (track->cluster[i].flags & flag) { avio_wb32(pb, i + 1); index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sample dependency atom */ static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track) { int i; uint8_t leading, dependent, reference, redundancy; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "sdtp"); avio_wb32(pb, 0); // version & flags for (i = 0; i < track->entry; i++) { dependent = MOV_SAMPLE_DEPENDENCY_YES; leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN; if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) { reference = MOV_SAMPLE_DEPENDENCY_NO; } if (track->cluster[i].flags & MOV_SYNC_SAMPLE) { dependent = MOV_SAMPLE_DEPENDENCY_NO; } avio_w8(pb, (leading << 6) | (dependent << 4) | (reference << 2) | redundancy); } return update_size(pb, pos); } static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x11); /* size */ if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr"); else ffio_wfourcc(pb, "damr"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */ avio_w8(pb, 0x00); /* Mode change period (no restriction) */ avio_w8(pb, 0x01); /* Frames per sample */ return 0x11; } static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track) { GetBitContext gbc; PutBitContext pbc; uint8_t buf[3]; int fscod, bsid, bsmod, acmod, lfeon, frmsizecod; if (track->vos_len < 7) return -1; avio_wb32(pb, 11); ffio_wfourcc(pb, "dac3"); init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8); fscod = get_bits(&gbc, 2); frmsizecod = get_bits(&gbc, 6); bsid = get_bits(&gbc, 5); bsmod = get_bits(&gbc, 3); acmod = get_bits(&gbc, 3); if (acmod == 2) { skip_bits(&gbc, 2); // dsurmod } else { if ((acmod & 1) && acmod != 1) skip_bits(&gbc, 2); // cmixlev if (acmod & 4) skip_bits(&gbc, 2); // surmixlev } lfeon = get_bits1(&gbc); init_put_bits(&pbc, buf, sizeof(buf)); put_bits(&pbc, 2, fscod); put_bits(&pbc, 5, bsid); put_bits(&pbc, 3, bsmod); put_bits(&pbc, 3, acmod); put_bits(&pbc, 1, lfeon); put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code put_bits(&pbc, 5, 0); // reserved flush_put_bits(&pbc); avio_write(pb, buf, sizeof(buf)); return 11; } struct eac3_info { AVPacket pkt; uint8_t ec3_done; uint8_t num_blocks; /* Layout of the EC3SpecificBox */ /* maximum bitrate */ uint16_t data_rate; /* number of independent substreams */ uint8_t num_ind_sub; struct { /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */ uint8_t fscod; /* bit stream identification 5 bits */ uint8_t bsid; /* one bit reserved */ /* audio service mixing (not supported yet) 1 bit */ /* bit stream mode 3 bits */ uint8_t bsmod; /* audio coding mode 3 bits */ uint8_t acmod; /* sub woofer on 1 bit */ uint8_t lfeon; /* 3 bits reserved */ /* number of dependent substreams associated with this substream 4 bits */ uint8_t num_dep_sub; /* channel locations of the dependent substream(s), if any, 9 bits */ uint16_t chan_loc; /* if there is no dependent substream, then one bit reserved instead */ } substream[1]; /* TODO: support 8 independent substreams */ }; #if CONFIG_AC3_PARSER static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov->fc, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { //info->num_ind_sub++; avpriv_request_sample(mov->fc, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } else { if (hdr->substreamid != 0) { avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } #endif static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track) { PutBitContext pbc; uint8_t *buf; struct eac3_info *info; int size, i; if (!track->eac3_priv) return AVERROR(EINVAL); info = track->eac3_priv; size = 2 + 4 * (info->num_ind_sub + 1); buf = av_malloc(size); if (!buf) { size = AVERROR(ENOMEM); goto end; } init_put_bits(&pbc, buf, size); put_bits(&pbc, 13, info->data_rate); put_bits(&pbc, 3, info->num_ind_sub); for (i = 0; i <= info->num_ind_sub; i++) { put_bits(&pbc, 2, info->substream[i].fscod); put_bits(&pbc, 5, info->substream[i].bsid); put_bits(&pbc, 1, 0); /* reserved */ put_bits(&pbc, 1, 0); /* asvc */ put_bits(&pbc, 3, info->substream[i].bsmod); put_bits(&pbc, 3, info->substream[i].acmod); put_bits(&pbc, 1, info->substream[i].lfeon); put_bits(&pbc, 5, 0); /* reserved */ put_bits(&pbc, 4, info->substream[i].num_dep_sub); if (!info->substream[i].num_dep_sub) { put_bits(&pbc, 1, 0); /* reserved */ size--; } else { put_bits(&pbc, 9, info->substream[i].chan_loc); } } flush_put_bits(&pbc); avio_wb32(pb, size + 8); ffio_wfourcc(pb, "dec3"); avio_write(pb, buf, size); av_free(buf); end: av_packet_unref(&info->pkt); av_freep(&track->eac3_priv); return size; } /** * This function writes extradata "as is". * Extradata must be formatted like a valid atom (with size and tag). */ static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track) { avio_write(pb, track->par->extradata, track->par->extradata_size); return track->par->extradata_size; } static int mov_write_enda_tag(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 1); /* little endian */ return 10; } static int mov_write_enda_tag_be(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 0); /* big endian */ return 10; } static void put_descr(AVIOContext *pb, int tag, unsigned int size) { int i = 3; avio_w8(pb, tag); for (; i > 0; i--) avio_w8(pb, (size >> (7 * i)) | 0x80); avio_w8(pb, size & 0x7F); } static unsigned compute_avg_bitrate(MOVTrack *track) { uint64_t size = 0; int i; if (!track->track_duration) return 0; for (i = 0; i < track->entry; i++) size += track->cluster[i].size; return size * 8 * track->timescale / track->track_duration; } static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic { AVCPBProperties *props; int64_t pos = avio_tell(pb); int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0; unsigned avg_bitrate; avio_wb32(pb, 0); // size ffio_wfourcc(pb, "esds"); avio_wb32(pb, 0); // Version // ES descriptor put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1); avio_wb16(pb, track->track_id); avio_w8(pb, 0x00); // flags (= no flags) // DecoderConfig descriptor put_descr(pb, 0x04, 13 + decoder_specific_info_len); // Object type indication if ((track->par->codec_id == AV_CODEC_ID_MP2 || track->par->codec_id == AV_CODEC_ID_MP3) && track->par->sample_rate > 24000) avio_w8(pb, 0x6B); // 11172-3 else avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id)); // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio) // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved) if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream) else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_w8(pb, 0x15); // flags (= Audiostream) else avio_w8(pb, 0x11); // flags (= Visualstream) props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB avg_bitrate = compute_avg_bitrate(track); avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window) avio_wb32(pb, avg_bitrate); if (track->vos_len) { // DecoderSpecific info descriptor put_descr(pb, 0x05, track->vos_len); avio_write(pb, track->vos_data, track->vos_len); } // SL descriptor put_descr(pb, 0x06, 1); avio_w8(pb, 0x02); return update_size(pb, pos); } static int mov_pcm_le_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24LE || codec_id == AV_CODEC_ID_PCM_S32LE || codec_id == AV_CODEC_ID_PCM_F32LE || codec_id == AV_CODEC_ID_PCM_F64LE; } static int mov_pcm_be_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24BE || codec_id == AV_CODEC_ID_PCM_S32BE || codec_id == AV_CODEC_ID_PCM_F32BE || codec_id == AV_CODEC_ID_PCM_F64BE; } static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); avio_wl32(pb, track->tag); // store it byteswapped track->par->codec_tag = av_bswap16(track->tag >> 16); if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0) return ret; return update_size(pb, pos); } static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "wfex"); if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0) return ret; return update_size(pb, pos); } static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dfLa"); avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */ if (track->par->extradata_size != FLAC_STREAMINFO_SIZE) return AVERROR_INVALIDDATA; /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */ avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */ avio_wb24(pb, track->par->extradata_size); /* Length */ avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */ return update_size(pb, pos); } static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dOps"); avio_w8(pb, 0); /* Version */ if (track->par->extradata_size < 19) { av_log(pb, AV_LOG_ERROR, "invalid extradata size\n"); return AVERROR_INVALIDDATA; } /* extradata contains an Ogg OpusHead, other than byte-ordering and OpusHead's preceeding magic/version, OpusSpecificBox is currently identical. */ avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */ avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */ avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */ avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */ /* Write the rest of the header out without byte-swapping. */ avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18); return update_size(pb, pos); } static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { uint32_t layout_tag, bitmap; int64_t pos = avio_tell(pb); layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id, track->par->channel_layout, &bitmap); if (!layout_tag) { av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to " "lack of channel information\n"); return 0; } if (track->multichannel_as_mono) return 0; avio_wb32(pb, 0); // Size ffio_wfourcc(pb, "chan"); // Type avio_w8(pb, 0); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, layout_tag); // mChannelLayoutTag avio_wb32(pb, bitmap); // mChannelBitmap avio_wb32(pb, 0); // mNumberChannelDescriptions return update_size(pb, pos); } static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "wave"); if (track->par->codec_id != AV_CODEC_ID_QDM2) { avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "frma"); avio_wl32(pb, track->tag); } if (track->par->codec_id == AV_CODEC_ID_AAC) { /* useless atom needed by mplayer, ipod, not needed by quicktime */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0); mov_write_esds_tag(pb, track); } else if (mov_pcm_le_gt16(track->par->codec_id)) { mov_write_enda_tag(pb); } else if (mov_pcm_be_gt16(track->par->codec_id)) { mov_write_enda_tag_be(pb); } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) { mov_write_amr_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_AC3) { mov_write_ac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_EAC3) { mov_write_eac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_QDM2) { mov_write_extradata_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { mov_write_ms_tag(s, pb, track); } avio_wb32(pb, 8); /* size */ avio_wb32(pb, 0); /* null tag */ return update_size(pb, pos); } static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf) { uint8_t *unescaped; const uint8_t *start, *next, *end = track->vos_data + track->vos_len; int unescaped_size, seq_found = 0; int level = 0, interlace = 0; int packet_seq = track->vc1_info.packet_seq; int packet_entry = track->vc1_info.packet_entry; int slices = track->vc1_info.slices; PutBitContext pbc; if (track->start_dts == AV_NOPTS_VALUE) { /* No packets written yet, vc1_info isn't authoritative yet. */ /* Assume inline sequence and entry headers. */ packet_seq = packet_entry = 1; av_log(NULL, AV_LOG_WARNING, "moov atom written before any packets, unable to write correct " "dvc1 atom. Set the delay_moov flag to fix this.\n"); } unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE); if (!unescaped) return AVERROR(ENOMEM); start = find_next_marker(track->vos_data, end); for (next = start; next < end; start = next) { GetBitContext gb; int size; next = find_next_marker(start + 4, end); size = next - start - 4; if (size <= 0) continue; unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped); init_get_bits(&gb, unescaped, 8 * unescaped_size); if (AV_RB32(start) == VC1_CODE_SEQHDR) { int profile = get_bits(&gb, 2); if (profile != PROFILE_ADVANCED) { av_free(unescaped); return AVERROR(ENOSYS); } seq_found = 1; level = get_bits(&gb, 3); /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag, * width, height */ skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12); skip_bits(&gb, 1); /* broadcast */ interlace = get_bits1(&gb); skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */ } } if (!seq_found) { av_free(unescaped); return AVERROR(ENOSYS); } init_put_bits(&pbc, buf, 7); /* VC1DecSpecStruc */ put_bits(&pbc, 4, 12); /* profile - advanced */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* reserved */ /* VC1AdvDecSpecStruc */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* cbr */ put_bits(&pbc, 6, 0); /* reserved */ put_bits(&pbc, 1, !interlace); /* no interlace */ put_bits(&pbc, 1, !packet_seq); /* no multiple seq */ put_bits(&pbc, 1, !packet_entry); /* no multiple entry */ put_bits(&pbc, 1, !slices); /* no slice code */ put_bits(&pbc, 1, 0); /* no bframe */ put_bits(&pbc, 1, 0); /* reserved */ /* framerate */ if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0) put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den); else put_bits32(&pbc, 0xffffffff); flush_put_bits(&pbc); av_free(unescaped); return 0; } static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track) { uint8_t buf[7] = { 0 }; int ret; if ((ret = mov_write_dvc1_structs(track, buf)) < 0) return ret; avio_wb32(pb, track->vos_len + 8 + sizeof(buf)); ffio_wfourcc(pb, "dvc1"); avio_write(pb, buf, sizeof(buf)); avio_write(pb, track->vos_data, track->vos_len); return 0; } static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, track->vos_len + 8); ffio_wfourcc(pb, "glbl"); avio_write(pb, track->vos_data, track->vos_len); return 8 + track->vos_len; } /** * Compute flags for 'lpcm' tag. * See CoreAudioTypes and AudioStreamBasicDescription at Apple. */ static int mov_get_lpcm_flags(enum AVCodecID codec_id) { switch (codec_id) { case AV_CODEC_ID_PCM_F32BE: case AV_CODEC_ID_PCM_F64BE: return 11; case AV_CODEC_ID_PCM_F32LE: case AV_CODEC_ID_PCM_F64LE: return 9; case AV_CODEC_ID_PCM_U8: return 10; case AV_CODEC_ID_PCM_S16BE: case AV_CODEC_ID_PCM_S24BE: case AV_CODEC_ID_PCM_S32BE: return 14; case AV_CODEC_ID_PCM_S8: case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S24LE: case AV_CODEC_ID_PCM_S32LE: return 12; default: return 0; } } static int get_cluster_duration(MOVTrack *track, int cluster_idx) { int64_t next_dts; if (cluster_idx >= track->entry) return 0; if (cluster_idx + 1 == track->entry) next_dts = track->track_duration + track->start_dts; else next_dts = track->cluster[cluster_idx + 1].dts; next_dts -= track->cluster[cluster_idx].dts; av_assert0(next_dts >= 0); av_assert0(next_dts <= INT_MAX); return next_dts; } static int get_samples_per_packet(MOVTrack *track) { int i, first_duration; // return track->par->frame_size; /* use 1 for raw PCM */ if (!track->audio_vbr) return 1; /* check to see if duration is constant for all clusters */ if (!track->entry) return 0; first_duration = get_cluster_duration(track, 0); for (i = 1; i < track->entry; i++) { if (get_cluster_duration(track, i) != first_duration) return 0; } return first_duration; } static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int version = 0; uint32_t tag = track->tag; if (track->mode == MODE_MOV) { if (track->timescale > UINT16_MAX) { if (mov_get_lpcm_flags(track->par->codec_id)) tag = AV_RL32("lpcm"); version = 2; } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id) || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2) { version = 1; } } avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "enca"); } else { avio_wl32(pb, tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */ /* SoundDescription */ avio_wb16(pb, version); /* Version */ avio_wb16(pb, 0); /* Revision level */ avio_wb32(pb, 0); /* Reserved */ if (version == 2) { avio_wb16(pb, 3); avio_wb16(pb, 16); avio_wb16(pb, 0xfffe); avio_wb16(pb, 0); avio_wb32(pb, 0x00010000); avio_wb32(pb, 72); avio_wb64(pb, av_double2int(track->par->sample_rate)); avio_wb32(pb, track->par->channels); avio_wb32(pb, 0x7F000000); avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id)); avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id)); avio_wb32(pb, track->sample_size); avio_wb32(pb, get_samples_per_packet(track)); } else { if (track->mode == MODE_MOV) { avio_wb16(pb, track->par->channels); if (track->par->codec_id == AV_CODEC_ID_PCM_U8 || track->par->codec_id == AV_CODEC_ID_PCM_S8) avio_wb16(pb, 8); /* bits per sample */ else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726) avio_wb16(pb, track->par->bits_per_coded_sample); else avio_wb16(pb, 16); avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */ } else { /* reserved for mp4/3gp */ if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { avio_wb16(pb, track->par->channels); } else { avio_wb16(pb, 2); } if (track->par->codec_id == AV_CODEC_ID_FLAC) { avio_wb16(pb, track->par->bits_per_raw_sample); } else { avio_wb16(pb, 16); } avio_wb16(pb, 0); } avio_wb16(pb, 0); /* packet size (= 0) */ if (track->par->codec_id == AV_CODEC_ID_OPUS) avio_wb16(pb, 48000); else avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ? track->par->sample_rate : 0); avio_wb16(pb, 0); /* Reserved */ } if (version == 1) { /* SoundDescription V1 extended info */ if (mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id)) avio_wb32(pb, 1); /* must be 1 for uncompressed formats */ else avio_wb32(pb, track->par->frame_size); /* Samples per packet */ avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */ avio_wb32(pb, track->sample_size); /* Bytes per frame */ avio_wb32(pb, 2); /* Bytes per sample */ } if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_AAC || track->par->codec_id == AV_CODEC_ID_AC3 || track->par->codec_id == AV_CODEC_ID_EAC3 || track->par->codec_id == AV_CODEC_ID_AMR_NB || track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2 || (mov_pcm_le_gt16(track->par->codec_id) && version==1) || (mov_pcm_be_gt16(track->par->codec_id) && version==1))) mov_write_wave_tag(s, pb, track); else if (track->tag == MKTAG('m','p','4','a')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) mov_write_amr_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AC3) mov_write_ac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_EAC3) mov_write_eac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_ALAC) mov_write_extradata_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) mov_write_wfex_tag(s, pb, track); else if (track->par->codec_id == AV_CODEC_ID_FLAC) mov_write_dfla_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_OPUS) mov_write_dops_tag(pb, track); else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_chan_tag(s, pb, track); if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } return update_size(pb, pos); } static int mov_write_d263_tag(AVIOContext *pb) { avio_wb32(pb, 0xf); /* size */ ffio_wfourcc(pb, "d263"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ /* FIXME use AVCodecContext level/profile, when encoder will set values */ avio_w8(pb, 0xa); /* level */ avio_w8(pb, 0); /* profile */ return 0xf; } static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "avcC"); ff_isom_write_avcc(pb, track->vos_data, track->vos_len); return update_size(pb, pos); } static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "vpcC"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); /* flags */ ff_isom_write_vpcc(s, pb, track->par); return update_size(pb, pos); } static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "hvcC"); if (track->tag == MKTAG('h','v','c','1')) ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1); else ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0); return update_size(pb, pos); } /* also used by all avid codecs (dv, imx, meridien) and their variants */ static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track) { int i; int interlaced; int cid; int display_width = track->par->width; if (track->vos_data && track->vos_len > 0x29) { if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) { /* looks like a DNxHD bit stream */ interlaced = (track->vos_data[5] & 2); cid = AV_RB32(track->vos_data + 0x28); } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n"); return 0; } } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n"); return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "0001"); if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */ track->par->color_range == AVCOL_RANGE_UNSPECIFIED) { avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */ } else { /* Full range (0-255) */ avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */ } avio_wb32(pb, 0); /* unknown */ if (track->tag == MKTAG('A','V','d','h')) { avio_wb32(pb, 32); ffio_wfourcc(pb, "ADHR"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 0); /* unknown */ return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 120); /* size */ ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); /* dnxhd cid, some id ? */ if ( track->par->sample_aspect_ratio.num > 0 && track->par->sample_aspect_ratio.den > 0) display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den; avio_wb32(pb, display_width); /* values below are based on samples created with quicktime and avid codecs */ if (interlaced) { avio_wb32(pb, track->par->height / 2); avio_wb32(pb, 2); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 4); /* unknown */ } else { avio_wb32(pb, track->par->height); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ if (track->par->height == 1080) avio_wb32(pb, 5); /* unknown */ else avio_wb32(pb, 6); /* unknown */ } /* padding */ for (i = 0; i < 10; i++) avio_wb64(pb, 0); return 0; } static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 12); ffio_wfourcc(pb, "DpxE"); if (track->par->extradata_size >= 12 && !memcmp(&track->par->extradata[4], "DpxE", 4)) { avio_wb32(pb, track->par->extradata[11]); } else { avio_wb32(pb, 1); } return 0; } static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (track->par->width == 720) { /* SD */ if (track->par->height == 480) { /* NTSC */ if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n'); else tag = MKTAG('d','v','c',' '); }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p'); else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p'); else tag = MKTAG('d','v','p','p'); } else if (track->par->height == 720) { /* HD 720 line */ if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q'); else tag = MKTAG('d','v','h','p'); } else if (track->par->height == 1080) { /* HD 1080 line */ if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5'); else tag = MKTAG('d','v','h','6'); } else { av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n"); return 0; } return tag; } static AVRational find_fps(AVFormatContext *s, AVStream *st) { AVRational rate = st->avg_frame_rate; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS rate = av_inv_q(st->codec->time_base); if (av_timecode_check_frame_rate(rate) < 0) { av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n", rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den); rate = st->avg_frame_rate; } FF_ENABLE_DEPRECATION_WARNINGS #endif return rate; } static int defined_frame_rate(AVFormatContext *s, AVStream *st) { AVRational rational_framerate = find_fps(s, st); int rate = 0; if (rational_framerate.den != 0) rate = av_q2d(rational_framerate); return rate; } static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('m', '2', 'v', '1'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','4'); else if (rate == 25) tag = MKTAG('x','d','v','5'); else if (rate == 30) tag = MKTAG('x','d','v','1'); else if (rate == 50) tag = MKTAG('x','d','v','a'); else if (rate == 60) tag = MKTAG('x','d','v','9'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','6'); else if (rate == 25) tag = MKTAG('x','d','v','7'); else if (rate == 30) tag = MKTAG('x','d','v','8'); } else { if (rate == 25) tag = MKTAG('x','d','v','3'); else if (rate == 30) tag = MKTAG('x','d','v','2'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','d'); else if (rate == 25) tag = MKTAG('x','d','v','e'); else if (rate == 30) tag = MKTAG('x','d','v','f'); } else { if (rate == 25) tag = MKTAG('x','d','v','c'); else if (rate == 30) tag = MKTAG('x','d','v','b'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','4'); else if (rate == 25) tag = MKTAG('x','d','5','5'); else if (rate == 30) tag = MKTAG('x','d','5','1'); else if (rate == 50) tag = MKTAG('x','d','5','a'); else if (rate == 60) tag = MKTAG('x','d','5','9'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','d'); else if (rate == 25) tag = MKTAG('x','d','5','e'); else if (rate == 30) tag = MKTAG('x','d','5','f'); } else { if (rate == 25) tag = MKTAG('x','d','5','c'); else if (rate == 30) tag = MKTAG('x','d','5','b'); } } } return tag; } static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P10) { if (track->par->width == 960 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','p'); else if (rate == 25) tag = MKTAG('a','i','5','q'); else if (rate == 30) tag = MKTAG('a','i','5','p'); else if (rate == 50) tag = MKTAG('a','i','5','q'); else if (rate == 60) tag = MKTAG('a','i','5','p'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','3'); else if (rate == 25) tag = MKTAG('a','i','5','2'); else if (rate == 30) tag = MKTAG('a','i','5','3'); } else { if (rate == 50) tag = MKTAG('a','i','5','5'); else if (rate == 60) tag = MKTAG('a','i','5','6'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P10) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','p'); else if (rate == 25) tag = MKTAG('a','i','1','q'); else if (rate == 30) tag = MKTAG('a','i','1','p'); else if (rate == 50) tag = MKTAG('a','i','1','q'); else if (rate == 60) tag = MKTAG('a','i','1','p'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','3'); else if (rate == 25) tag = MKTAG('a','i','1','2'); else if (rate == 30) tag = MKTAG('a','i','1','3'); } else { if (rate == 25) tag = MKTAG('a','i','1','5'); else if (rate == 50) tag = MKTAG('a','i','1','5'); else if (rate == 60) tag = MKTAG('a','i','1','6'); } } else if ( track->par->width == 4096 && track->par->height == 2160 || track->par->width == 3840 && track->par->height == 2160 || track->par->width == 2048 && track->par->height == 1080) { tag = MKTAG('a','i','v','x'); } } return tag; } static const struct { enum AVPixelFormat pix_fmt; uint32_t tag; unsigned bps; } mov_pix_fmt_tags[] = { { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 }, { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 }, { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 }, { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 }, { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 }, { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 }, { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 }, { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 }, { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 }, { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 }, { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 }, { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 }, { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 }, { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 }, { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 }, }; static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = MKTAG('A','V','d','n'); if (track->par->profile != FF_PROFILE_UNKNOWN && track->par->profile != FF_PROFILE_DNXHD) tag = MKTAG('A','V','d','h'); return tag; } static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int i; enum AVPixelFormat pix_fmt; for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) { if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) { tag = mov_pix_fmt_tags[i].tag; track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps; if (track->par->codec_tag == mov_pix_fmt_tags[i].tag) break; } } pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov, track->par->bits_per_coded_sample); if (tag == MKTAG('r','a','w',' ') && track->par->format != pix_fmt && track->par->format != AV_PIX_FMT_GRAY8 && track->par->format != AV_PIX_FMT_NONE) av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n", av_get_pix_fmt_name(track->par->format)); return tag; } static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL && (track->par->codec_id == AV_CODEC_ID_DVVIDEO || track->par->codec_id == AV_CODEC_ID_RAWVIDEO || track->par->codec_id == AV_CODEC_ID_H263 || track->par->codec_id == AV_CODEC_ID_H264 || track->par->codec_id == AV_CODEC_ID_DNXHD || track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO || av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio if (track->par->codec_id == AV_CODEC_ID_DVVIDEO) tag = mov_get_dv_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) tag = mov_get_rawvideo_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO) tag = mov_get_mpeg2_xdcam_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_H264) tag = mov_get_h264_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_DNXHD) tag = mov_get_dnxhd_codec_tag(s, track); else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id); if (tag) av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, " "the file may be unplayable!\n"); } } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id); if (ms_tag) { tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff)); av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, " "the file may be unplayable!\n"); } } } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id); } return tag; } static const AVCodecTag codec_cover_image_tags[] = { { AV_CODEC_ID_MJPEG, 0xD }, { AV_CODEC_ID_PNG, 0xE }, { AV_CODEC_ID_BMP, 0x1B }, { AV_CODEC_ID_NONE, 0 }, }; static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (is_cover_image(track->st)) return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id); if (track->mode == MODE_MP4 || track->mode == MODE_PSP) tag = track->par->codec_tag; else if (track->mode == MODE_ISM) tag = track->par->codec_tag; else if (track->mode == MODE_IPOD) { if (!av_match_ext(s->url, "m4a") && !av_match_ext(s->url, "m4v") && !av_match_ext(s->url, "m4b")) av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v " "Quicktime/Ipod might not play the file\n"); tag = track->par->codec_tag; } else if (track->mode & MODE_3GP) tag = track->par->codec_tag; else if (track->mode == MODE_F4V) tag = track->par->codec_tag; else tag = mov_get_codec_tag(s, track); return tag; } /** Write uuid atom. * Needed to make file play in iPods running newest firmware * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1 */ static int mov_write_uuid_tag_ipod(AVIOContext *pb) { avio_wb32(pb, 28); ffio_wfourcc(pb, "uuid"); avio_wb32(pb, 0x6b6840f2); avio_wb32(pb, 0x5f244fc5); avio_wb32(pb, 0xba39a51b); avio_wb32(pb, 0xcf0323f3); avio_wb32(pb, 0x0); return 28; } static const uint16_t fiel_data[] = { 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e }; static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order) { unsigned mov_field_order = 0; if (field_order < FF_ARRAY_ELEMS(fiel_data)) mov_field_order = fiel_data[field_order]; else return 0; avio_wb32(pb, 10); ffio_wfourcc(pb, "fiel"); avio_wb16(pb, mov_field_order); return 10; } static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wl32(pb, track->tag); // store it byteswapped avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_write_esds_tag(pb, track); else if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); return update_size(pb, pos); } static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d) { int8_t stereo_mode; if (stereo_3d->flags != 0) { av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags); return 0; } switch (stereo_3d->type) { case AV_STEREO3D_2D: stereo_mode = 0; break; case AV_STEREO3D_TOPBOTTOM: stereo_mode = 1; break; case AV_STEREO3D_SIDEBYSIDE: stereo_mode = 2; break; default: av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type)); return 0; } avio_wb32(pb, 13); /* size */ ffio_wfourcc(pb, "st3d"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_w8(pb, stereo_mode); return 13; } static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping) { int64_t sv3d_pos, svhd_pos, proj_pos; const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT; if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR && spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE && spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) { av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection); return 0; } sv3d_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sv3d"); svhd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "svhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_put_str(pb, metadata_source); update_size(pb, svhd_pos); proj_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "proj"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "prhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->yaw); avio_wb32(pb, spherical_mapping->pitch); avio_wb32(pb, spherical_mapping->roll); switch (spherical_mapping->projection) { case AV_SPHERICAL_EQUIRECTANGULAR: case AV_SPHERICAL_EQUIRECTANGULAR_TILE: avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "equi"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->bound_top); avio_wb32(pb, spherical_mapping->bound_bottom); avio_wb32(pb, spherical_mapping->bound_left); avio_wb32(pb, spherical_mapping->bound_right); break; case AV_SPHERICAL_CUBEMAP: avio_wb32(pb, 20); /* size */ ffio_wfourcc(pb, "cbmp"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, 0); /* layout */ avio_wb32(pb, spherical_mapping->padding); /* padding */ break; } update_size(pb, proj_pos); return update_size(pb, sv3d_pos); } static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 40); ffio_wfourcc(pb, "clap"); avio_wb32(pb, track->par->width); /* apertureWidth_N */ avio_wb32(pb, 1); /* apertureWidth_D (= 1) */ avio_wb32(pb, track->height); /* apertureHeight_N */ avio_wb32(pb, 1); /* apertureHeight_D (= 1) */ avio_wb32(pb, 0); /* horizOff_N (= 0) */ avio_wb32(pb, 1); /* horizOff_D (= 1) */ avio_wb32(pb, 0); /* vertOff_N (= 0) */ avio_wb32(pb, 1); /* vertOff_D (= 1) */ return 40; } static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track) { AVRational sar; av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num, track->par->sample_aspect_ratio.den, INT_MAX); avio_wb32(pb, 16); ffio_wfourcc(pb, "pasp"); avio_wb32(pb, sar.num); avio_wb32(pb, sar.den); return 16; } static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma) { uint32_t gama = 0; if (gamma <= 0.0) { gamma = avpriv_get_gamma_from_trc(track->par->color_trc); } av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma); if (gamma > 1e-6) { gama = (uint32_t)lrint((double)(1<<16) * gamma); av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama); av_assert0(track->mode == MODE_MOV); avio_wb32(pb, 12); ffio_wfourcc(pb, "gama"); avio_wb32(pb, gama); return 12; } else { av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n"); } return 0; } static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track) { // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9 // Ref (MP4): ISO/IEC 14496-12:2012 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED && track->par->color_trc == AVCOL_TRC_UNSPECIFIED && track->par->color_space == AVCOL_SPC_UNSPECIFIED) { if ((track->par->width >= 1920 && track->par->height >= 1080) || (track->par->width == 1280 && track->par->height == 720)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n"); track->par->color_primaries = AVCOL_PRI_BT709; } else if (track->par->width == 720 && track->height == 576) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n"); track->par->color_primaries = AVCOL_PRI_BT470BG; } else if (track->par->width == 720 && (track->height == 486 || track->height == 480)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n"); track->par->color_primaries = AVCOL_PRI_SMPTE170M; } else { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n"); } switch (track->par->color_primaries) { case AVCOL_PRI_BT709: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_BT709; break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_BT470BG: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_SMPTE170M; break; } } /* We should only ever be called by MOV or MP4. */ av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4); avio_wb32(pb, 18 + (track->mode == MODE_MP4)); ffio_wfourcc(pb, "colr"); if (track->mode == MODE_MP4) ffio_wfourcc(pb, "nclx"); else ffio_wfourcc(pb, "nclc"); switch (track->par->color_primaries) { case AVCOL_PRI_BT709: avio_wb16(pb, 1); break; case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break; case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break; case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break; case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break; default: avio_wb16(pb, 2); } switch (track->par->color_trc) { case AVCOL_TRC_BT709: avio_wb16(pb, 1); break; case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break; case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break; case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break; default: avio_wb16(pb, 2); } switch (track->par->color_space) { case AVCOL_SPC_BT709: avio_wb16(pb, 1); break; case AVCOL_SPC_BT470BG: case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break; case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break; default: avio_wb16(pb, 2); } if (track->mode == MODE_MP4) { int full_range = track->par->color_range == AVCOL_RANGE_JPEG; avio_w8(pb, full_range << 7); return 19; } else { return 18; } } static void find_compressor(char * compressor_name, int len, MOVTrack *track) { AVDictionaryEntry *encoder; int xdcam_res = (track->par->width == 1280 && track->par->height == 720) || (track->par->width == 1440 && track->par->height == 1080) || (track->par->width == 1920 && track->par->height == 1080); if (track->mode == MODE_MOV && (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) { av_strlcpy(compressor_name, encoder->value, 32); } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) { int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(NULL, st); av_strlcatf(compressor_name, len, "XDCAM"); if (track->par->format == AV_PIX_FMT_YUV422P) { av_strlcatf(compressor_name, len, " HD422"); } else if(track->par->width == 1440) { av_strlcatf(compressor_name, len, " HD"); } else av_strlcatf(compressor_name, len, " EX"); av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p'); av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1)); } } static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); char compressor_name[32] = { 0 }; int avid = 0; int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422) || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422) || track->par->codec_id == AV_CODEC_ID_V308 || track->par->codec_id == AV_CODEC_ID_V408 || track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210); avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "encv"); } else { avio_wl32(pb, track->tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (uncompressed_ycbcr) { avio_wb16(pb, 2); /* Codec stream version */ } else { avio_wb16(pb, 0); /* Codec stream version */ } avio_wb16(pb, 0); /* Codec stream revision (=0) */ if (track->mode == MODE_MOV) { ffio_wfourcc(pb, "FFMP"); /* Vendor */ if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) { avio_wb32(pb, 0); /* Temporal Quality */ avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/ } else { avio_wb32(pb, 0x200); /* Temporal Quality = normal */ avio_wb32(pb, 0x200); /* Spatial Quality = normal */ } } else { avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ } avio_wb16(pb, track->par->width); /* Video width */ avio_wb16(pb, track->height); /* Video height */ avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */ avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */ avio_wb32(pb, 0); /* Data size (= 0) */ avio_wb16(pb, 1); /* Frame count (= 1) */ /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */ find_compressor(compressor_name, 32, track); avio_w8(pb, strlen(compressor_name)); avio_write(pb, compressor_name, 31); if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210)) avio_wb16(pb, 0x18); else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample) avio_wb16(pb, track->par->bits_per_coded_sample | (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0)); else avio_wb16(pb, 0x18); /* Reserved */ if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) { int pal_size = 1 << track->par->bits_per_coded_sample; int i; avio_wb16(pb, 0); /* Color table ID */ avio_wb32(pb, 0); /* Color table seed */ avio_wb16(pb, 0x8000); /* Color table flags */ avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */ for (i = 0; i < pal_size; i++) { uint32_t rgb = track->palette[i]; uint16_t r = (rgb >> 16) & 0xff; uint16_t g = (rgb >> 8) & 0xff; uint16_t b = rgb & 0xff; avio_wb16(pb, 0); avio_wb16(pb, (r << 8) | r); avio_wb16(pb, (g << 8) | g); avio_wb16(pb, (b << 8) | b); } } else avio_wb16(pb, 0xffff); /* Reserved */ if (track->tag == MKTAG('m','p','4','v')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H263) mov_write_d263_tag(pb); else if (track->par->codec_id == AV_CODEC_ID_AVUI || track->par->codec_id == AV_CODEC_ID_SVQ3) { mov_write_extradata_tag(pb, track); avio_wb32(pb, 0); } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) { mov_write_avid_tag(pb, track); avid = 1; } else if (track->par->codec_id == AV_CODEC_ID_HEVC) mov_write_hvcc_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) { mov_write_avcc_tag(pb, track); if (track->mode == MODE_IPOD) mov_write_uuid_tag_ipod(pb); } else if (track->par->codec_id == AV_CODEC_ID_VP9) { mov_write_vpcc_tag(mov->fc, pb, track); } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0) mov_write_dvc1_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_VP6F || track->par->codec_id == AV_CODEC_ID_VP6A) { /* Don't write any potential extradata here - the cropping * is signalled via the normal width/height fields. */ } else if (track->par->codec_id == AV_CODEC_ID_R10K) { if (track->par->codec_tag == MKTAG('R','1','0','k')) mov_write_dpxe_tag(pb, track); } else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->par->codec_id != AV_CODEC_ID_H264 && track->par->codec_id != AV_CODEC_ID_MPEG4 && track->par->codec_id != AV_CODEC_ID_DNXHD) { int field_order = track->par->field_order; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN) field_order = track->st->codec->field_order; FF_ENABLE_DEPRECATION_WARNINGS #endif if (field_order != AV_FIELD_UNKNOWN) mov_write_fiel_tag(pb, track, field_order); } if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) { if (track->mode == MODE_MOV) mov_write_gama_tag(pb, track, mov->gamma); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n"); } if (mov->flags & FF_MOV_FLAG_WRITE_COLR) { if (track->mode == MODE_MOV || track->mode == MODE_MP4) mov_write_colr_tag(pb, track); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n"); } if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) { AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL); AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL); if (stereo_3d) mov_write_st3d_tag(pb, stereo_3d); if (spherical_mapping) mov_write_sv3d_tag(mov->fc, pb, spherical_mapping); } if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) { mov_write_pasp_tag(pb, track); } if (uncompressed_ycbcr){ mov_write_clap_tag(pb, track); } if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } /* extra padding for avid stsd */ /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */ if (avid) avio_wb32(pb, 0); return update_size(pb, pos); } static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "rtp "); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb16(pb, 1); /* Hint track version */ avio_wb16(pb, 1); /* Highest compatible version */ avio_wb32(pb, track->max_packet_size); /* Max packet size */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "tims"); avio_wb32(pb, track->timescale); return update_size(pb, pos); } static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name) { uint64_t str_size =strlen(reel_name); int64_t pos = avio_tell(pb); if (str_size >= UINT16_MAX){ av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size); avio_wb16(pb, 0); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "name"); /* Data format */ avio_wb16(pb, str_size); /* string size */ avio_wb16(pb, track->language); /* langcode */ avio_write(pb, reel_name, str_size); /* reel name */ return update_size(pb,pos); } static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); #if 1 int frame_duration; int nb_frames; AVDictionaryEntry *t = NULL; if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) { #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den); nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num); FF_ENABLE_DEPRECATION_WARNINGS #else av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n"); return AVERROR(EINVAL); #endif } else { frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den); nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num); } if (nb_frames > 255) { av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ avio_wb32(pb, 0); /* Flags */ avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */ avio_wb32(pb, track->timescale); /* Timescale */ avio_wb32(pb, frame_duration); /* Frame duration */ avio_w8(pb, nb_frames); /* Number of frames */ avio_w8(pb, 0); /* Reserved */ t = av_dict_get(track->st->metadata, "reel_name", NULL, 0); if (t && utf8len(t->value) && track->mode != MODE_MP4) mov_write_source_reference_tag(pb, track, t->value); else avio_wb16(pb, 0); /* zero size */ #else avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); #endif return update_size(pb, pos); } static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb32(pb, 0); /* Reserved */ return update_size(pb, pos); } static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsd"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_video_tag(pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_audio_tag(s, pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) mov_write_subtitle_tag(pb, track); else if (track->par->codec_tag == MKTAG('r','t','p',' ')) mov_write_rtp_tag(pb, track); else if (track->par->codec_tag == MKTAG('t','m','c','d')) mov_write_tmcd_tag(pb, track); else if (track->par->codec_tag == MKTAG('g','p','m','d')) mov_write_gpmd_tag(pb, track); return update_size(pb, pos); } static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; MOVStts *ctts_entries; uint32_t entries = 0; uint32_t atom_size; int i; ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */ if (!ctts_entries) return AVERROR(ENOMEM); ctts_entries[0].count = 1; ctts_entries[0].duration = track->cluster[0].cts; for (i = 1; i < track->entry; i++) { if (track->cluster[i].cts == ctts_entries[entries].duration) { ctts_entries[entries].count++; /* compress */ } else { entries++; ctts_entries[entries].duration = track->cluster[i].cts; ctts_entries[entries].count = 1; } } entries++; /* last one */ atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "ctts"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, ctts_entries[i].count); avio_wb32(pb, ctts_entries[i].duration); } av_free(ctts_entries); return atom_size; } /* Time to sample atom */ static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track) { MOVStts *stts_entries = NULL; uint32_t entries = -1; uint32_t atom_size; int i; if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) { stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */ if (!stts_entries) return AVERROR(ENOMEM); stts_entries[0].count = track->sample_count; stts_entries[0].duration = 1; entries = 1; } else { if (track->entry) { stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */ if (!stts_entries) return AVERROR(ENOMEM); } for (i = 0; i < track->entry; i++) { int duration = get_cluster_duration(track, i); if (i && duration == stts_entries[entries].duration) { stts_entries[entries].count++; /* compress */ } else { entries++; stts_entries[entries].duration = duration; stts_entries[entries].count = 1; } } entries++; /* last one */ } atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "stts"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, stts_entries[i].count); avio_wb32(pb, stts_entries[i].duration); } av_free(stts_entries); return atom_size; } static int mov_write_dref_tag(AVIOContext *pb) { avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "dref"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ avio_wb32(pb, 0xc); /* size */ //FIXME add the alis and rsrc atom ffio_wfourcc(pb, "url "); avio_wb32(pb, 1); /* version & flags */ return 28; } static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track) { struct sgpd_entry { int count; int16_t roll_distance; int group_description_index; }; struct sgpd_entry *sgpd_entries = NULL; int entries = -1; int group = 0; int i, j; const int OPUS_SEEK_PREROLL_MS = 80; int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS, (AVRational){1, 1000}, (AVRational){1, 48000}); if (!track->entry) return 0; sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries)); if (!sgpd_entries) return AVERROR(ENOMEM); av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC); if (track->par->codec_id == AV_CODEC_ID_OPUS) { for (i = 0; i < track->entry; i++) { int roll_samples_remaining = roll_samples; int distance = 0; for (j = i - 1; j >= 0; j--) { roll_samples_remaining -= get_cluster_duration(track, j); distance++; if (roll_samples_remaining <= 0) break; } /* We don't have enough preceeding samples to compute a valid roll_distance here, so this sample can't be independently decoded. */ if (roll_samples_remaining > 0) distance = 0; /* Verify distance is a minimum of 2 (60ms) packets and a maximum of 32 (2.5ms) packets. */ av_assert0(distance == 0 || (distance >= 2 && distance <= 32)); if (i && distance == sgpd_entries[entries].roll_distance) { sgpd_entries[entries].count++; } else { entries++; sgpd_entries[entries].count = 1; sgpd_entries[entries].roll_distance = distance; sgpd_entries[entries].group_description_index = distance ? ++group : 0; } } } else { entries++; sgpd_entries[entries].count = track->sample_count; sgpd_entries[entries].roll_distance = 1; sgpd_entries[entries].group_description_index = ++group; } entries++; if (!group) { av_free(sgpd_entries); return 0; } /* Write sgpd tag */ avio_wb32(pb, 24 + (group * 2)); /* size */ ffio_wfourcc(pb, "sgpd"); avio_wb32(pb, 1 << 24); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, 2); /* default_length */ avio_wb32(pb, group); /* entry_count */ for (i = 0; i < entries; i++) { if (sgpd_entries[i].group_description_index) { avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */ } } /* Write sbgp tag */ avio_wb32(pb, 20 + (entries * 8)); /* size */ ffio_wfourcc(pb, "sbgp"); avio_wb32(pb, 0); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, entries); /* entry_count */ for (i = 0; i < entries; i++) { avio_wb32(pb, sgpd_entries[i].count); /* sample_count */ avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */ } av_free(sgpd_entries); return 0; } static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stbl"); mov_write_stsd_tag(s, pb, mov, track); mov_write_stts_tag(pb, track); if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_tag == MKTAG('r','t','p',' ')) && track->has_keyframes && track->has_keyframes < track->entry) mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable) mov_write_sdtp_tag(pb, track); if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS) mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->flags & MOV_TRACK_CTTS && track->entry) { if ((ret = mov_write_ctts_tag(s, pb, track)) < 0) return ret; } mov_write_stsc_tag(pb, track); mov_write_stsz_tag(pb, track); mov_write_stco_tag(pb, track); if (track->cenc.aes_ctr) { ff_mov_cenc_write_stbl_atoms(&track->cenc, pb); } if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) { mov_preroll_write_stbl_atoms(pb, track); } return update_size(pb, pos); } static int mov_write_dinf_tag(AVIOContext *pb) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "dinf"); mov_write_dref_tag(pb); return update_size(pb, pos); } static int mov_write_nmhd_tag(AVIOContext *pb) { avio_wb32(pb, 12); ffio_wfourcc(pb, "nmhd"); avio_wb32(pb, 0); return 12; } static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); const char *font = "Lucida Grande"; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* text font */ avio_wb16(pb, 0); /* text face */ avio_wb16(pb, 12); /* text size */ avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */ avio_wb16(pb, 0x0000); /* text color (red) */ avio_wb16(pb, 0x0000); /* text color (green) */ avio_wb16(pb, 0x0000); /* text color (blue) */ avio_wb16(pb, 0xffff); /* background color (red) */ avio_wb16(pb, 0xffff); /* background color (green) */ avio_wb16(pb, 0xffff); /* background color (blue) */ avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */ avio_write(pb, font, strlen(font)); /* font name */ return update_size(pb, pos); } static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gmhd"); avio_wb32(pb, 0x18); /* gmin size */ ffio_wfourcc(pb, "gmin");/* generic media info */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0x40); /* graphics mode = */ avio_wb16(pb, 0x8000); /* opColor (r?) */ avio_wb16(pb, 0x8000); /* opColor (g?) */ avio_wb16(pb, 0x8000); /* opColor (b?) */ avio_wb16(pb, 0); /* balance */ avio_wb16(pb, 0); /* reserved */ /* * This special text atom is required for * Apple Quicktime chapters. The contents * don't appear to be documented, so the * bytes are copied verbatim. */ if (track->tag != MKTAG('c','6','0','8')) { avio_wb32(pb, 0x2C); /* size */ ffio_wfourcc(pb, "text"); avio_wb16(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00004000); avio_wb16(pb, 0x0000); } if (track->par->codec_tag == MKTAG('t','m','c','d')) { int64_t tmcd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); mov_write_tcmi_tag(pb, track); update_size(pb, tmcd_pos); } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { int64_t gpmd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* version */ update_size(pb, gpmd_pos); } return update_size(pb, pos); } static int mov_write_smhd_tag(AVIOContext *pb) { avio_wb32(pb, 16); /* size */ ffio_wfourcc(pb, "smhd"); avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* reserved (balance, normally = 0) */ avio_wb16(pb, 0); /* reserved */ return 16; } static int mov_write_vmhd_tag(AVIOContext *pb) { avio_wb32(pb, 0x14); /* size (always 0x14) */ ffio_wfourcc(pb, "vmhd"); avio_wb32(pb, 0x01); /* version & flags */ avio_wb64(pb, 0); /* reserved (graphics mode = copy) */ return 0x14; } static int is_clcp_track(MOVTrack *track) { return track->tag == MKTAG('c','7','0','8') || track->tag == MKTAG('c','6','0','8'); } static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; const char *hdlr, *descr = NULL, *hdlr_type = NULL; int64_t pos = avio_tell(pb); hdlr = "dhlr"; hdlr_type = "url "; descr = "DataHandler"; if (track) { hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0"; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { hdlr_type = "vide"; descr = "VideoHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { hdlr_type = "soun"; descr = "SoundHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (is_clcp_track(track)) { hdlr_type = "clcp"; descr = "ClosedCaptionHandler"; } else { if (track->tag == MKTAG('t','x','3','g')) { hdlr_type = "sbtl"; } else if (track->tag == MKTAG('m','p','4','s')) { hdlr_type = "subp"; } else { hdlr_type = "text"; } descr = "SubtitleHandler"; } } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) { hdlr_type = "hint"; descr = "HintHandler"; } else if (track->par->codec_tag == MKTAG('t','m','c','d')) { hdlr_type = "tmcd"; descr = "TimeCodeHandler"; } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { hdlr_type = "meta"; descr = "GoPro MET"; // GoPro Metadata } else { av_log(s, AV_LOG_WARNING, "Unknown hldr_type for %s, writing dummy values\n", av_fourcc2str(track->par->codec_tag)); } if (track->st) { // hdlr.name is used by some players to identify the content title // of the track. So if an alternate handler description is // specified, use it. AVDictionaryEntry *t; t = av_dict_get(track->st->metadata, "handler_name", NULL, 0); if (t && utf8len(t->value)) descr = t->value; } } if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */ descr = ""; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); /* Version & flags */ avio_write(pb, hdlr, 4); /* handler */ ffio_wfourcc(pb, hdlr_type); /* handler type */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ if (!track || track->mode == MODE_MOV) avio_w8(pb, strlen(descr)); /* pascal string */ avio_write(pb, descr, strlen(descr)); /* handler description */ if (track && track->mode != MODE_MOV) avio_w8(pb, 0); /* c string */ return update_size(pb, pos); } static int mov_write_hmhd_tag(AVIOContext *pb) { /* This atom must be present, but leaving the values at zero * seems harmless. */ avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "hmhd"); avio_wb32(pb, 0); /* version, flags */ avio_wb16(pb, 0); /* maxPDUsize */ avio_wb16(pb, 0); /* avgPDUsize */ avio_wb32(pb, 0); /* maxbitrate */ avio_wb32(pb, 0); /* avgbitrate */ avio_wb32(pb, 0); /* reserved */ return 28; } static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "minf"); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_vmhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_smhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) { mov_write_gmhd_tag(pb, track); } else { mov_write_nmhd_tag(pb); } } else if (track->tag == MKTAG('r','t','p',' ')) { mov_write_hmhd_tag(pb); } else if (track->tag == MKTAG('t','m','c','d')) { if (track->mode != MODE_MOV) mov_write_nmhd_tag(pb); else mov_write_gmhd_tag(pb, track); } else if (track->tag == MKTAG('g','p','m','d')) { mov_write_gmhd_tag(pb, track); } if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */ mov_write_hdlr_tag(s, pb, NULL); mov_write_dinf_tag(pb); if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int version = track->track_duration < INT32_MAX ? 0 : 1; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, "mdhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */ avio_wb16(pb, track->language); /* language */ avio_wb16(pb, 0); /* reserved (quality) */ if (version != 0 && track->mode == MODE_MOV) { av_log(NULL, AV_LOG_ERROR, "FATAL error, file duration too long for timebase, this file will not be\n" "playable with quicktime. Choose a different timebase or a different\n" "container format\n"); } return 32; } static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "mdia"); mov_write_mdhd_tag(pb, mov, track); mov_write_hdlr_tag(s, pb, track); if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } /* transformation matrix |a b u| |c d v| |tx ty w| */ static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c, int16_t d, int16_t tx, int16_t ty) { avio_wb32(pb, a << 16); /* 16.16 format */ avio_wb32(pb, b << 16); /* 16.16 format */ avio_wb32(pb, 0); /* u in 2.30 format */ avio_wb32(pb, c << 16); /* 16.16 format */ avio_wb32(pb, d << 16); /* 16.16 format */ avio_wb32(pb, 0); /* v in 2.30 format */ avio_wb32(pb, tx << 16); /* 16.16 format */ avio_wb32(pb, ty << 16); /* 16.16 format */ avio_wb32(pb, 1 << 30); /* w in 2.30 format */ } static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int flags = MOV_TKHD_FLAG_IN_MOVIE; int rotation = 0; int group = 0; uint32_t *display_matrix = NULL; int display_matrix_size, i; if (st) { if (mov->per_stream_grouping) group = st->index; else group = st->codecpar->codec_type; display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &display_matrix_size); if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix)) display_matrix = NULL; } if (track->flags & MOV_TRACK_ENABLED) flags |= MOV_TKHD_FLAG_ENABLED; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */ ffio_wfourcc(pb, "tkhd"); avio_w8(pb, version); avio_wb24(pb, flags); if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->track_id); /* track-id */ avio_wb32(pb, 0); /* reserved */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb16(pb, 0); /* layer */ avio_wb16(pb, group); /* alternate group) */ /* Volume, only for audio */ if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_wb16(pb, 0x0100); else avio_wb16(pb, 0); avio_wb16(pb, 0); /* reserved */ /* Matrix structure */ #if FF_API_OLD_ROTATE_API if (st && st->metadata) { AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0); rotation = (rot && rot->value) ? atoi(rot->value) : 0; } #endif if (display_matrix) { for (i = 0; i < 9; i++) avio_wb32(pb, display_matrix[i]); #if FF_API_OLD_ROTATE_API } else if (rotation == 90) { write_matrix(pb, 0, 1, -1, 0, track->par->height, 0); } else if (rotation == 180) { write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height); } else if (rotation == 270) { write_matrix(pb, 0, -1, 1, 0, 0, track->par->width); #endif } else { write_matrix(pb, 1, 0, 0, 1, 0, 0); } /* Track width and height, for visual only */ if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) { int64_t track_width_1616; if (track->mode == MODE_MOV) { track_width_1616 = track->par->width * 0x10000ULL; } else { track_width_1616 = av_rescale(st->sample_aspect_ratio.num, track->par->width * 0x10000LL, st->sample_aspect_ratio.den); if (!track_width_1616 || track->height != track->par->height || track_width_1616 > UINT32_MAX) track_width_1616 = track->par->width * 0x10000ULL; } if (track_width_1616 > UINT32_MAX) { av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n"); track_width_1616 = 0; } avio_wb32(pb, track_width_1616); if (track->height > 0xFFFF) { av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n"); avio_wb32(pb, 0); } else avio_wb32(pb, track->height * 0x10000U); } else { avio_wb32(pb, 0); avio_wb32(pb, 0); } return 0x5c; } static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track) { int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width, track->par->sample_aspect_ratio.den); int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tapt"); avio_wb32(pb, 20); ffio_wfourcc(pb, "clef"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "prof"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "enof"); avio_wb32(pb, 0); avio_wb32(pb, track->par->width << 16); avio_wb32(pb, track->par->height << 16); return update_size(pb, pos); } // This box seems important for the psp playback ... without it the movie seems to hang static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int entry_size, entry_count, size; int64_t delay, start_ct = track->start_cts; int64_t start_dts = track->start_dts; if (track->entry) { if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) { av_log(mov->fc, AV_LOG_DEBUG, "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n", track->cluster[0].dts, track->cluster[0].cts, start_dts, start_ct, track->track_id); start_dts = track->cluster[0].dts; start_ct = track->cluster[0].cts; } } delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN); version |= delay < INT32_MAX ? 0 : 1; entry_size = (version == 1) ? 20 : 12; entry_count = 1 + (delay > 0); size = 24 + entry_count * entry_size; /* write the atom data */ avio_wb32(pb, size); ffio_wfourcc(pb, "edts"); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "elst"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entry_count); if (delay > 0) { /* add an empty edit to delay presentation */ /* In the positive delay case, the delay includes the cts * offset, and the second edit list entry below trims out * the same amount from the actual content. This makes sure * that the offset last sample is included in the edit * list duration as well. */ if (version == 1) { avio_wb64(pb, delay); avio_wb64(pb, -1); } else { avio_wb32(pb, delay); avio_wb32(pb, -1); } avio_wb32(pb, 0x00010000); } else { /* Avoid accidentally ending up with start_ct = -1 which has got a * special meaning. Normally start_ct should end up positive or zero * here, but use FFMIN in case dts is a small positive integer * rounded to 0 when represented in MOV_TIMESCALE units. */ av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0); start_ct = -FFMIN(start_dts, 0); /* Note, this delay is calculated from the pts of the first sample, * ensuring that we don't reduce the duration for cases with * dts<0 pts=0. */ duration += delay; } /* For fragmented files, we don't know the full length yet. Setting * duration to 0 allows us to only specify the offset, including * the rest of the content (from all future fragments) without specifying * an explicit duration. */ if (mov->flags & FF_MOV_FLAG_FRAGMENT) duration = 0; /* duration */ if (version == 1) { avio_wb64(pb, duration); avio_wb64(pb, start_ct); } else { avio_wb32(pb, duration); avio_wb32(pb, start_ct); } avio_wb32(pb, 0x00010000); return size; } static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 20); // size ffio_wfourcc(pb, "tref"); avio_wb32(pb, 12); // size (subatom) avio_wl32(pb, track->tref_tag); avio_wb32(pb, track->tref_id); return 20; } // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it) static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov) { avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x1c); // another size here! ffio_wfourcc(pb, "MTDT"); avio_wb32(pb, 0x00010012); avio_wb32(pb, 0x0a); avio_wb32(pb, 0x55c40000); avio_wb32(pb, 0x1); avio_wb32(pb, 0x0); return 0x34; } static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track) { AVFormatContext *ctx = track->rtp_ctx; char buf[1000] = ""; int len; ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track, NULL, NULL, 0, 0, ctx); av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id); len = strlen(buf); avio_wb32(pb, len + 24); ffio_wfourcc(pb, "udta"); avio_wb32(pb, len + 16); ffio_wfourcc(pb, "hnti"); avio_wb32(pb, len + 8); ffio_wfourcc(pb, "sdp "); avio_write(pb, buf, len); return len + 24; } static int mov_write_track_metadata(AVIOContext *pb, AVStream *st, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */ return update_size(pb, pos); } static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVStream *st) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; if (!st) return 0; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & (MODE_MP4|MODE_MOV)) mov_write_track_metadata(pb_buf, st, "name", "title"); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t pos = avio_tell(pb); int entry_backup = track->entry; int chunk_backup = track->chunkCount; int ret; /* If we want to have an empty moov, but some samples already have been * buffered (delay_moov), pretend that no samples have been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) track->chunkCount = track->entry = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "trak"); mov_write_tkhd_tag(pb, mov, track, st); av_assert2(mov->use_editlist >= 0); if (track->start_dts != AV_NOPTS_VALUE) { if (mov->use_editlist) mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track)) av_log(mov->fc, AV_LOG_WARNING, "Not writing any edit list even though one would have been required\n"); } if (track->tref_tag) mov_write_tref_tag(pb, track); if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0) return ret; if (track->mode == MODE_PSP) mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box if (track->tag == MKTAG('r','t','p',' ')) mov_write_udta_sdp(pb, track); if (track->mode == MODE_MOV) { if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio); if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) { mov_write_tapt_tag(pb, track); } } if (is_clcp_track(track) && st->sample_aspect_ratio.num) { mov_write_tapt_tag(pb, track); } } mov_write_track_udta_tag(pb, mov, st); track->entry = entry_backup; track->chunkCount = chunk_backup; return update_size(pb, pos); } static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov) { int i, has_audio = 0, has_video = 0; int64_t pos = avio_tell(pb); int audio_profile = mov->iods_audio_profile; int video_profile = mov->iods_video_profile; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO; has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO; } } if (audio_profile < 0) audio_profile = 0xFF - has_audio; if (video_profile < 0) video_profile = 0xFF - has_video; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "iods"); avio_wb32(pb, 0); /* version & flags */ put_descr(pb, 0x10, 7); avio_wb16(pb, 0x004f); avio_w8(pb, 0xff); avio_w8(pb, 0xff); avio_w8(pb, audio_profile); avio_w8(pb, video_profile); avio_w8(pb, 0xff); return update_size(pb, pos); } static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x20); /* size */ ffio_wfourcc(pb, "trex"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->track_id); /* track ID */ avio_wb32(pb, 1); /* default sample description index */ avio_wb32(pb, 0); /* default sample duration */ avio_wb32(pb, 0); /* default sample size */ avio_wb32(pb, 0); /* default sample flags */ return 0; } static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "mvex"); for (i = 0; i < mov->nb_streams; i++) mov_write_trex_tag(pb, &mov->tracks[i]); return update_size(pb, pos); } static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov) { int max_track_id = 1, i; int64_t max_track_len = 0; int version; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) { int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration, MOV_TIMESCALE, mov->tracks[i].timescale, AV_ROUND_UP); if (max_track_len < max_track_len_temp) max_track_len = max_track_len_temp; if (max_track_id < mov->tracks[i].track_id) max_track_id = mov->tracks[i].track_id; } } /* If using delay_moov, make sure the output is the same as if no * samples had been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { max_track_len = 0; max_track_id = 1; } version = max_track_len < UINT32_MAX ? 0 : 1; avio_wb32(pb, version == 1 ? 120 : 108); /* size */ ffio_wfourcc(pb, "mvhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, mov->time); avio_wb64(pb, mov->time); } else { avio_wb32(pb, mov->time); /* creation time */ avio_wb32(pb, mov->time); /* modification time */ } avio_wb32(pb, MOV_TIMESCALE); (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */ avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */ avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */ avio_wb16(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ /* Matrix structure */ write_matrix(pb, 1, 0, 0, 1, 0, 0); avio_wb32(pb, 0); /* reserved (preview time) */ avio_wb32(pb, 0); /* reserved (preview duration) */ avio_wb32(pb, 0); /* reserved (poster time) */ avio_wb32(pb, 0); /* reserved (selection time) */ avio_wb32(pb, 0); /* reserved (selection duration) */ avio_wb32(pb, 0); /* reserved (current time) */ avio_wb32(pb, max_track_id + 1); /* Next track id */ return 0x6c; } static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdir"); ffio_wfourcc(pb, "appl"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } /* helper function to write a data tag with the specified string as data */ static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style) { if (long_style) { int size = 16 + strlen(data); avio_wb32(pb, size); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 1); avio_wb32(pb, 0); avio_write(pb, data, strlen(data)); return size; } else { if (!lang) lang = ff_mov_iso639_to_lang("und", 1); avio_wb16(pb, strlen(data)); /* string length */ avio_wb16(pb, lang); avio_write(pb, data, strlen(data)); return strlen(data) + 4; } } static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style) { int size = 0; if (value && value[0]) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, name); mov_write_string_data_tag(pb, value, lang, long_style); size = update_size(pb, pos); } return size; } static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s, const char *tag, int *lang) { int l, len, len2; AVDictionaryEntry *t, *t2 = NULL; char tag2[16]; *lang = 0; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return NULL; len = strlen(t->key); snprintf(tag2, sizeof(tag2), "%s-", tag); while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) { len2 = strlen(t2->key); if (len2 == len + 4 && !strcmp(t->value, t2->value) && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) { *lang = l; return t; } } return t; } static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int long_style) { int lang; AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang); if (!t) return 0; return mov_write_string_tag(pb, name, t->value, lang, long_style); } /* iTunes bpm number */ static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0); int size = 0, tmpo = t ? atoi(t->value) : 0; if (tmpo) { size = 26; avio_wb32(pb, size); ffio_wfourcc(pb, "tmpo"); avio_wb32(pb, size-8); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); //type specifier avio_wb32(pb, 0); avio_wb16(pb, tmpo); // data } return size; } /* 3GPP TS 26.244 */ static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb) { int lang; int64_t pos = avio_tell(pb); double latitude, longitude, altitude; int32_t latitude_fix, longitude_fix, altitude_fix; AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang); const char *ptr, *place = ""; char *end; static const char *astronomical_body = "earth"; if (!t) return 0; ptr = t->value; longitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; latitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; altitude = strtod(ptr, &end); /* If no altitude was present, the default 0 should be fine */ if (*end == '/') place = end + 1; latitude_fix = (int32_t) ((1 << 16) * latitude); longitude_fix = (int32_t) ((1 << 16) * longitude); altitude_fix = (int32_t) ((1 << 16) * altitude); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "loci"); /* type */ avio_wb32(pb, 0); /* version + flags */ avio_wb16(pb, lang); avio_write(pb, place, strlen(place) + 1); avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */ avio_wb32(pb, latitude_fix); avio_wb32(pb, longitude_fix); avio_wb32(pb, altitude_fix); avio_write(pb, astronomical_body, strlen(astronomical_body) + 1); avio_w8(pb, 0); /* additional notes, null terminated string */ return update_size(pb, pos); } /* iTunes track or disc number */ static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s, int disc) { AVDictionaryEntry *t = av_dict_get(s->metadata, disc ? "disc" : "track", NULL, 0); int size = 0, track = t ? atoi(t->value) : 0; if (track) { int tracks = 0; char *slash = strchr(t->value, '/'); if (slash) tracks = atoi(slash + 1); avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, disc ? "disk" : "trkn"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0); // 8 bytes empty avio_wb32(pb, 0); avio_wb16(pb, 0); // empty avio_wb16(pb, track); // track / disc number avio_wb16(pb, tracks); // total track / disc number avio_wb16(pb, 0); // empty size = 32; } return size; } static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int len) { AVDictionaryEntry *t = NULL; uint8_t num; int size = 24 + len; if (len != 1 && len != 4) return -1; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return 0; num = atoi(t->value); avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); avio_wb32(pb, 0); if (len==4) avio_wb32(pb, num); else avio_w8 (pb, num); return size; } static int mov_write_covr(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = 0; int i; for (i = 0; i < s->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (!is_cover_image(trk->st) || trk->cover_image.size <= 0) continue; if (!pos) { pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "covr"); } avio_wb32(pb, 16 + trk->cover_image.size); ffio_wfourcc(pb, "data"); avio_wb32(pb, trk->tag); avio_wb32(pb , 0); avio_write(pb, trk->cover_image.data, trk->cover_image.size); } return pos ? update_size(pb, pos) : 0; } /* iTunes meta data list */ static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); mov_write_string_metadata(s, pb, "\251nam", "title" , 1); mov_write_string_metadata(s, pb, "\251ART", "artist" , 1); mov_write_string_metadata(s, pb, "aART", "album_artist", 1); mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1); mov_write_string_metadata(s, pb, "\251alb", "album" , 1); mov_write_string_metadata(s, pb, "\251day", "date" , 1); if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) { if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1); } mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1); mov_write_string_metadata(s, pb, "\251gen", "genre" , 1); mov_write_string_metadata(s, pb, "cprt", "copyright", 1); mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1); mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1); mov_write_string_metadata(s, pb, "desc", "description",1); mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1); mov_write_string_metadata(s, pb, "tvsh", "show" , 1); mov_write_string_metadata(s, pb, "tven", "episode_id",1); mov_write_string_metadata(s, pb, "tvnn", "network" , 1); mov_write_string_metadata(s, pb, "keyw", "keywords" , 1); mov_write_int8_metadata (s, pb, "tves", "episode_sort",4); mov_write_int8_metadata (s, pb, "tvsn", "season_number",4); mov_write_int8_metadata (s, pb, "stik", "media_type",1); mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1); mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1); mov_write_int8_metadata (s, pb, "cpil", "compilation", 1); mov_write_covr(pb, s); mov_write_trkn_tag(pb, mov, s, 0); // track number mov_write_trkn_tag(pb, mov, s, 1); // disc number mov_write_tmpo_tag(pb, s); return update_size(pb, pos); } static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdta"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int64_t curpos, entry_pos; int count = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "keys"); avio_wb32(pb, 0); entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* entry count */ while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { avio_wb32(pb, strlen(t->key) + 8); ffio_wfourcc(pb, "mdta"); avio_write(pb, t->key, strlen(t->key)); count += 1; } curpos = avio_tell(pb); avio_seek(pb, entry_pos, SEEK_SET); avio_wb32(pb, count); // rewrite entry count avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int count = 1; /* keys are 1-index based */ avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { int64_t entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wb32(pb, count); /* key */ mov_write_string_data_tag(pb, t->value, 0, 1); update_size(pb, entry_pos); count += 1; } return update_size(pb, pos); } /* meta data tags */ static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int size = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "meta"); avio_wb32(pb, 0); if (mov->flags & FF_MOV_FLAG_USE_MDTA) { mov_write_mdta_hdlr_tag(pb, mov, s); mov_write_mdta_keys_tag(pb, mov, s); mov_write_mdta_ilst_tag(pb, mov, s); } else { /* iTunes metadata tag */ mov_write_itunes_hdlr_tag(pb, mov, s); mov_write_ilst_tag(pb, mov, s); } size = update_size(pb, pos); return size; } static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb, const char *name, const char *key) { int len; AVDictionaryEntry *t; if (!(t = av_dict_get(s->metadata, key, NULL, 0))) return 0; len = strlen(t->value); if (len > 0) { int size = len + 8; avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_write(pb, t->value, len); return size; } return 0; } static int ascii_to_wc(AVIOContext *pb, const uint8_t *b) { int val; while (*b) { GET_UTF8(val, *b++, return -1;) avio_wb16(pb, val); } avio_wb16(pb, 0x00); return 0; } static uint16_t language_code(const char *str) { return (((str[0] - 0x60) & 0x1F) << 10) + (((str[1] - 0x60) & 0x1F) << 5) + (( str[2] - 0x60) & 0x1F); } static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_wb32(pb, 0); /* version + flags */ if (!strcmp(tag, "yrrc")) avio_wb16(pb, atoi(t->value)); else { avio_wb16(pb, language_code("eng")); /* language */ avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */ if (!strcmp(tag, "albm") && (t = av_dict_get(s->metadata, "track", NULL, 0))) avio_w8(pb, atoi(t->value)); } return update_size(pb, pos); } static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i, nb_chapters = FFMIN(s->nb_chapters, 255); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "chpl"); avio_wb32(pb, 0x01000000); // version + flags avio_wb32(pb, 0); // unknown avio_w8(pb, nb_chapters); for (i = 0; i < nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000})); if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { int len = FFMIN(strlen(t->value), 255); avio_w8(pb, len); avio_write(pb, t->value, len); } else avio_w8(pb, 0); } return update_size(pb, pos); } static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & MODE_3GP) { mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist"); mov_write_3gp_udta_tag(pb_buf, s, "titl", "title"); mov_write_3gp_udta_tag(pb_buf, s, "auth", "author"); mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre"); mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment"); mov_write_3gp_udta_tag(pb_buf, s, "albm", "album"); mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright"); mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date"); mov_write_loci_tag(s, pb_buf); } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0); mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0); mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0); mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0); mov_write_string_metadata(s, pb_buf, "\251day", "date", 0); mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0); // currently ignored by mov.c mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0); // add support for libquicktime, this atom is also actually read by mov.c mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0); mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0); mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0); mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0); mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0); mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0); mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0); mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp"); } else { /* iTunes meta data */ mov_write_meta_tag(pb_buf, mov, s); mov_write_loci_tag(s, pb_buf); } if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL)) mov_write_chpl_tag(pb_buf, s); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static void mov_write_psp_udta_tag(AVIOContext *pb, const char *str, const char *lang, int type) { int len = utf8len(str) + 1; if (len <= 0) return; avio_wb16(pb, len * 2 + 10); /* size */ avio_wb32(pb, type); /* type */ avio_wb16(pb, language_code(lang)); /* language */ avio_wb16(pb, 0x01); /* ? */ ascii_to_wc(pb, str); } static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0); int64_t pos, pos2; if (title) { pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); pos2 = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "MTDT"); avio_wb16(pb, 4); // ? avio_wb16(pb, 0x0C); /* size */ avio_wb32(pb, 0x0B); /* type */ avio_wb16(pb, language_code("und")); /* language */ avio_wb16(pb, 0x0); /* ? */ avio_wb16(pb, 0x021C); /* data */ if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04); mov_write_psp_udta_tag(pb, title->value, "eng", 0x01); mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03); update_size(pb, pos2); return update_size(pb, pos); } return 0; } static void build_chunks(MOVTrack *trk) { int i; MOVIentry *chunk = &trk->cluster[0]; uint64_t chunkSize = chunk->size; chunk->chunkNum = 1; if (trk->chunkCount) return; trk->chunkCount = 1; for (i = 1; i<trk->entry; i++){ if (chunk->pos + chunkSize == trk->cluster[i].pos && chunkSize + trk->cluster[i].size < (1<<20)){ chunkSize += trk->cluster[i].size; chunk->samples_in_chunk += trk->cluster[i].entries; } else { trk->cluster[i].chunkNum = chunk->chunkNum+1; chunk=&trk->cluster[i]; chunkSize = chunk->size; trk->chunkCount++; } } } /** * Assign track ids. If option "use_stream_ids_as_track_ids" is set, * the stream ids are used as track ids. * * This assumes mov->tracks and s->streams are in the same order and * there are no gaps in either of them (so mov->tracks[n] refers to * s->streams[n]). * * As an exception, there can be more entries in * s->streams than in mov->tracks, in which case new track ids are * generated (starting after the largest found stream id). */ static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s) { int i; if (mov->track_ids_ok) return 0; if (mov->use_stream_ids_as_track_ids) { int next_generated_track_id = 0; for (i = 0; i < s->nb_streams; i++) { if (s->streams[i]->id > next_generated_track_id) next_generated_track_id = s->streams[i]->id; } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id; } } else { for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i + 1; } } mov->track_ids_ok = 1; return 0; } static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int i; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "moov"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].time = mov->time; if (mov->tracks[i].entry) build_chunks(&mov->tracks[i]); } if (mov->chapter_track) for (i = 0; i < s->nb_streams; i++) { mov->tracks[i].tref_tag = MKTAG('c','h','a','p'); mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->tag == MKTAG('r','t','p',' ')) { track->tref_tag = MKTAG('h','i','n','t'); track->tref_id = mov->tracks[track->src_track].track_id; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { int * fallback, size; fallback = (int*)av_stream_get_side_data(track->st, AV_PKT_DATA_FALLBACK_TRACK, &size); if (fallback != NULL && size == sizeof(int)) { if (*fallback >= 0 && *fallback < mov->nb_streams) { track->tref_tag = MKTAG('f','a','l','l'); track->tref_id = mov->tracks[*fallback].track_id; } } } } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('t','m','c','d')) { int src_trk = mov->tracks[i].src_track; mov->tracks[src_trk].tref_tag = mov->tracks[i].tag; mov->tracks[src_trk].tref_id = mov->tracks[i].track_id; //src_trk may have a different timescale than the tmcd track mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration, mov->tracks[i].timescale, mov->tracks[src_trk].timescale); } } mov_write_mvhd_tag(pb, mov); if (mov->mode != MODE_MOV && !mov->iods_skip) mov_write_iods_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL); if (ret < 0) return ret; } } if (mov->flags & FF_MOV_FLAG_FRAGMENT) mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */ if (mov->mode == MODE_PSP) mov_write_uuidusmt_tag(pb, s); else mov_write_udta_tag(pb, mov, s); return update_size(pb, pos); } static void param_write_int(AVIOContext *pb, const char *name, int value) { avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value); } static void param_write_string(AVIOContext *pb, const char *name, const char *value) { avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value); } static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len) { char buf[150]; len = FFMIN(sizeof(buf) / 2 - 1, len); ff_data_to_hex(buf, value, len, 0); buf[2 * len] = '\0'; avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf); } static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i; int64_t manifest_bit_rate = 0; AVCPBProperties *props = NULL; static const uint8_t uuid[] = { 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd, 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }; avio_wb32(pb, 0); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_wb32(pb, 0); avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n"); avio_printf(pb, "<head>\n"); if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT)) avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n", LIBAVFORMAT_IDENT); avio_printf(pb, "</head>\n"); avio_printf(pb, "<body>\n"); avio_printf(pb, "<switch>\n"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; const char *type; int track_id = track->track_id; char track_name_buf[32] = { 0 }; AVStream *st = track->st; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) { type = "video"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { type = "audio"; } else { continue; } props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); if (track->par->bit_rate) { manifest_bit_rate = track->par->bit_rate; } else if (props) { manifest_bit_rate = props->max_bitrate; } avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type, manifest_bit_rate); param_write_int(pb, "systemBitrate", manifest_bit_rate); param_write_int(pb, "trackID", track_id); param_write_string(pb, "systemLanguage", lang ? lang->value : "und"); /* Build track name piece by piece: */ /* 1. track type */ av_strlcat(track_name_buf, type, sizeof(track_name_buf)); /* 2. track language, if available */ if (lang) av_strlcatf(track_name_buf, sizeof(track_name_buf), "_%s", lang->value); /* 3. special type suffix */ /* "_cc" = closed captions, "_ad" = audio_description */ if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf)); else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED) av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf)); param_write_string(pb, "trackName", track_name_buf); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->par->codec_id == AV_CODEC_ID_H264) { uint8_t *ptr; int size = track->par->extradata_size; if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr, &size)) { param_write_hex(pb, "CodecPrivateData", ptr ? ptr : track->par->extradata, size); av_free(ptr); } param_write_string(pb, "FourCC", "H264"); } else if (track->par->codec_id == AV_CODEC_ID_VC1) { param_write_string(pb, "FourCC", "WVC1"); param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); } param_write_int(pb, "MaxWidth", track->par->width); param_write_int(pb, "MaxHeight", track->par->height); param_write_int(pb, "DisplayWidth", track->par->width); param_write_int(pb, "DisplayHeight", track->par->height); } else { if (track->par->codec_id == AV_CODEC_ID_AAC) { switch (track->par->profile) { case FF_PROFILE_AAC_HE_V2: param_write_string(pb, "FourCC", "AACP"); break; case FF_PROFILE_AAC_HE: param_write_string(pb, "FourCC", "AACH"); break; default: param_write_string(pb, "FourCC", "AACL"); } } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) { param_write_string(pb, "FourCC", "WMAP"); } param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id)); param_write_int(pb, "Channels", track->par->channels); param_write_int(pb, "SamplingRate", track->par->sample_rate); param_write_int(pb, "BitsPerSample", 16); param_write_int(pb, "PacketSize", track->par->block_align ? track->par->block_align : 4); } avio_printf(pb, "</%s>\n", type); } avio_printf(pb, "</switch>\n"); avio_printf(pb, "</body>\n"); avio_printf(pb, "</smil>\n"); return update_size(pb, pos); } static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 16); ffio_wfourcc(pb, "mfhd"); avio_wb32(pb, 0); avio_wb32(pb, mov->fragments); return 0; } static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry) { return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO : (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC); } static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET; if (!track->entry) { flags |= MOV_TFHD_DURATION_IS_EMPTY; } else { flags |= MOV_TFHD_DEFAULT_FLAGS; } if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET) flags &= ~MOV_TFHD_BASE_DATA_OFFSET; if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) { flags &= ~MOV_TFHD_BASE_DATA_OFFSET; flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF; } /* Don't set a default sample size, the silverlight player refuses * to play files with that set. Don't set a default sample duration, * WMP freaks out if it is set. Don't set a base data offset, PIFF * file format says it MUST NOT be set. */ if (track->mode == MODE_ISM) flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET); avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfhd"); avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, track->track_id); /* track-id */ if (flags & MOV_TFHD_BASE_DATA_OFFSET) avio_wb64(pb, moof_offset); if (flags & MOV_TFHD_DEFAULT_DURATION) { track->default_duration = get_cluster_duration(track, 0); avio_wb32(pb, track->default_duration); } if (flags & MOV_TFHD_DEFAULT_SIZE) { track->default_size = track->entry ? track->cluster[0].size : 1; avio_wb32(pb, track->default_size); } else track->default_size = -1; if (flags & MOV_TFHD_DEFAULT_FLAGS) { /* Set the default flags based on the second sample, if available. * If the first sample is different, that can be signaled via a separate field. */ if (track->entry > 1) track->default_sample_flags = get_sample_flags(track, &track->cluster[1]); else track->default_sample_flags = track->par->codec_type == AVMEDIA_TYPE_VIDEO ? (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) : MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO; avio_wb32(pb, track->default_sample_flags); } return update_size(pb, pos); } static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int moof_size, int first, int end) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TRUN_DATA_OFFSET; int i; for (i = first; i < end; i++) { if (get_cluster_duration(track, i) != track->default_duration) flags |= MOV_TRUN_SAMPLE_DURATION; if (track->cluster[i].size != track->default_size) flags |= MOV_TRUN_SAMPLE_SIZE; if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags) flags |= MOV_TRUN_SAMPLE_FLAGS; } if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 && get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags) flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS; if (track->flags & MOV_TRACK_CTTS) flags |= MOV_TRUN_SAMPLE_CTS; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "trun"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, end - first); /* sample count */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) && !mov->first_trun) avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */ else avio_wb32(pb, moof_size + 8 + track->data_offset + track->cluster[first].pos); /* data offset */ if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[first])); for (i = first; i < end; i++) { if (flags & MOV_TRUN_SAMPLE_DURATION) avio_wb32(pb, get_cluster_duration(track, i)); if (flags & MOV_TRUN_SAMPLE_SIZE) avio_wb32(pb, track->cluster[i].size); if (flags & MOV_TRUN_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[i])); if (flags & MOV_TRUN_SAMPLE_CTS) avio_wb32(pb, track->cluster[i].cts); } mov->first_trun = 0; return update_size(pb, pos); } static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); static const uint8_t uuid[] = { 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6, 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2 }; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_wb64(pb, track->start_dts + track->frag_start + track->cluster[0].cts); avio_wb64(pb, track->end_pts - (track->cluster[0].dts + track->cluster[0].cts)); return update_size(pb, pos); } static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int entry) { int n = track->nb_frag_info - 1 - entry, i; int size = 8 + 16 + 4 + 1 + 16*n; static const uint8_t uuid[] = { 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95, 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f }; if (entry < 0) return 0; avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET); avio_wb32(pb, size); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_w8(pb, n); for (i = 0; i < n; i++) { int index = entry + 1 + i; avio_wb64(pb, track->frag_info[index].time); avio_wb64(pb, track->frag_info[index].duration); } if (n < mov->ism_lookahead) { int free_size = 16 * (mov->ism_lookahead - n); avio_wb32(pb, free_size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, free_size - 8); } return 0; } static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; for (i = 0; i < mov->ism_lookahead; i++) { /* Update the tfrf tag for the last ism_lookahead fragments, * nb_frag_info - 1 is the next fragment to be written. */ mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i); } avio_seek(pb, pos, SEEK_SET); return 0; } static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks, int size) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; MOVFragmentInfo *info; if ((tracks >= 0 && i != tracks) || !track->entry) continue; track->nb_frag_info++; if (track->nb_frag_info >= track->frag_info_capacity) { unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT; if (av_reallocp_array(&track->frag_info, new_capacity, sizeof(*track->frag_info))) return AVERROR(ENOMEM); track->frag_info_capacity = new_capacity; } info = &track->frag_info[track->nb_frag_info - 1]; info->offset = avio_tell(pb); info->size = size; // Try to recreate the original pts for the first packet // from the fields we have stored info->time = track->start_dts + track->frag_start + track->cluster[0].cts; info->duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); // If the pts is less than zero, we will have trimmed // away parts of the media track using an edit list, // and the corresponding start presentation time is zero. if (info->time < 0) { info->duration += info->time; info->time = 0; } info->tfrf_offset = 0; mov_write_tfrf_tags(pb, mov, track); } return 0; } static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if ((tracks >= 0 && i != tracks) || !track->entry) continue; if (track->nb_frag_info > max) { memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info)); track->nb_frag_info = max; } } } static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tfdt"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb64(pb, track->frag_start); return update_size(pb, pos); } static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset, int moof_size) { int64_t pos = avio_tell(pb); int i, start = 0; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "traf"); mov_write_tfhd_tag(pb, mov, track, moof_offset); if (mov->mode != MODE_ISM) mov_write_tfdt_tag(pb, track); for (i = 1; i < track->entry; i++) { if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) { mov_write_trun_tag(pb, mov, track, moof_size, start, i); start = i; } } mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry); if (mov->mode == MODE_ISM) { mov_write_tfxd_tag(pb, track); if (mov->ism_lookahead) { int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead; if (track->nb_frag_info > 0) { MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1]; if (!info->tfrf_offset) info->tfrf_offset = avio_tell(pb); } avio_wb32(pb, 8 + size); ffio_wfourcc(pb, "free"); for (i = 0; i < size; i++) avio_w8(pb, 0); } } return update_size(pb, pos); } static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov, int tracks, int moof_size) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "moof"); mov->first_trun = 1; mov_write_mfhd_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; if (!track->entry) continue; mov_write_traf_tag(pb, mov, track, pos, moof_size); } return update_size(pb, pos); } static int mov_write_sidx_tag(AVIOContext *pb, MOVTrack *track, int ref_size, int total_sidx_size) { int64_t pos = avio_tell(pb), offset_pos, end_pos; int64_t presentation_time, duration, offset; int starts_with_SAP, i, entries; if (track->entry) { entries = 1; presentation_time = track->start_dts + track->frag_start + track->cluster[0].cts; duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE; // pts<0 should be cut away using edts if (presentation_time < 0) { duration += presentation_time; presentation_time = 0; } } else { entries = track->nb_frag_info; if (entries <= 0) return 0; presentation_time = track->frag_info[0].time; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sidx"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); /* reference_ID */ avio_wb32(pb, track->timescale); /* timescale */ avio_wb64(pb, presentation_time); /* earliest_presentation_time */ offset_pos = avio_tell(pb); avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */ avio_wb16(pb, 0); /* reserved */ avio_wb16(pb, entries); /* reference_count */ for (i = 0; i < entries; i++) { if (!track->entry) { if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) { av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n"); } duration = track->frag_info[i].duration; ref_size = track->frag_info[i].size; starts_with_SAP = 1; } avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */ avio_wb32(pb, duration); /* subsegment_duration */ avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */ } end_pos = avio_tell(pb); offset = pos + total_sidx_size - end_pos; avio_seek(pb, offset_pos, SEEK_SET); avio_wb64(pb, offset); avio_seek(pb, end_pos, SEEK_SET); return update_size(pb, pos); } static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov, int tracks, int ref_size) { int i, round, ret; AVIOContext *avio_buf; int total_size = 0; for (round = 0; round < 2; round++) { // First run one round to calculate the total size of all // sidx atoms. // This would be much simpler if we'd only write one sidx // atom, for the first track in the moof. if (round == 0) { if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; } else { avio_buf = pb; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; // When writing a sidx for the full file, entry is 0, but // we want to include all tracks. ref_size is 0 in this case, // since we read it from frag_info instead. if (!track->entry && ref_size > 0) continue; total_size -= mov_write_sidx_tag(avio_buf, track, ref_size, total_size); } if (round == 0) total_size = ffio_close_null_buf(avio_buf); } return 0; } static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks) { int64_t pos = avio_tell(pb), pts_us, ntp_ts; MOVTrack *first_track; /* PRFT should be associated with at most one track. So, choosing only the * first track. */ if (tracks > 0) return 0; first_track = &(mov->tracks[0]); if (!first_track->entry) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n"); return 0; } if (first_track->cluster[0].pts == AV_NOPTS_VALUE) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n"); return 0; } if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) { ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time()); } else if (mov->write_prft == MOV_PRFT_SRC_PTS) { pts_us = av_rescale_q(first_track->cluster[0].pts, first_track->st->time_base, AV_TIME_BASE_Q); ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US); } else { av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n", mov->write_prft); return 0; } avio_wb32(pb, 0); // Size place holder ffio_wfourcc(pb, "prft"); // Type avio_w8(pb, 1); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, first_track->track_id); // reference track ID avio_wb64(pb, ntp_ts); // NTP time stamp avio_wb64(pb, first_track->cluster[0].pts); //media time return update_size(pb, pos); } static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks, int64_t mdat_size) { AVIOContext *avio_buf; int ret, moof_size; if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; mov_write_moof_tag_internal(avio_buf, mov, tracks, 0); moof_size = ffio_close_null_buf(avio_buf); if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size); if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB) mov_write_prft_tag(pb, mov, tracks); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX || !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) || mov->ism_lookahead) { if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0) return ret; if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) && mov->flags & FF_MOV_FLAG_SKIP_TRAILER) { mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1); } } return mov_write_moof_tag_internal(pb, mov, tracks, moof_size); } static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfra"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); avio_wb32(pb, 0); /* length of traf/trun/sample num */ avio_wb32(pb, track->nb_frag_info); for (i = 0; i < track->nb_frag_info; i++) { avio_wb64(pb, track->frag_info[i].time); avio_wb64(pb, track->frag_info[i].offset + track->data_offset); avio_w8(pb, 1); /* traf number */ avio_w8(pb, 1); /* trun number */ avio_w8(pb, 1); /* sample number */ } return update_size(pb, pos); } static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "mfra"); /* An empty mfra atom is enough to indicate to the publishing point that * the stream has ended. */ if (mov->flags & FF_MOV_FLAG_ISML) return update_size(pb, pos); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->nb_frag_info) mov_write_tfra_tag(pb, track); } avio_wb32(pb, 16); ffio_wfourcc(pb, "mfro"); avio_wb32(pb, 0); /* version + flags */ avio_wb32(pb, avio_tell(pb) + 4 - pos); return update_size(pb, pos); } static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 8); // placeholder for extended size field (64 bit) ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free"); mov->mdat_pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "mdat"); return 0; } /* TODO: This needs to be more general */ static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = avio_tell(pb); int has_h264 = 0, has_video = 0; int minor = 0x200; int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) has_video = 1; if (st->codecpar->codec_id == AV_CODEC_ID_H264) has_h264 = 1; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ftyp"); if (mov->major_brand && strlen(mov->major_brand) >= 4) ffio_wfourcc(pb, mov->major_brand); else if (mov->mode == MODE_3GP) { ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4"); minor = has_h264 ? 0x100 : 0x200; } else if (mov->mode & MODE_3G2) { ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a"); minor = has_h264 ? 0x20000 : 0x10000; } else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) ffio_wfourcc(pb, "iso4"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "isom"); else if (mov->mode == MODE_IPOD) ffio_wfourcc(pb, has_video ? "M4V ":"M4A "); else if (mov->mode == MODE_ISM) ffio_wfourcc(pb, "isml"); else if (mov->mode == MODE_F4V) ffio_wfourcc(pb, "f4v "); else ffio_wfourcc(pb, "qt "); avio_wb32(pb, minor); if (mov->mode == MODE_MOV) ffio_wfourcc(pb, "qt "); else if (mov->mode == MODE_ISM) { ffio_wfourcc(pb, "piff"); } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) { ffio_wfourcc(pb, "isom"); ffio_wfourcc(pb, "iso2"); if (has_h264) ffio_wfourcc(pb, "avc1"); } // We add tfdt atoms when fragmenting, signal this with the iso6 compatible // brand. This is compatible with users that don't understand tfdt. if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM) ffio_wfourcc(pb, "iso6"); if (mov->mode == MODE_3GP) ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4"); else if (mov->mode & MODE_3G2) ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a"); else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "mp41"); if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) ffio_wfourcc(pb, "dash"); return update_size(pb, pos); } static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s) { AVStream *video_st = s->streams[0]; AVCodecParameters *video_par = s->streams[0]->codecpar; AVCodecParameters *audio_par = s->streams[1]->codecpar; int audio_rate = audio_par->sample_rate; int64_t frame_rate = video_st->avg_frame_rate.den ? (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den : 0; int audio_kbitrate = audio_par->bit_rate / 1000; int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate); if (frame_rate < 0 || frame_rate > INT32_MAX) { av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000); return AVERROR(EINVAL); } avio_wb32(pb, 0x94); /* size */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "PROF"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x3); /* 3 sections ? */ avio_wb32(pb, 0x14); /* size */ ffio_wfourcc(pb, "FPRF"); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x2c); /* size */ ffio_wfourcc(pb, "APRF"); /* audio */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x2); /* TrackID */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0x20f); avio_wb32(pb, 0x0); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_rate); avio_wb32(pb, audio_par->channels); avio_wb32(pb, 0x34); /* size */ ffio_wfourcc(pb, "VPRF"); /* video */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x1); /* TrackID */ if (video_par->codec_id == AV_CODEC_ID_H264) { ffio_wfourcc(pb, "avc1"); avio_wb16(pb, 0x014D); avio_wb16(pb, 0x0015); } else { ffio_wfourcc(pb, "mp4v"); avio_wb16(pb, 0x0000); avio_wb16(pb, 0x0103); } avio_wb32(pb, 0x0); avio_wb32(pb, video_kbitrate); avio_wb32(pb, video_kbitrate); avio_wb32(pb, frame_rate); avio_wb32(pb, frame_rate); avio_wb16(pb, video_par->width); avio_wb16(pb, video_par->height); avio_wb32(pb, 0x010001); /* ? */ return 0; } static int mov_write_identification(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; mov_write_ftyp_tag(pb,s); if (mov->mode == MODE_PSP) { int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) video_streams_nb++; else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) audio_streams_nb++; else other_streams_nb++; } if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) { av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n"); return AVERROR(EINVAL); } return mov_write_uuidprof_tag(pb, s); } return 0; } static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags) { uint32_t c = -1; int i, closed_gop = 0; for (i = 0; i < pkt->size - 4; i++) { c = (c << 8) + pkt->data[i]; if (c == 0x1b8) { // gop closed_gop = pkt->data[i + 4] >> 6 & 0x01; } else if (c == 0x100) { // pic int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6); if (!temp_ref || closed_gop) // I picture is not reordered *flags = MOV_SYNC_SAMPLE; else *flags = MOV_PARTIAL_SYNC_SAMPLE; break; } } return 0; } static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk) { const uint8_t *start, *next, *end = pkt->data + pkt->size; int seq = 0, entry = 0; int key = pkt->flags & AV_PKT_FLAG_KEY; start = find_next_marker(pkt->data, end); for (next = start; next < end; start = next) { next = find_next_marker(start + 4, end); switch (AV_RB32(start)) { case VC1_CODE_SEQHDR: seq = 1; break; case VC1_CODE_ENTRYPOINT: entry = 1; break; case VC1_CODE_SLICE: trk->vc1_info.slices = 1; break; } } if (!trk->entry && trk->vc1_info.first_packet_seen) trk->vc1_info.first_frag_written = 1; if (!trk->entry && !trk->vc1_info.first_frag_written) { /* First packet in first fragment */ trk->vc1_info.first_packet_seq = seq; trk->vc1_info.first_packet_entry = entry; trk->vc1_info.first_packet_seen = 1; } else if ((seq && !trk->vc1_info.packet_seq) || (entry && !trk->vc1_info.packet_entry)) { int i; for (i = 0; i < trk->entry; i++) trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE; trk->has_keyframes = 0; if (seq) trk->vc1_info.packet_seq = 1; if (entry) trk->vc1_info.packet_entry = 1; if (!trk->vc1_info.first_frag_written) { /* First fragment */ if ((!seq || trk->vc1_info.first_packet_seq) && (!entry || trk->vc1_info.first_packet_entry)) { /* First packet had the same headers as this one, readd the * sync sample flag. */ trk->cluster[0].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes = 1; } } } if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry) key = seq && entry; else if (trk->vc1_info.packet_seq) key = seq; else if (trk->vc1_info.packet_entry) key = entry; if (key) { trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes++; } } static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; int ret, buf_size; uint8_t *buf; int i, offset; if (!track->mdat_buf) return 0; if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; offset = avio_tell(mov->mdat_buf); avio_write(mov->mdat_buf, buf, buf_size); av_free(buf); for (i = track->entries_flushed; i < track->entry; i++) track->cluster[i].pos += offset; track->entries_flushed = track->entry; return 0; } static int mov_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int i, first_track = -1; int64_t mdat_size = 0; int ret; int has_video = 0, starts_with_key = 0, first_video_track = 1; if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) return 0; // Try to fill in the duration of the last packet in each stream // from queued packets in the interleave queues. If the flushing // of fragments was triggered automatically by an AVPacket, we // already have reliable info for the end of that track, but other // tracks may need to be filled in. for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (!track->end_reliable) { AVPacket pkt; if (!ff_interleaved_peek(s, i, &pkt, 1)) { if (track->dts_shift != AV_NOPTS_VALUE) pkt.dts += track->dts_shift; track->track_duration = pkt.dts - track->start_dts; if (pkt.pts != AV_NOPTS_VALUE) track->end_pts = pkt.pts; else track->end_pts = pkt.dts; } } } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->entry <= 1) continue; // Sample durations are calculated as the diff of dts values, // but for the last sample in a fragment, we don't know the dts // of the first sample in the next fragment, so we have to rely // on what was set as duration in the AVPacket. Not all callers // set this though, so we might want to replace it with an // estimate if it currently is zero. if (get_cluster_duration(track, track->entry - 1) != 0) continue; // Use the duration (i.e. dts diff) of the second last sample for // the last one. This is a wild guess (and fatal if it turns out // to be too long), but probably the best we can do - having a zero // duration is bad as well. track->track_duration += get_cluster_duration(track, track->entry - 2); track->end_pts += get_cluster_duration(track, track->entry - 2); if (!mov->missing_duration_warned) { av_log(s, AV_LOG_WARNING, "Estimating the duration of the last packet in a " "fragment, consider setting the duration field in " "AVPacket instead.\n"); mov->missing_duration_warned = 1; } } if (!mov->moov_written) { int64_t pos = avio_tell(s->pb); uint8_t *buf; int buf_size, moov_size; for (i = 0; i < mov->nb_streams; i++) if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st)) break; /* Don't write the initial moov unless all tracks have data */ if (i < mov->nb_streams && !force) return 0; moov_size = get_moov_size(s); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = pos + moov_size + 8; avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER); if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov_write_identification(s->pb, s); if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) { if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); avio_flush(s->pb); mov->moov_written = 1; return 0; } buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; avio_wb32(s->pb, buf_size + 8); ffio_wfourcc(s->pb, "mdat"); avio_write(s->pb, buf, buf_size); av_free(buf); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); mov->moov_written = 1; mov->mdat_size = 0; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry) mov->tracks[i].frag_start += mov->tracks[i].start_dts + mov->tracks[i].track_duration - mov->tracks[i].cluster[0].dts; mov->tracks[i].entry = 0; mov->tracks[i].end_reliable = 0; } avio_flush(s->pb); return 0; } if (mov->frag_interleave) { for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int ret; if ((ret = mov_flush_fragment_interleaving(s, track)) < 0) return ret; } if (!mov->mdat_buf) return 0; mdat_size = avio_tell(mov->mdat_buf); } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave) track->data_offset = 0; else track->data_offset = mdat_size; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { has_video = 1; if (first_video_track) { if (track->entry) starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE; first_video_track = 0; } } if (!track->entry) continue; if (track->mdat_buf) mdat_size += avio_tell(track->mdat_buf); if (first_track < 0) first_track = i; } if (!mdat_size) return 0; avio_write_marker(s->pb, av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale), (has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int buf_size, write_moof = 1, moof_tracks = -1; uint8_t *buf; int64_t duration = 0; if (track->entry) duration = track->start_dts + track->track_duration - track->cluster[0].dts; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) { if (!track->mdat_buf) continue; mdat_size = avio_tell(track->mdat_buf); moof_tracks = i; } else { write_moof = i == first_track; } if (write_moof) { avio_flush(s->pb); mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size); mov->fragments++; avio_wb32(s->pb, mdat_size + 8); ffio_wfourcc(s->pb, "mdat"); } if (track->entry) track->frag_start += duration; track->entry = 0; track->entries_flushed = 0; track->end_reliable = 0; if (!mov->frag_interleave) { if (!track->mdat_buf) continue; buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; } else { if (!mov->mdat_buf) continue; buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; } avio_write(s->pb, buf, buf_size); av_free(buf); } mov->mdat_size = 0; avio_flush(s->pb); return 0; } static int mov_auto_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int had_moov = mov->moov_written; int ret = mov_flush_fragment(s, force); if (ret < 0) return ret; // If using delay_moov, the first flush only wrote the moov, // not the actual moof+mdat pair, thus flush once again. if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV) ret = mov_flush_fragment(s, force); return ret; } static int check_pkt(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; int64_t ref; uint64_t duration; if (trk->entry) { ref = trk->cluster[trk->entry - 1].dts; } else if ( trk->start_dts != AV_NOPTS_VALUE && !trk->frag_discont) { ref = trk->start_dts + trk->track_duration; } else ref = pkt->dts; // Skip tests for the first packet if (trk->dts_shift != AV_NOPTS_VALUE) { /* With negative CTS offsets we have set an offset to the DTS, * reverse this for the check. */ ref -= trk->dts_shift; } duration = pkt->dts - ref; if (pkt->dts < ref || duration >= INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n", duration, pkt->dts ); pkt->dts = ref + 1; pkt->pts = AV_NOPTS_VALUE; } if (pkt->duration < 0 || pkt->duration > INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration); return AVERROR(EINVAL); } return 0; } int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; unsigned int samples_in_chunk = 0; int size = pkt->size, ret = 0; uint8_t *reformatted_data = NULL; ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret; if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { if (mov->frag_interleave && mov->fragments > 0) { if (trk->entry - trk->entries_flushed >= mov->frag_interleave) { if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0) return ret; } } if (!trk->mdat_buf) { if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0) return ret; } pb = trk->mdat_buf; } else { if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } pb = mov->mdat_buf; } } if (par->codec_id == AV_CODEC_ID_AMR_NB) { /* We must find out how many AMR blocks there are in one packet */ static const uint16_t packed_size[16] = {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1}; int len = 0; while (len < size && samples_in_chunk < 100) { len += packed_size[(pkt->data[len] >> 3) & 0x0F]; samples_in_chunk++; } if (samples_in_chunk > 1) { av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n"); return -1; } } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS || par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { samples_in_chunk = trk->par->frame_size; } else if (trk->sample_size) samples_in_chunk = size / trk->sample_size; else samples_in_chunk = 1; /* copy extradata if it exists */ if (trk->vos_len == 0 && par->extradata_size > 0 && !TAG_IS_AVCI(trk->tag) && (par->codec_id != AV_CODEC_ID_DNXHD)) { trk->vos_len = par->extradata_size; trk->vos_data = av_malloc(trk->vos_len); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, par->extradata, trk->vos_len); } if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return -1; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) { /* from x264 or from bytestream H.264 */ /* NAL reformatting needed */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data, &size); avio_write(pb, reformatted_data, size); } else { if (trk->cenc.aes_ctr) { size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size); if (size < 0) { ret = size; goto err; } } else { size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size); } } } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 && (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) { /* extradata is Annex B, assume the bitstream is too and convert it */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL); avio_write(pb, reformatted_data, size); } else { size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL); } #if CONFIG_AC3_PARSER } else if (par->codec_id == AV_CODEC_ID_EAC3) { size = handle_eac3(mov, pkt, trk); if (size < 0) return size; else if (!size) goto end; avio_write(pb, pkt->data, size); #endif } else { if (trk->cenc.aes_ctr) { if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) { int nal_size_length = (par->extradata[4] & 0x3) + 1; ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size); } else { ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size); } if (ret) { goto err; } } else { avio_write(pb, pkt->data, size); } } if ((par->codec_id == AV_CODEC_ID_DNXHD || par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) { /* copy frame to create needed atoms */ trk->vos_len = size; trk->vos_data = av_malloc(size); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, pkt->data, size); } if (trk->entry >= trk->cluster_capacity) { unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE); if (av_reallocp_array(&trk->cluster, new_capacity, sizeof(*trk->cluster))) { ret = AVERROR(ENOMEM); goto err; } trk->cluster_capacity = new_capacity; } trk->cluster[trk->entry].pos = avio_tell(pb) - size; trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk; trk->cluster[trk->entry].chunkNum = 0; trk->cluster[trk->entry].size = size; trk->cluster[trk->entry].entries = samples_in_chunk; trk->cluster[trk->entry].dts = pkt->dts; trk->cluster[trk->entry].pts = pkt->pts; if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) { if (!trk->frag_discont) { /* First packet of a new fragment. We already wrote the duration * of the last packet of the previous fragment based on track_duration, * which might not exactly match our dts. Therefore adjust the dts * of this packet to be what the previous packets duration implies. */ trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration; /* We also may have written the pts and the corresponding duration * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with * the next fragment. This means the cts of the first sample must * be the same in all fragments, unless end_pts was updated by * the packet causing the fragment to be written. */ if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) || mov->mode == MODE_ISM) pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts; } else { /* New fragment, but discontinuous from previous fragments. * Pretend the duration sum of the earlier fragments is * pkt->dts - trk->start_dts. */ trk->frag_start = pkt->dts - trk->start_dts; trk->end_pts = AV_NOPTS_VALUE; trk->frag_discont = 0; } } if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) { /* Not using edit lists and shifting the first track to start from zero. * If the other streams start from a later timestamp, we won't be able * to signal the difference in starting time without an edit list. * Thus move the timestamp for this first sample to 0, increasing * its duration instead. */ trk->cluster[trk->entry].dts = trk->start_dts = 0; } if (trk->start_dts == AV_NOPTS_VALUE) { trk->start_dts = pkt->dts; if (trk->frag_discont) { if (mov->use_editlist) { /* Pretend the whole stream started at pts=0, with earlier fragments * already written. If the stream started at pts=0, the duration sum * of earlier fragments would have been pkt->pts. */ trk->frag_start = pkt->pts; trk->start_dts = pkt->dts - pkt->pts; } else { /* Pretend the whole stream started at dts=0, with earlier fragments * already written, with a duration summing up to pkt->dts. */ trk->frag_start = pkt->dts; trk->start_dts = 0; } trk->frag_discont = 0; } else if (pkt->dts && mov->moov_written) av_log(s, AV_LOG_WARNING, "Track %d starts with a nonzero dts %"PRId64", while the moov " "already has been written. Set the delay_moov flag to handle " "this case.\n", pkt->stream_index, pkt->dts); } trk->track_duration = pkt->dts - trk->start_dts + pkt->duration; trk->last_sample_is_subtitle_end = 0; if (pkt->pts == AV_NOPTS_VALUE) { av_log(s, AV_LOG_WARNING, "pts has no value\n"); pkt->pts = pkt->dts; } if (pkt->dts != pkt->pts) trk->flags |= MOV_TRACK_CTTS; trk->cluster[trk->entry].cts = pkt->pts - pkt->dts; trk->cluster[trk->entry].flags = 0; if (trk->start_cts == AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; if (trk->end_pts == AV_NOPTS_VALUE) trk->end_pts = trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration; else trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration); if (par->codec_id == AV_CODEC_ID_VC1) { mov_parse_vc1_frame(pkt, trk); } else if (pkt->flags & AV_PKT_FLAG_KEY) { if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO && trk->entry > 0) { // force sync sample for the first key frame mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags); if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE) trk->flags |= MOV_TRACK_STPS; } else { trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE; } if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE) trk->has_keyframes++; } if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) { trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE; trk->has_disposable++; } trk->entry++; trk->sample_count += samples_in_chunk; mov->mdat_size += size; if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry, reformatted_data, size); end: err: av_free(reformatted_data); return ret; } static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; int64_t frag_duration = 0; int size = pkt->size; int ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) { int i; for (i = 0; i < s->nb_streams; i++) mov->tracks[i].frag_discont = 1; mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT; } if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) { if (trk->dts_shift == AV_NOPTS_VALUE) trk->dts_shift = pkt->pts - pkt->dts; pkt->dts += trk->dts_shift; } if (trk->par->codec_id == AV_CODEC_ID_MP4ALS || trk->par->codec_id == AV_CODEC_ID_AAC || trk->par->codec_id == AV_CODEC_ID_FLAC) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!newextra) return AVERROR(ENOMEM); av_free(par->extradata); par->extradata = newextra; memcpy(par->extradata, side, side_size); par->extradata_size = side_size; if (!pkt->size) // Flush packet mov->need_rewrite_extradata = 1; } } if (!pkt->size) { if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) { trk->start_dts = pkt->dts; if (pkt->pts != AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; else trk->start_cts = 0; } return 0; /* Discard 0 sized packets */ } if (trk->entry && pkt->stream_index < s->nb_streams) frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q); if ((mov->max_fragment_duration && frag_duration >= mov->max_fragment_duration) || (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) || (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME && par->codec_type == AVMEDIA_TYPE_VIDEO && trk->entry && pkt->flags & AV_PKT_FLAG_KEY) || (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) { if (frag_duration >= mov->min_fragment_duration) { // Set the duration of this track to line up with the next // sample in this track. This avoids relying on AVPacket // duration, but only helps for this particular track, not // for the other ones that are flushed at the same time. trk->track_duration = pkt->dts - trk->start_dts; if (pkt->pts != AV_NOPTS_VALUE) trk->end_pts = pkt->pts; else trk->end_pts = pkt->dts; trk->end_reliable = 1; mov_auto_flush_fragment(s, 0); } } return ff_mov_write_packet(s, pkt); } static int mov_write_subtitle_end_packet(AVFormatContext *s, int stream_index, int64_t dts) { AVPacket end; uint8_t data[2] = {0}; int ret; av_init_packet(&end); end.size = sizeof(data); end.data = data; end.pts = dts; end.dts = dts; end.duration = 0; end.stream_index = stream_index; ret = mov_write_single_packet(s, &end); av_packet_unref(&end); return ret; } static int mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk; if (!pkt) { mov_flush_fragment(s, 1); return 1; } trk = &mov->tracks[pkt->stream_index]; if (is_cover_image(trk->st)) { int ret; if (trk->st->nb_frames >= 1) { if (trk->st->nb_frames == 1) av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d," " ignoring.\n", pkt->stream_index); return 0; } if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0) return ret; return 0; } else { int i; if (!pkt->size) return mov_write_single_packet(s, pkt); /* Passthrough. */ /* * Subtitles require special handling. * * 1) For full complaince, every track must have a sample at * dts == 0, which is rarely true for subtitles. So, as soon * as we see any packet with dts > 0, write an empty subtitle * at dts == 0 for any subtitle track with no samples in it. * * 2) For each subtitle track, check if the current packet's * dts is past the duration of the last subtitle sample. If * so, we now need to write an end sample for that subtitle. * * This must be done conditionally to allow for subtitles that * immediately replace each other, in which case an end sample * is not needed, and is, in fact, actively harmful. * * 3) See mov_write_trailer for how the final end sample is * handled. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; int ret; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && trk->track_duration < pkt->dts && (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) { ret = mov_write_subtitle_end_packet(s, i, trk->track_duration); if (ret < 0) return ret; trk->last_sample_is_subtitle_end = 1; } } if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) { AVPacket *opkt = pkt; int reshuffle_ret, ret; if (trk->is_unaligned_qt_rgb) { int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16; int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2; reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride); if (reshuffle_ret < 0) return reshuffle_ret; } else reshuffle_ret = 0; if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) { ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette); if (ret < 0) goto fail; if (ret) trk->pal_done++; } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO && (trk->par->format == AV_PIX_FMT_GRAY8 || trk->par->format == AV_PIX_FMT_MONOBLACK)) { for (i = 0; i < pkt->size; i++) pkt->data[i] = ~pkt->data[i]; } if (reshuffle_ret) { ret = mov_write_single_packet(s, pkt); fail: if (reshuffle_ret) av_packet_free(&pkt); return ret; } } return mov_write_single_packet(s, pkt); } } // QuickTime chapters involve an additional text track with the chapter names // as samples, and a tref pointing from the other tracks to the chapter one. static int mov_create_chapter_track(AVFormatContext *s, int tracknum) { AVIOContext *pb; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[tracknum]; AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY }; int i, len; track->mode = mov->mode; track->tag = MKTAG('t','e','x','t'); track->timescale = MOV_TIMESCALE; track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_SUBTITLE; #if 0 // These properties are required to make QT recognize the chapter track uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, }; if (ff_alloc_extradata(track->par, sizeof(chapter_properties))) return AVERROR(ENOMEM); memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties)); #else if (avio_open_dyn_buf(&pb) >= 0) { int size; uint8_t *buf; /* Stub header (usually for Quicktime chapter track) */ // TextSampleEntry avio_wb32(pb, 0x01); // displayFlags avio_w8(pb, 0x00); // horizontal justification avio_w8(pb, 0x00); // vertical justification avio_w8(pb, 0x00); // bgColourRed avio_w8(pb, 0x00); // bgColourGreen avio_w8(pb, 0x00); // bgColourBlue avio_w8(pb, 0x00); // bgColourAlpha // BoxRecord avio_wb16(pb, 0x00); // defTextBoxTop avio_wb16(pb, 0x00); // defTextBoxLeft avio_wb16(pb, 0x00); // defTextBoxBottom avio_wb16(pb, 0x00); // defTextBoxRight // StyleRecord avio_wb16(pb, 0x00); // startChar avio_wb16(pb, 0x00); // endChar avio_wb16(pb, 0x01); // fontID avio_w8(pb, 0x00); // fontStyleFlags avio_w8(pb, 0x00); // fontSize avio_w8(pb, 0x00); // fgColourRed avio_w8(pb, 0x00); // fgColourGreen avio_w8(pb, 0x00); // fgColourBlue avio_w8(pb, 0x00); // fgColourAlpha // FontTableBox avio_wb32(pb, 0x0D); // box size ffio_wfourcc(pb, "ftab"); // box atom name avio_wb16(pb, 0x01); // entry count // FontRecord avio_wb16(pb, 0x01); // font ID avio_w8(pb, 0x00); // font name length if ((size = avio_close_dyn_buf(pb, &buf)) > 0) { track->par->extradata = buf; track->par->extradata_size = size; } else { av_freep(&buf); } } #endif for (i = 0; i < s->nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.duration = end - pkt.dts; if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { static const char encd[12] = { 0x00, 0x00, 0x00, 0x0C, 'e', 'n', 'c', 'd', 0x00, 0x00, 0x01, 0x00 }; len = strlen(t->value); pkt.size = len + 2 + 12; pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB16(pkt.data, len); memcpy(pkt.data + 2, t->value, len); memcpy(pkt.data + len + 2, encd, sizeof(encd)); ff_mov_write_packet(s, &pkt); av_freep(&pkt.data); } } return 0; } static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr) { int ret; /* compute the frame number */ ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s); return ret; } static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc) { int ret; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[index]; AVStream *src_st = s->streams[src_index]; AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4}; AVRational rate = find_fps(s, src_st); /* tmcd track based on video stream */ track->mode = mov->mode; track->tag = MKTAG('t','m','c','d'); track->src_track = src_index; track->timescale = mov->tracks[src_index].timescale; if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME) track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME; /* set st to src_st for metadata access*/ track->st = src_st; /* encode context: tmcd data stream */ track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_DATA; track->par->codec_tag = track->tag; track->st->avg_frame_rate = av_inv_q(rate); /* the tmcd track just contains one packet with the frame number */ pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB32(pkt.data, tc.start); ret = ff_mov_write_packet(s, &pkt); av_free(pkt.data); return ret; } /* * st->disposition controls the "enabled" flag in the tkhd tag. * QuickTime will not play a track if it is not enabled. So make sure * that one track of each type (audio, video, subtitle) is enabled. * * Subtitles are special. For audio and video, setting "enabled" also * makes the track "default" (i.e. it is rendered when played). For * subtitles, an "enabled" subtitle is not rendered by default, but * if no subtitle is enabled, the subtitle menu in QuickTime will be * empty! */ static void enable_tracks(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; int enabled[AVMEDIA_TYPE_NB]; int first[AVMEDIA_TYPE_NB]; for (i = 0; i < AVMEDIA_TYPE_NB; i++) { enabled[i] = 0; first[i] = -1; } for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN || st->codecpar->codec_type >= AVMEDIA_TYPE_NB || is_cover_image(st)) continue; if (first[st->codecpar->codec_type] < 0) first[st->codecpar->codec_type] = i; if (st->disposition & AV_DISPOSITION_DEFAULT) { mov->tracks[i].flags |= MOV_TRACK_ENABLED; enabled[st->codecpar->codec_type]++; } } for (i = 0; i < AVMEDIA_TYPE_NB; i++) { switch (i) { case AVMEDIA_TYPE_VIDEO: case AVMEDIA_TYPE_AUDIO: case AVMEDIA_TYPE_SUBTITLE: if (enabled[i] > 1) mov->per_stream_grouping = 1; if (!enabled[i] && first[i] >= 0) mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED; break; } } } static void mov_free(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; if (mov->chapter_track) { if (mov->tracks[mov->chapter_track].par) av_freep(&mov->tracks[mov->chapter_track].par->extradata); av_freep(&mov->tracks[mov->chapter_track].par); } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) ff_mov_close_hinting(&mov->tracks[i]); else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd) av_freep(&mov->tracks[i].par); av_freep(&mov->tracks[i].cluster); av_freep(&mov->tracks[i].frag_info); av_packet_unref(&mov->tracks[i].cover_image); if (mov->tracks[i].vos_len) av_freep(&mov->tracks[i].vos_data); ff_mov_cenc_free(&mov->tracks[i].cenc); } av_freep(&mov->tracks); } static uint32_t rgb_to_yuv(uint32_t rgb) { uint8_t r, g, b; int y, cb, cr; r = (rgb >> 16) & 0xFF; g = (rgb >> 8) & 0xFF; b = (rgb ) & 0xFF; y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000); cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000); cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000); return (y << 16) | (cr << 8) | cb; } static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track, AVStream *st) { int i, width = 720, height = 480; int have_palette = 0, have_size = 0; uint32_t palette[16]; char *cur = st->codecpar->extradata; while (cur && *cur) { if (strncmp("palette:", cur, 8) == 0) { int i, count; count = sscanf(cur + 8, "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"", &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3], &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7], &palette[ 8], &palette[ 9], &palette[10], &palette[11], &palette[12], &palette[13], &palette[14], &palette[15]); for (i = 0; i < count; i++) { palette[i] = rgb_to_yuv(palette[i]); } have_palette = 1; } else if (!strncmp("size:", cur, 5)) { sscanf(cur + 5, "%dx%d", &width, &height); have_size = 1; } if (have_palette && have_size) break; cur += strcspn(cur, "\n\r"); cur += strspn(cur, "\n\r"); } if (have_palette) { track->vos_data = av_malloc(16*4); if (!track->vos_data) return AVERROR(ENOMEM); for (i = 0; i < 16; i++) { AV_WB32(track->vos_data + i * 4, palette[i]); } track->vos_len = 16 * 4; } st->codecpar->width = width; st->codecpar->height = track->height = height; return 0; } static int mov_init(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret; mov->fc = s; /* Default mode == MP4 */ mov->mode = MODE_MP4; if (s->oformat) { if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP; else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2; else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV; else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP; else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD; else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM; else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V; } if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV; /* Set the FRAGMENT flag if any of the fragmentation methods are * enabled. */ if (mov->max_fragment_duration || mov->max_fragment_size || mov->flags & (FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) mov->flags |= FF_MOV_FLAG_FRAGMENT; /* Set other implicit flags immediately */ if (mov->mode == MODE_ISM) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF | FF_MOV_FLAG_FRAGMENT; if (mov->flags & FF_MOV_FLAG_DASH) mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_DEFAULT_BASE_MOOF; if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) { av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n"); s->flags &= ~AVFMT_FLAG_AUTO_BSF; } if (mov->flags & FF_MOV_FLAG_FASTSTART) { mov->reserved_moov_size = -1; } if (mov->use_editlist < 0) { mov->use_editlist = 1; if (mov->flags & FF_MOV_FLAG_FRAGMENT && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { // If we can avoid needing an edit list by shifting the // tracks, prefer that over (trying to) write edit lists // in fragmented output. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) mov->use_editlist = 0; } } if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist) av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n"); if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO) s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO; /* Clear the omit_tfhd_offset flag if default_base_moof is set; * if the latter is set that's enough and omit_tfhd_offset doesn't * add anything extra on top of that. */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET; if (mov->frag_interleave && mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) { av_log(s, AV_LOG_ERROR, "Sample interleaving in fragments is mutually exclusive with " "omit_tfhd_offset and separate_moof\n"); return AVERROR(EINVAL); } /* Non-seekable output is ok if using fragmentation. If ism_lookahead * is enabled, we don't support non-seekable output at all. */ if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) { av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n"); return AVERROR(EINVAL); } mov->nb_streams = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) mov->chapter_track = mov->nb_streams++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) mov->nb_streams++; } if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4) || mov->write_tmcd == 1) { /* +1 tmcd track for each video stream with a timecode */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; AVDictionaryEntry *t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) { AVTimecode tc; ret = mov_check_timecode_track(s, &tc, i, t->value); if (ret >= 0) mov->nb_meta_tmcd++; } } /* check if there is already a tmcd track to remux */ if (mov->nb_meta_tmcd) { for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) { av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track " "so timecode metadata are now ignored\n"); mov->nb_meta_tmcd = 0; } } } mov->nb_streams += mov->nb_meta_tmcd; } // Reserve an extra stream for chapters for the case where chapters // are written in the trailer mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks)); if (!mov->tracks) return AVERROR(ENOMEM); if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) { if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) { mov->encryption_scheme = MOV_ENC_CENC_AES_CTR; if (mov->encryption_key_len != AES_CTR_KEY_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n", mov->encryption_key_len, AES_CTR_KEY_SIZE); return AVERROR(EINVAL); } if (mov->encryption_kid_len != CENC_KID_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n", mov->encryption_kid_len, CENC_KID_SIZE); return AVERROR(EINVAL); } } else { av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n", mov->encryption_scheme_str); return AVERROR(EINVAL); } } for (i = 0; i < s->nb_streams; i++) { AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); track->st = st; track->par = st->codecpar; track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV); if (track->language < 0) track->language = 0; track->mode = mov->mode; track->tag = mov_find_codec_tag(s, track); if (!track->tag) { av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, " "codec not currently supported in container\n", avcodec_get_name(st->codecpar->codec_id), i); return AVERROR(EINVAL); } /* If hinting of this track is enabled by a later hint track, * this is updated. */ track->hint_track = -1; track->start_dts = AV_NOPTS_VALUE; track->start_cts = AV_NOPTS_VALUE; track->end_pts = AV_NOPTS_VALUE; track->dts_shift = AV_NOPTS_VALUE; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') || track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') || track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) { if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) { av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n"); return AVERROR(EINVAL); } track->height = track->tag >> 24 == 'n' ? 486 : 576; } if (mov->video_track_timescale) { track->timescale = mov->video_track_timescale; } else { track->timescale = st->time_base.den; while(track->timescale < 10000) track->timescale *= 2; } if (st->codecpar->width > 65535 || st->codecpar->height > 65535) { av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height); return AVERROR(EINVAL); } if (track->mode == MODE_MOV && track->timescale > 100000) av_log(s, AV_LOG_WARNING, "WARNING codec timebase is very high. If duration is too long,\n" "file may not be playable by quicktime. Specify a shorter timebase\n" "or choose different container.\n"); if (track->mode == MODE_MOV && track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->tag == MKTAG('r','a','w',' ')) { enum AVPixelFormat pix_fmt = track->par->format; if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1) pix_fmt = AV_PIX_FMT_MONOWHITE; track->is_unaligned_qt_rgb = pix_fmt == AV_PIX_FMT_RGB24 || pix_fmt == AV_PIX_FMT_BGR24 || pix_fmt == AV_PIX_FMT_PAL8 || pix_fmt == AV_PIX_FMT_GRAY8 || pix_fmt == AV_PIX_FMT_MONOWHITE || pix_fmt == AV_PIX_FMT_MONOBLACK; } if (track->par->codec_id == AV_CODEC_ID_VP9) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n"); return AVERROR(EINVAL); } } else if (track->par->codec_id == AV_CODEC_ID_AV1) { /* spec is not finished, so forbid for now */ av_log(s, AV_LOG_ERROR, "AV1 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } else if (track->par->codec_id == AV_CODEC_ID_VP8) { /* altref frames handling is not defined in the spec as of version v1.0, * so just forbid muxing VP8 streams altogether until a new version does */ av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { track->timescale = st->codecpar->sample_rate; if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) { av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i); track->audio_vbr = 1; }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || st->codecpar->codec_id == AV_CODEC_ID_ILBC){ if (!st->codecpar->block_align) { av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i); return AVERROR(EINVAL); } track->sample_size = st->codecpar->block_align; }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */ track->audio_vbr = 1; }else{ track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels; } if (st->codecpar->codec_id == AV_CODEC_ID_ILBC || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) { track->audio_vbr = 1; } if (track->mode != MODE_MOV && track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) { if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) { av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n", i, track->par->sample_rate); return AVERROR(EINVAL); } else { av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n", i, track->par->sample_rate); } } if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id)); return AVERROR(EINVAL); } if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { av_log(s, AV_LOG_ERROR, "%s in MP4 support is experimental, add " "'-strict %d' if you want to use it.\n", avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL); return AVERROR_EXPERIMENTAL; } } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { track->timescale = st->time_base.den; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { track->timescale = st->time_base.den; } else { track->timescale = MOV_TIMESCALE; } if (!track->height) track->height = st->codecpar->height; /* The ism specific timescale isn't mandatory, but is assumed by * some tools, such as mp4split. */ if (mov->mode == MODE_ISM) track->timescale = 10000000; avpriv_set_pts_info(st, 64, 1, track->timescale); if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) { ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key, track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT); if (ret) return ret; } } enable_tracks(s); return 0; } static int mov_write_header(AVFormatContext *s) { AVIOContext *pb = s->pb; MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) nb_tracks++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { hint_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) nb_tracks++; } if (mov->mode == MODE_MOV || mov->mode == MODE_MP4) tmcd_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) { int j; AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; /* copy extradata if it exists */ if (st->codecpar->extradata_size) { if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_create_dvd_sub_decoder_specific_info(track, st); else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) { track->vos_len = st->codecpar->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) { return AVERROR(ENOMEM); } memcpy(track->vos_data, st->codecpar->extradata, track->vos_len); } } if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || track->par->channel_layout != AV_CH_LAYOUT_MONO) continue; for (j = 0; j < s->nb_streams; j++) { AVStream *stj= s->streams[j]; MOVTrack *trackj= &mov->tracks[j]; if (j == i) continue; if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || trackj->par->channel_layout != AV_CH_LAYOUT_MONO || trackj->language != track->language || trackj->tag != track->tag ) continue; track->multichannel_as_mono++; } } if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_identification(pb, s)) < 0) return ret; } if (mov->reserved_moov_size){ mov->reserved_header_pos = avio_tell(pb); if (mov->reserved_moov_size > 0) avio_skip(pb, mov->reserved_moov_size); } if (mov->flags & FF_MOV_FLAG_FRAGMENT) { /* If no fragmentation options have been set, set a default. */ if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) && !mov->max_fragment_duration && !mov->max_fragment_size) mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME; } else { if (mov->flags & FF_MOV_FLAG_FASTSTART) mov->reserved_header_pos = avio_tell(pb); mov_write_mdat_tag(pb, mov); } ff_parse_creation_time_metadata(s, &mov->time, 1); if (mov->time) mov->time += 0x7C25B080; // 1970 based -> 1904 based if (mov->chapter_track) if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) { if (rtp_hinting_needed(s->streams[i])) { if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0) return ret; hint_track++; } } } if (mov->nb_meta_tmcd) { /* Initialize the tmcd tracks */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { AVTimecode tc; if (!t) t = av_dict_get(st->metadata, "timecode", NULL, 0); if (!t) continue; if (mov_check_timecode_track(s, &tc, i, t->value) < 0) continue; if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0) return ret; tmcd_track++; } } } avio_flush(pb); if (mov->flags & FF_MOV_FLAG_ISML) mov_write_isml_manifest(pb, mov, s); if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_moov_tag(pb, mov, s)) < 0) return ret; avio_flush(pb); mov->moov_written = 1; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(pb); } return 0; } static int get_moov_size(AVFormatContext *s) { int ret; AVIOContext *moov_buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&moov_buf)) < 0) return ret; if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0) return ret; return ffio_close_null_buf(moov_buf); } static int get_sidx_size(AVFormatContext *s) { int ret; AVIOContext *buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&buf)) < 0) return ret; mov_write_sidx_tags(buf, mov, -1, 0); return ffio_close_null_buf(buf); } /* * This function gets the moov size if moved to the top of the file: the chunk * offset table can switch between stco (32-bit entries) to co64 (64-bit * entries) when the moov is moved to the beginning, so the size of the moov * would change. It also updates the chunk offset tables. */ static int compute_moov_size(AVFormatContext *s) { int i, moov_size, moov_size2; MOVMuxContext *mov = s->priv_data; moov_size = get_moov_size(s); if (moov_size < 0) return moov_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size; moov_size2 = get_moov_size(s); if (moov_size2 < 0) return moov_size2; /* if the size changed, we just switched from stco to co64 and need to * update the offsets */ if (moov_size2 != moov_size) for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size2 - moov_size; return moov_size2; } static int compute_sidx_size(AVFormatContext *s) { int i, sidx_size; MOVMuxContext *mov = s->priv_data; sidx_size = get_sidx_size(s); if (sidx_size < 0) return sidx_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += sidx_size; return sidx_size; } static int shift_data(AVFormatContext *s) { int ret = 0, moov_size; MOVMuxContext *mov = s->priv_data; int64_t pos, pos_end = avio_tell(s->pb); uint8_t *buf, *read_buf[2]; int read_buf_id = 0; int read_size[2]; AVIOContext *read_pb; if (mov->flags & FF_MOV_FLAG_FRAGMENT) moov_size = compute_sidx_size(s); else moov_size = compute_moov_size(s); if (moov_size < 0) return moov_size; buf = av_malloc(moov_size * 2); if (!buf) return AVERROR(ENOMEM); read_buf[0] = buf; read_buf[1] = buf + moov_size; /* Shift the data: the AVIO context of the output can only be used for * writing, so we re-open the same output, but for reading. It also avoids * a read/seek/write/seek back and forth. */ avio_flush(s->pb); ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL); if (ret < 0) { av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for " "the second pass (faststart)\n", s->url); goto end; } /* mark the end of the shift to up to the last data we wrote, and get ready * for writing */ pos_end = avio_tell(s->pb); avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET); /* start reading at where the new moov will be placed */ avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET); pos = avio_tell(read_pb); #define READ_BLOCK do { \ read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \ read_buf_id ^= 1; \ } while (0) /* shift data by chunk of at most moov_size */ READ_BLOCK; do { int n; READ_BLOCK; n = read_size[read_buf_id]; if (n <= 0) break; avio_write(s->pb, read_buf[read_buf_id], n); pos += n; } while (pos < pos_end); ff_format_io_close(s, &read_pb); end: av_free(buf); return ret; } static int mov_write_trailer(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; int res = 0; int i; int64_t moov_pos; if (mov->need_rewrite_extradata) { for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; AVCodecParameters *par = track->par; track->vos_len = par->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) return AVERROR(ENOMEM); memcpy(track->vos_data, par->extradata, track->vos_len); } mov->need_rewrite_extradata = 0; } /* * Before actually writing the trailer, make sure that there are no * dangling subtitles, that need a terminating sample. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && !trk->last_sample_is_subtitle_end) { mov_write_subtitle_end_packet(s, i, trk->track_duration); trk->last_sample_is_subtitle_end = 1; } } // If there were no chapters when the header was written, but there // are chapters now, write them in the trailer. This only works // when we are not doing fragments. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) { if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) { mov->chapter_track = mov->nb_streams++; if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0) return res; } } if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) { moov_pos = avio_tell(pb); /* Write size of mdat tag */ if (mov->mdat_size + 8 <= UINT32_MAX) { avio_seek(pb, mov->mdat_pos, SEEK_SET); avio_wb32(pb, mov->mdat_size + 8); } else { /* overwrite 'wide' placeholder atom */ avio_seek(pb, mov->mdat_pos - 8, SEEK_SET); /* special value: real atom size will be 64 bit value after * tag field */ avio_wb32(pb, 1); ffio_wfourcc(pb, "mdat"); avio_wb64(pb, mov->mdat_size + 16); } avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET); if (mov->flags & FF_MOV_FLAG_FASTSTART) { av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n"); res = shift_data(s); if (res < 0) return res; avio_seek(pb, mov->reserved_header_pos, SEEK_SET); if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } else if (mov->reserved_moov_size > 0) { int64_t size; if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos); if (size < 8){ av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size); return AVERROR(EINVAL); } avio_wb32(pb, size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, size - 8); avio_seek(pb, moov_pos, SEEK_SET); } else { if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } res = 0; } else { mov_auto_flush_fragment(s, 1); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = 0; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) { int64_t end; av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n"); res = shift_data(s); if (res < 0) return res; end = avio_tell(pb); avio_seek(pb, mov->reserved_header_pos, SEEK_SET); mov_write_sidx_tags(pb, mov, -1, 0); avio_seek(pb, end, SEEK_SET); avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) { avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } } return res; } static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt) { int ret = 1; AVStream *st = s->streams[pkt->stream_index]; if (st->codecpar->codec_id == AV_CODEC_ID_AAC) { if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL); } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) { ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL); } return ret; } static const AVCodecTag codec_3gp_tags[] = { { AV_CODEC_ID_H263, MKTAG('s','2','6','3') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') }, { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_NONE, 0 }, }; const AVCodecTag codec_mp4_tags[] = { { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') }, { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') }, { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') }, { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') }, { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') }, { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') }, { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') }, { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') }, { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') }, { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') }, { AV_CODEC_ID_NONE , 0 }, }; const AVCodecTag codec_ism_tags[] = { { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') }, { AV_CODEC_ID_NONE , 0 }, }; static const AVCodecTag codec_ipod_tags[] = { { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') }, { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') }, { AV_CODEC_ID_NONE, 0 }, }; static const AVCodecTag codec_f4v_tags[] = { { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') }, { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') }, { AV_CODEC_ID_NONE, 0 }, }; #if CONFIG_MOV_MUXER MOV_CLASS(mov) AVOutputFormat ff_mov_muxer = { .name = "mov", .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"), .extensions = "mov", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mov_muxer_class, }; #endif #if CONFIG_TGP_MUXER MOV_CLASS(tgp) AVOutputFormat ff_tgp_muxer = { .name = "3gp", .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"), .extensions = "3gp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tgp_muxer_class, }; #endif #if CONFIG_MP4_MUXER MOV_CLASS(mp4) AVOutputFormat ff_mp4_muxer = { .name = "mp4", .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "mp4", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mp4_muxer_class, }; #endif #if CONFIG_PSP_MUXER MOV_CLASS(psp) AVOutputFormat ff_psp_muxer = { .name = "psp", .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"), .extensions = "mp4,psp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &psp_muxer_class, }; #endif #if CONFIG_TG2_MUXER MOV_CLASS(tg2) AVOutputFormat ff_tg2_muxer = { .name = "3g2", .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"), .extensions = "3g2", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tg2_muxer_class, }; #endif #if CONFIG_IPOD_MUXER MOV_CLASS(ipod) AVOutputFormat ff_ipod_muxer = { .name = "ipod", .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "m4v,m4a,m4b", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ipod_muxer_class, }; #endif #if CONFIG_ISMV_MUXER MOV_CLASS(ismv) AVOutputFormat ff_ismv_muxer = { .name = "ismv", .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"), .mime_type = "video/mp4", .extensions = "ismv,isma", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, codec_ism_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ismv_muxer_class, }; #endif #if CONFIG_F4V_MUXER MOV_CLASS(f4v) AVOutputFormat ff_f4v_muxer = { .name = "f4v", .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"), .mime_type = "application/f4v", .extensions = "f4v", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH, .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &f4v_muxer_class, }; #endif
./CrossVul/dataset_final_sorted/CWE-369/c/bad_257_0
crossvul-cpp_data_bad_2303_2
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library VMS-specific Routines. */ #include <stdlib.h> #include <unixio.h> #include "tiffiop.h" #if !HAVE_IEEEFP #include <math.h> #endif #ifdef VAXC #define NOSHARE noshare #else #define NOSHARE #endif COMPILATION SHOULD FAIL This file is not yet updated to reflect changes in LibTiff 4.0. If you have the opportunity to update and test this file, please contact LibTiff folks for all assistance you may require and contribute the results #ifdef __alpha /* Dummy entry point for backwards compatibility */ void TIFFModeCCITTFax3(void){} #endif static tsize_t _tiffReadProc(thandle_t fd, tdata_t buf, tsize_t size) { return (read((int) fd, buf, size)); } static tsize_t _tiffWriteProc(thandle_t fd, tdata_t buf, tsize_t size) { return (write((int) fd, buf, size)); } static toff_t _tiffSeekProc(thandle_t fd, toff_t off, int whence) { return ((toff_t) lseek((int) fd, (off_t) off, whence)); } static int _tiffCloseProc(thandle_t fd) { return (close((int) fd)); } #include <sys/stat.h> static toff_t _tiffSizeProc(thandle_t fd) { struct stat sb; return (toff_t) (fstat((int) fd, &sb) < 0 ? 0 : sb.st_size); } #ifdef HAVE_MMAP #include <starlet.h> #include <fab.h> #include <secdef.h> /* * Table for storing information on current open sections. * (Should really be a linked list) */ #define MAX_MAPPED 100 static int no_mapped = 0; static struct { char *base; char *top; unsigned short channel; } map_table[MAX_MAPPED]; /* * This routine maps a file into a private section. Note that this * method of accessing a file is by far the fastest under VMS. * The routine may fail (i.e. return 0) for several reasons, for * example: * - There is no more room for storing the info on sections. * - The process is out of open file quota, channels, ... * - fd does not describe an opened file. * - The file is already opened for write access by this process * or another process * - There is no free "hole" in virtual memory that fits the * size of the file */ static int _tiffMapProc(thandle_t fd, tdata_t* pbase, toff_t* psize) { char name[256]; struct FAB fab; unsigned short channel; char *inadr[2], *retadr[2]; unsigned long status; long size; if (no_mapped >= MAX_MAPPED) return(0); /* * We cannot use a file descriptor, we * must open the file once more. */ if (getname((int)fd, name, 1) == NULL) return(0); /* prepare the FAB for a user file open */ fab = cc$rms_fab; fab.fab$l_fop |= FAB$V_UFO; fab.fab$b_fac = FAB$M_GET; fab.fab$b_shr = FAB$M_SHRGET; fab.fab$l_fna = name; fab.fab$b_fns = strlen(name); status = sys$open(&fab); /* open file & get channel number */ if ((status&1) == 0) return(0); channel = (unsigned short)fab.fab$l_stv; inadr[0] = inadr[1] = (char *)0; /* just an address in P0 space */ /* * Map the blocks of the file up to * the EOF block into virtual memory. */ size = _tiffSizeProc(fd); status = sys$crmpsc(inadr, retadr, 0, SEC$M_EXPREG, 0,0,0, channel, TIFFhowmany(size,512), 0,0,0); ddd if ((status&1) == 0){ sys$dassgn(channel); return(0); } *pbase = (tdata_t) retadr[0]; /* starting virtual address */ /* * Use the size of the file up to the * EOF mark for UNIX compatibility. */ *psize = (toff_t) size; /* Record the section in the table */ map_table[no_mapped].base = retadr[0]; map_table[no_mapped].top = retadr[1]; map_table[no_mapped].channel = channel; no_mapped++; return(1); } /* * This routine unmaps a section from the virtual address space of * the process, but only if the base was the one returned from a * call to TIFFMapFileContents. */ static void _tiffUnmapProc(thandle_t fd, tdata_t base, toff_t size) { char *inadr[2]; int i, j; /* Find the section in the table */ for (i = 0;i < no_mapped; i++) { if (map_table[i].base == (char *) base) { /* Unmap the section */ inadr[0] = (char *) base; inadr[1] = map_table[i].top; sys$deltva(inadr, 0, 0); sys$dassgn(map_table[i].channel); /* Remove this section from the list */ for (j = i+1; j < no_mapped; j++) map_table[j-1] = map_table[j]; no_mapped--; return; } } } #else /* !HAVE_MMAP */ static int _tiffMapProc(thandle_t fd, tdata_t* pbase, toff_t* psize) { return (0); } static void _tiffUnmapProc(thandle_t fd, tdata_t base, toff_t size) { } #endif /* !HAVE_MMAP */ /* * Open a TIFF file descriptor for read/writing. */ TIFF* TIFFFdOpen(int fd, const char* name, const char* mode) { TIFF* tif; tif = TIFFClientOpen(name, mode, ddd (thandle_t) fd, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); if (tif) tif->tif_fd = fd; return (tif); } /* * Open a TIFF file for read/writing. */ TIFF* TIFFOpen(const char* name, const char* mode) { static const char module[] = "TIFFOpen"; int m, fd; m = _TIFFgetMode(mode, module); if (m == -1) return ((TIFF*)0); if (m&O_TRUNC){ /* * There is a bug in open in VAXC. If you use * open w/ m=O_RDWR|O_CREAT|O_TRUNC the * wrong thing happens. On the other hand * creat does the right thing. */ fd = creat((char *) /* bug in stdio.h */ name, 0666, "alq = 128", "deq = 64", "mbc = 32", "fop = tef"); } else if (m&O_RDWR) { fd = open(name, m, 0666, "deq = 64", "mbc = 32", "fop = tef", "ctx = stm"); } else fd = open(name, m, 0666, "mbc = 32", "ctx = stm"); if (fd < 0) { TIFFErrorExt(0, module, "%s: Cannot open", name); return ((TIFF*)0); } return (TIFFFdOpen(fd, name, mode)); } tdata_t _TIFFmalloc(tsize_t s) { return (malloc((size_t) s)); } void _TIFFfree(tdata_t p) { free(p); } tdata_t _TIFFrealloc(tdata_t p, tsize_t s) { return (realloc(p, (size_t) s)); } void _TIFFmemset(tdata_t p, int v, tsize_t c) { memset(p, v, (size_t) c); } void _TIFFmemcpy(tdata_t d, const tdata_t s, tsize_t c) { memcpy(d, s, (size_t) c); } int _TIFFmemcmp(const tdata_t p1, const tdata_t p2, tsize_t c) { return (memcmp(p1, p2, (size_t) c)); } /* * On the VAX, we need to make those global, writable pointers * non-shareable, otherwise they would be made shareable by default. * On the AXP, this brain damage has been corrected. * * I (Karsten Spang, krs@kampsax.dk) have dug around in the GCC * manual and the GAS code and have come up with the following * construct, but I don't have GCC on my VAX, so it is untested. * Please tell me if it does not work. */ static void vmsWarningHandler(const char* module, const char* fmt, va_list ap) { if (module != NULL) fprintf(stderr, "%s: ", module); fprintf(stderr, "Warning, "); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); } NOSHARE TIFFErrorHandler _TIFFwarningHandler = vmsWarningHandler #if defined(VAX) && defined(__GNUC__) asm("_$$PsectAttributes_NOSHR$$_TIFFwarningHandler") #endif ; static void vmsErrorHandler(const char* module, const char* fmt, va_list ap) { if (module != NULL) fprintf(stderr, "%s: ", module); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); } NOSHARE TIFFErrorHandler _TIFFerrorHandler = vmsErrorHandler #if defined(VAX) && defined(__GNUC__) asm("_$$PsectAttributes_NOSHR$$_TIFFerrorHandler") #endif ; #if !HAVE_IEEEFP /* IEEE floting point handling */ typedef struct ieeedouble { unsigned long mant2; /* fix NDR: full 8-byte swap */ unsigned long mant : 20, exp : 11, sign : 1; } ieeedouble; typedef struct ieeefloat { unsigned long mant : 23, exp : 8, sign : 1; } ieeefloat; /* * NB: These are D_FLOAT's, not G_FLOAT's. A G_FLOAT is * simply a reverse-IEEE float/double. */ typedef struct { unsigned long mant1 : 7, exp : 8, sign : 1, mant2 : 16, mant3 : 16, mant4 : 16; } nativedouble; typedef struct { unsigned long mant1 : 7, exp : 8, sign : 1, mant2 : 16; } nativefloat; typedef union { ieeedouble ieee; nativedouble native; char b[8]; uint32 l[2]; double d; } double_t; typedef union { ieeefloat ieee; nativefloat native; char b[4]; uint32 l; float f; } float_t; #if defined(VAXC) || defined(DECC) #pragma inline(ieeetod,dtoieee) #endif /* * Convert an IEEE double precision number to native double precision. * The source is contained in two longwords, the second holding the sign, * exponent and the higher order bits of the mantissa, and the first * holding the rest of the mantissa as follows: * (Note: It is assumed that the number has been eight-byte swapped to * LSB first.) * * First longword: * 32 least significant bits of mantissa * Second longword: * 0-19: 20 most significant bits of mantissa * 20-30: exponent * 31: sign * The exponent is stored as excess 1023. * The most significant bit of the mantissa is implied 1, and not stored. * If the exponent and mantissa are zero, the number is zero. * If the exponent is 0 (i.e. -1023) and the mantissa is non-zero, it is an * unnormalized number with the most significant bit NOT implied. * If the exponent is 2047, the number is invalid, in case the mantissa is zero, * this means overflow (+/- depending of the sign bit), otherwise * it simply means invalid number. * * If the number is too large for the machine or was specified as overflow, * +/-HUGE_VAL is returned. */ INLINE static void ieeetod(double *dp) { double_t source; long sign,exp,mant; double dmant; source.ieee = ((double_t*)dp)->ieee; sign = source.ieee.sign; exp = source.ieee.exp; mant = source.ieee.mant; if (exp == 2047) { if (mant) /* Not a Number (NAN) */ *dp = HUGE_VAL; else /* +/- infinity */ *dp = (sign ? -HUGE_VAL : HUGE_VAL); return; } if (!exp) { if (!(mant || source.ieee.mant2)) { /* zero */ *dp=0; return; } else { /* Unnormalized number */ /* NB: not -1023, the 1 bit is not implied */ exp= -1022; } } else { mant |= 1<<20; exp -= 1023; } dmant = (((double) mant) + ((double) source.ieee.mant2) / (((double) (1<<16)) * ((double) (1<<16)))) / (double) (1<<20); dmant = ldexp(dmant, exp); if (sign) dmant= -dmant; *dp = dmant; } INLINE static void dtoieee(double *dp) { double_t num; double x; int exp; num.d = *dp; if (!num.d) { /* Zero is just binary all zeros */ num.l[0] = num.l[1] = 0; return; } if (num.d < 0) { /* Sign is encoded separately */ num.d = -num.d; num.ieee.sign = 1; } else { num.ieee.sign = 0; } /* Now separate the absolute value into mantissa and exponent */ x = frexp(num.d, &exp); /* * Handle cases where the value is outside the * range for IEEE floating point numbers. * (Overflow cannot happen on a VAX, but underflow * can happen for G float.) */ if (exp < -1022) { /* Unnormalized number */ x = ldexp(x, -1023-exp); exp = 0; } else if (exp > 1023) { /* +/- infinity */ x = 0; exp = 2047; } else { /* Get rid of most significant bit */ x *= 2; x -= 1; exp += 1022; /* fix NDR: 1.0 -> x=0.5, exp=1 -> ieee.exp = 1023 */ } num.ieee.exp = exp; x *= (double) (1<<20); num.ieee.mant = (long) x; x -= (double) num.ieee.mant; num.ieee.mant2 = (long) (x*((double) (1<<16)*(double) (1<<16))); if (!(num.ieee.mant || num.ieee.exp || num.ieee.mant2)) { /* Avoid negative zero */ num.ieee.sign = 0; } ((double_t*)dp)->ieee = num.ieee; } /* * Beware, these do not handle over/under-flow * during conversion from ieee to native format. */ #define NATIVE2IEEEFLOAT(fp) { \ float_t t; \ if (t.ieee.exp = (fp)->native.exp) \ t.ieee.exp += -129 + 127; \ t.ieee.sign = (fp)->native.sign; \ t.ieee.mant = ((fp)->native.mant1<<16)|(fp)->native.mant2; \ *(fp) = t; \ } #define IEEEFLOAT2NATIVE(fp) { \ float_t t; int v = (fp)->ieee.exp; \ if (v) v += -127 + 129; /* alter bias of exponent */\ t.native.exp = v; /* implicit truncation of exponent */\ t.native.sign = (fp)->ieee.sign; \ v = (fp)->ieee.mant; \ t.native.mant1 = v >> 16; \ t.native.mant2 = v;\ *(fp) = t; \ } #define IEEEDOUBLE2NATIVE(dp) ieeetod(dp) #define NATIVE2IEEEDOUBLE(dp) dtoieee(dp) /* * These unions are used during floating point * conversions. The above macros define the * conversion operations. */ void TIFFCvtIEEEFloatToNative(TIFF* tif, u_int n, float* f) { float_t* fp = (float_t*) f; while (n-- > 0) { IEEEFLOAT2NATIVE(fp); fp++; } } void TIFFCvtNativeToIEEEFloat(TIFF* tif, u_int n, float* f) { float_t* fp = (float_t*) f; while (n-- > 0) { NATIVE2IEEEFLOAT(fp); fp++; } } void TIFFCvtIEEEDoubleToNative(TIFF* tif, u_int n, double* f) { double_t* fp = (double_t*) f; while (n-- > 0) { IEEEDOUBLE2NATIVE(fp); fp++; } } void TIFFCvtNativeToIEEEDouble(TIFF* tif, u_int n, double* f) { double_t* fp = (double_t*) f; while (n-- > 0) { NATIVE2IEEEDOUBLE(fp); fp++; } } #endif /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-369/c/bad_2303_2
crossvul-cpp_data_bad_3367_0
// imagew-api.c // Part of ImageWorsener, Copyright (c) 2011 by Jason Summers. // For more information, see the readme.txt file. // Most of the functions declared in imagew.h are defined here. #include "imagew-config.h" #include <stdlib.h> #include <string.h> #include <stdarg.h> #include "imagew-internals.h" // Translate a string, using the given flags. IW_IMPL(void) iw_translate(struct iw_context *ctx, unsigned int flags, char *dst, size_t dstlen, const char *src) { int ret; dst[0]='\0'; if(ctx && ctx->translate_fn) { ret = (*ctx->translate_fn)(ctx,flags,dst,dstlen,src); } else { ret = 0; } if(!ret) { // Not translated. Just copy the string. iw_strlcpy(dst,src,dstlen); } } // Formats and translates, and returns the resulting string in buf. // 'ctx' can be NULL, in which case no tranlation will happen. IW_IMPL(void) iw_translatev(struct iw_context *ctx, unsigned int flags, char *dst, size_t dstlen, const char *fmt, va_list ap) { char buf1[IW_MSG_MAX]; char buf2[IW_MSG_MAX]; // If not translating, just format the string directly. if(!ctx || !ctx->translate_fn) { iw_vsnprintf(dst,dstlen,fmt,ap); return; } // String is now in fmt. iw_translate(ctx,IW_TRANSLATEFLAG_FORMAT|flags,buf1,sizeof(buf1),fmt); // String is now in buf1. iw_vsnprintf(buf2,sizeof(buf2),buf1,ap); // String is now in buf2. iw_translate(ctx,IW_TRANSLATEFLAG_POSTFORMAT|flags,dst,dstlen,buf2); // String is now in dst. } // Formats and translates, and returns the resulting string in buf IW_IMPL(void) iw_translatef(struct iw_context *ctx, unsigned int flags, char *dst, size_t dstlen, const char *fmt, ...) { va_list ap; va_start(ap, fmt); iw_translatev(ctx,flags,dst,dstlen,fmt,ap); va_end(ap); } static void iw_warning_internal(struct iw_context *ctx, const char *s) { if(!ctx->warning_fn) return; (*ctx->warning_fn)(ctx,s); } IW_IMPL(void) iw_warning(struct iw_context *ctx, const char *s) { char buf[IW_MSG_MAX]; if(!ctx->warning_fn) return; iw_translate(ctx,IW_TRANSLATEFLAG_WARNINGMSG,buf,sizeof(buf),s); iw_warning_internal(ctx,buf); } IW_IMPL(void) iw_warningv(struct iw_context *ctx, const char *fmt, va_list ap) { char buf[IW_MSG_MAX]; if(!ctx->warning_fn) return; iw_translatev(ctx,IW_TRANSLATEFLAG_WARNINGMSG,buf,sizeof(buf),fmt,ap); iw_warning_internal(ctx,buf); } // Call the caller's warning function, if defined. IW_IMPL(void) iw_warningf(struct iw_context *ctx, const char *fmt, ...) { va_list ap; if(!ctx->warning_fn) return; va_start(ap, fmt); iw_warningv(ctx,fmt,ap); va_end(ap); } static void iw_set_error_internal(struct iw_context *ctx, const char *s) { if(ctx->error_flag) return; // Only record the first error. ctx->error_flag = 1; if(!ctx->error_msg) { ctx->error_msg=iw_malloc_ex(ctx,IW_MALLOCFLAG_NOERRORS,IW_MSG_MAX*sizeof(char)); if(!ctx->error_msg) { return; } } iw_strlcpy(ctx->error_msg,s,IW_MSG_MAX); } IW_IMPL(void) iw_set_error(struct iw_context *ctx, const char *s) { char buf[IW_MSG_MAX]; if(ctx->error_flag) return; // Only record the first error. iw_translate(ctx,IW_TRANSLATEFLAG_ERRORMSG,buf,sizeof(buf),s); iw_set_error_internal(ctx,buf); } IW_IMPL(void) iw_set_errorv(struct iw_context *ctx, const char *fmt, va_list ap) { char buf[IW_MSG_MAX]; if(ctx->error_flag) return; // Only record the first error. iw_translatev(ctx,IW_TRANSLATEFLAG_ERRORMSG,buf,sizeof(buf),fmt,ap); iw_set_error_internal(ctx,buf); } IW_IMPL(void) iw_set_errorf(struct iw_context *ctx, const char *fmt, ...) { va_list ap; va_start(ap, fmt); iw_set_errorv(ctx,fmt,ap); va_end(ap); } IW_IMPL(const char*) iw_get_errormsg(struct iw_context *ctx, char *buf, int buflen) { if(ctx->error_msg) { iw_strlcpy(buf,ctx->error_msg,buflen); } else { iw_translate(ctx,IW_TRANSLATEFLAG_ERRORMSG,buf,buflen,"Error message not available"); } return buf; } IW_IMPL(int) iw_get_errorflag(struct iw_context *ctx) { return ctx->error_flag; } // Given a color type, returns the number of channels. IW_IMPL(int) iw_imgtype_num_channels(int t) { switch(t) { case IW_IMGTYPE_RGBA: return 4; case IW_IMGTYPE_RGB: return 3; case IW_IMGTYPE_GRAYA: return 2; } return 1; } IW_IMPL(size_t) iw_calc_bytesperrow(int num_pixels, int bits_per_pixel) { return (size_t)(((num_pixels*bits_per_pixel)+7)/8); } IW_IMPL(int) iw_check_image_dimensions(struct iw_context *ctx, int w, int h) { if(w>ctx->max_width || h>ctx->max_height) { iw_set_errorf(ctx,"Image dimensions too large (%d\xc3\x97%d)",w,h); return 0; } if(w<1 || h<1) { iw_set_errorf(ctx,"Invalid image dimensions (%d\xc3\x97%d)",w,h); return 0; } return 1; } IW_IMPL(int) iw_is_valid_density(double density_x, double density_y, int density_code) { if(density_x<0.0001 || density_y<0.0001) return 0; if(density_x>10000000.0 || density_y>10000000.0) return 0; if(density_x/10.0>density_y) return 0; if(density_y/10.0>density_x) return 0; if(density_code!=IW_DENSITY_UNITS_UNKNOWN && density_code!=IW_DENSITY_UNITS_PER_METER) return 0; return 1; } static void default_resize_settings(struct iw_resize_settings *rs) { int i; rs->family = IW_RESIZETYPE_AUTO; rs->edge_policy = IW_EDGE_POLICY_STANDARD; rs->blur_factor = 1.0; rs->translate = 0.0; for(i=0;i<3;i++) { rs->channel_offset[i] = 0.0; } } IW_IMPL(struct iw_context*) iw_create_context(struct iw_init_params *params) { struct iw_context *ctx; if(params && params->mallocfn) { ctx = (*params->mallocfn)(params->userdata,IW_MALLOCFLAG_ZEROMEM,sizeof(struct iw_context)); } else { ctx = iwpvt_default_malloc(NULL,IW_MALLOCFLAG_ZEROMEM,sizeof(struct iw_context)); } if(!ctx) return NULL; if(params) { ctx->userdata = params->userdata; ctx->caller_api_version = params->api_version; } if(params && params->mallocfn) { ctx->mallocfn = params->mallocfn; ctx->freefn = params->freefn; } else { ctx->mallocfn = iwpvt_default_malloc; ctx->freefn = iwpvt_default_free; } ctx->max_malloc = IW_DEFAULT_MAX_MALLOC; ctx->max_width = ctx->max_height = IW_DEFAULT_MAX_DIMENSION; default_resize_settings(&ctx->resize_settings[IW_DIMENSION_H]); default_resize_settings(&ctx->resize_settings[IW_DIMENSION_V]); ctx->input_w = -1; ctx->input_h = -1; iw_make_srgb_csdescr_2(&ctx->img1cs); iw_make_srgb_csdescr_2(&ctx->img2cs); ctx->to_grayscale=0; ctx->grayscale_formula = IW_GSF_STANDARD; ctx->req.include_screen = 1; ctx->opt_grayscale = 1; ctx->opt_palette = 1; ctx->opt_16_to_8 = 1; ctx->opt_strip_alpha = 1; ctx->opt_binary_trns = 1; return ctx; } IW_IMPL(void) iw_destroy_context(struct iw_context *ctx) { int i; if(!ctx) return; if(ctx->req.options) { for(i=0; i<=ctx->req.options_count; i++) { iw_free(ctx, ctx->req.options[i].name); iw_free(ctx, ctx->req.options[i].val); } iw_free(ctx, ctx->req.options); } if(ctx->img1.pixels) iw_free(ctx,ctx->img1.pixels); if(ctx->img2.pixels) iw_free(ctx,ctx->img2.pixels); if(ctx->error_msg) iw_free(ctx,ctx->error_msg); if(ctx->optctx.tmp_pixels) iw_free(ctx,ctx->optctx.tmp_pixels); if(ctx->optctx.palette) iw_free(ctx,ctx->optctx.palette); if(ctx->input_color_corr_table) iw_free(ctx,ctx->input_color_corr_table); if(ctx->output_rev_color_corr_table) iw_free(ctx,ctx->output_rev_color_corr_table); if(ctx->nearest_color_table) iw_free(ctx,ctx->nearest_color_table); if(ctx->prng) iwpvt_prng_destroy(ctx,ctx->prng); iw_free(ctx,ctx); } IW_IMPL(void) iw_get_output_image(struct iw_context *ctx, struct iw_image *img) { int k; iw_zeromem(img,sizeof(struct iw_image)); img->width = ctx->optctx.width; img->height = ctx->optctx.height; img->imgtype = ctx->optctx.imgtype; img->sampletype = ctx->img2.sampletype; img->bit_depth = ctx->optctx.bit_depth; img->pixels = (iw_byte*)ctx->optctx.pixelsptr; img->bpr = ctx->optctx.bpr; img->density_code = ctx->img2.density_code; img->density_x = ctx->img2.density_x; img->density_y = ctx->img2.density_y; img->rendering_intent = ctx->img2.rendering_intent; img->has_bkgdlabel = ctx->optctx.has_bkgdlabel; for(k=0;k<4;k++) { if(ctx->optctx.bit_depth==8) { img->bkgdlabel.c[k] = ((double)ctx->optctx.bkgdlabel[k])/255.0; } else { img->bkgdlabel.c[k] = ((double)ctx->optctx.bkgdlabel[k])/65535.0; } } img->has_colorkey_trns = ctx->optctx.has_colorkey_trns; img->colorkey[0] = ctx->optctx.colorkey[0]; img->colorkey[1] = ctx->optctx.colorkey[1]; img->colorkey[2] = ctx->optctx.colorkey[2]; if(ctx->reduced_output_maxcolor_flag) { img->reduced_maxcolors = 1; if(IW_IMGTYPE_IS_GRAY(img->imgtype)) { img->maxcolorcode[IW_CHANNELTYPE_GRAY] = ctx->img2_ci[0].maxcolorcode_int; if(IW_IMGTYPE_HAS_ALPHA(img->imgtype)) { img->maxcolorcode[IW_CHANNELTYPE_ALPHA] = ctx->img2_ci[1].maxcolorcode_int; } } else { img->maxcolorcode[IW_CHANNELTYPE_RED] = ctx->img2_ci[0].maxcolorcode_int; img->maxcolorcode[IW_CHANNELTYPE_GREEN] = ctx->img2_ci[1].maxcolorcode_int; img->maxcolorcode[IW_CHANNELTYPE_BLUE] = ctx->img2_ci[2].maxcolorcode_int; if(IW_IMGTYPE_HAS_ALPHA(img->imgtype)) { img->maxcolorcode[IW_CHANNELTYPE_ALPHA] = ctx->img2_ci[3].maxcolorcode_int; } } } } IW_IMPL(void) iw_get_output_colorspace(struct iw_context *ctx, struct iw_csdescr *csdescr) { *csdescr = ctx->img2cs; // struct copy } IW_IMPL(const struct iw_palette*) iw_get_output_palette(struct iw_context *ctx) { return ctx->optctx.palette; } IW_IMPL(void) iw_set_output_canvas_size(struct iw_context *ctx, int w, int h) { ctx->canvas_width = w; ctx->canvas_height = h; } IW_IMPL(void) iw_set_output_image_size(struct iw_context *ctx, double w, double h) { ctx->req.out_true_width = w; if(ctx->req.out_true_width<0.01) ctx->req.out_true_width=0.01; ctx->req.out_true_height = h; if(ctx->req.out_true_height<0.01) ctx->req.out_true_height=0.01; ctx->req.out_true_valid = 1; } IW_IMPL(void) iw_set_input_crop(struct iw_context *ctx, int x, int y, int w, int h) { ctx->input_start_x = x; ctx->input_start_y = y; ctx->input_w = w; ctx->input_h = h; } IW_IMPL(void) iw_set_output_profile(struct iw_context *ctx, unsigned int n) { ctx->output_profile = n; } IW_IMPL(void) iw_set_output_depth(struct iw_context *ctx, int bps) { ctx->req.output_depth = bps; } IW_IMPL(void) iw_set_output_max_color_code(struct iw_context *ctx, int channeltype, int n) { if(channeltype>=0 && channeltype<IW_NUM_CHANNELTYPES) { ctx->req.output_maxcolorcode[channeltype] = n; } } IW_IMPL(void) iw_set_dither_type(struct iw_context *ctx, int channeltype, int f, int s) { if(channeltype>=0 && channeltype<IW_NUM_CHANNELTYPES) { ctx->ditherfamily_by_channeltype[channeltype] = f; ctx->dithersubtype_by_channeltype[channeltype] = s; } switch(channeltype) { case IW_CHANNELTYPE_ALL: ctx->ditherfamily_by_channeltype[IW_CHANNELTYPE_ALPHA] = f; ctx->dithersubtype_by_channeltype[IW_CHANNELTYPE_ALPHA] = s; // fall thru case IW_CHANNELTYPE_NONALPHA: ctx->ditherfamily_by_channeltype[IW_CHANNELTYPE_RED] = f; ctx->dithersubtype_by_channeltype[IW_CHANNELTYPE_RED] = s; ctx->ditherfamily_by_channeltype[IW_CHANNELTYPE_GREEN] = f; ctx->dithersubtype_by_channeltype[IW_CHANNELTYPE_GREEN] = s; ctx->ditherfamily_by_channeltype[IW_CHANNELTYPE_BLUE] = f; ctx->dithersubtype_by_channeltype[IW_CHANNELTYPE_BLUE] = s; ctx->ditherfamily_by_channeltype[IW_CHANNELTYPE_GRAY] = f; ctx->dithersubtype_by_channeltype[IW_CHANNELTYPE_GRAY] = s; break; } } IW_IMPL(void) iw_set_color_count(struct iw_context *ctx, int channeltype, int c) { if(channeltype>=0 && channeltype<IW_NUM_CHANNELTYPES) { ctx->req.color_count[channeltype] = c; } switch(channeltype) { case IW_CHANNELTYPE_ALL: ctx->req.color_count[IW_CHANNELTYPE_ALPHA] = c; // fall thru case IW_CHANNELTYPE_NONALPHA: ctx->req.color_count[IW_CHANNELTYPE_RED] = c; ctx->req.color_count[IW_CHANNELTYPE_GREEN] = c; ctx->req.color_count[IW_CHANNELTYPE_BLUE] = c; ctx->req.color_count[IW_CHANNELTYPE_GRAY] = c; break; } } IW_IMPL(void) iw_set_channel_offset(struct iw_context *ctx, int channeltype, int dimension, double offs) { if(channeltype<0 || channeltype>2) return; if(dimension<0 || dimension>1) dimension=0; ctx->resize_settings[dimension].channel_offset[channeltype] = offs; } IW_IMPL(void) iw_set_input_max_color_code(struct iw_context *ctx, int input_channel, int c) { if(input_channel>=0 && input_channel<IW_CI_COUNT) { ctx->img1_ci[input_channel].maxcolorcode_int = c; } } IW_IMPL(void) iw_set_input_bkgd_label_2(struct iw_context *ctx, const struct iw_color *clr) { ctx->img1_bkgd_label_set = 1; ctx->img1_bkgd_label_inputcs = *clr; } IW_IMPL(void) iw_set_input_bkgd_label(struct iw_context *ctx, double r, double g, double b) { struct iw_color clr; clr.c[0] = r; clr.c[1] = g; clr.c[2] = b; clr.c[3] = 1.0; iw_set_input_bkgd_label_2(ctx, &clr); } IW_IMPL(void) iw_set_output_bkgd_label_2(struct iw_context *ctx, const struct iw_color *clr) { ctx->req.output_bkgd_label_valid = 1; ctx->req.output_bkgd_label = *clr; } IW_IMPL(void) iw_set_output_bkgd_label(struct iw_context *ctx, double r, double g, double b) { struct iw_color clr; clr.c[0] = r; clr.c[1] = g; clr.c[2] = b; clr.c[3] = 1.0; iw_set_output_bkgd_label_2(ctx, &clr); } IW_IMPL(int) iw_get_input_density(struct iw_context *ctx, double *px, double *py, int *pcode) { *px = 1.0; *py = 1.0; *pcode = ctx->img1.density_code; if(ctx->img1.density_code!=IW_DENSITY_UNKNOWN) { *px = ctx->img1.density_x; *py = ctx->img1.density_y; return 1; } return 0; } IW_IMPL(void) iw_set_output_density(struct iw_context *ctx, double x, double y, int code) { ctx->img2.density_code = code; ctx->img2.density_x = x; ctx->img2.density_y = y; } // Detect a "gamma" colorspace that is actually linear. static void optimize_csdescr(struct iw_csdescr *cs) { if(cs->cstype!=IW_CSTYPE_GAMMA) return; if(cs->gamma>=0.999995 && cs->gamma<=1.000005) { cs->cstype = IW_CSTYPE_LINEAR; } } IW_IMPL(void) iw_make_linear_csdescr(struct iw_csdescr *cs) { cs->cstype = IW_CSTYPE_LINEAR; cs->gamma = 0.0; cs->srgb_intent = 0; } // This function is deprecated, and should not be used. IW_IMPL(void) iw_make_srgb_csdescr(struct iw_csdescr *cs, int srgb_intent) { cs->cstype = IW_CSTYPE_SRGB; cs->gamma = 0.0; cs->srgb_intent = srgb_intent; } IW_IMPL(void) iw_make_srgb_csdescr_2(struct iw_csdescr *cs) { cs->cstype = IW_CSTYPE_SRGB; cs->gamma = 0.0; } IW_IMPL(void) iw_make_rec709_csdescr(struct iw_csdescr *cs) { cs->cstype = IW_CSTYPE_REC709; cs->gamma = 0.0; } IW_IMPL(void) iw_make_gamma_csdescr(struct iw_csdescr *cs, double gamma) { cs->cstype = IW_CSTYPE_GAMMA; cs->gamma = gamma; if(cs->gamma<0.1) cs->gamma=0.1; if(cs->gamma>10.0) cs->gamma=10.0; cs->srgb_intent = 0; optimize_csdescr(cs); } IW_IMPL(void) iw_set_output_colorspace(struct iw_context *ctx, const struct iw_csdescr *csdescr) { ctx->req.output_cs = *csdescr; // struct copy optimize_csdescr(&ctx->req.output_cs); ctx->req.output_cs_valid = 1; } IW_IMPL(void) iw_set_input_colorspace(struct iw_context *ctx, const struct iw_csdescr *csdescr) { ctx->img1cs = *csdescr; // struct copy optimize_csdescr(&ctx->img1cs); } IW_IMPL(void) iw_set_apply_bkgd_2(struct iw_context *ctx, const struct iw_color *clr) { ctx->req.bkgd_valid=1; ctx->req.bkgd = *clr; } IW_IMPL(void) iw_set_apply_bkgd(struct iw_context *ctx, double r, double g, double b) { struct iw_color clr; clr.c[IW_CHANNELTYPE_RED]=r; clr.c[IW_CHANNELTYPE_GREEN]=g; clr.c[IW_CHANNELTYPE_BLUE]=b; clr.c[IW_CHANNELTYPE_ALPHA]=1.0; iw_set_apply_bkgd_2(ctx, &clr); } IW_IMPL(void) iw_set_bkgd_checkerboard_2(struct iw_context *ctx, int checkersize, const struct iw_color *clr) { ctx->req.bkgd_checkerboard=1; ctx->bkgd_check_size=checkersize; ctx->req.bkgd2 = *clr; } IW_IMPL(void) iw_set_bkgd_checkerboard(struct iw_context *ctx, int checkersize, double r2, double g2, double b2) { struct iw_color clr; clr.c[IW_CHANNELTYPE_RED]=r2; clr.c[IW_CHANNELTYPE_GREEN]=g2; clr.c[IW_CHANNELTYPE_BLUE]=b2; clr.c[IW_CHANNELTYPE_ALPHA]=1.0; iw_set_bkgd_checkerboard_2(ctx, checkersize, &clr); } IW_IMPL(void) iw_set_bkgd_checkerboard_origin(struct iw_context *ctx, int x, int y) { ctx->bkgd_check_origin[IW_DIMENSION_H] = x; ctx->bkgd_check_origin[IW_DIMENSION_V] = y; } IW_IMPL(void) iw_set_max_malloc(struct iw_context *ctx, size_t n) { ctx->max_malloc = n; } IW_IMPL(void) iw_set_random_seed(struct iw_context *ctx, int randomize, int rand_seed) { ctx->randomize = randomize; ctx->random_seed = rand_seed; } IW_IMPL(void) iw_set_userdata(struct iw_context *ctx, void *userdata) { ctx->userdata = userdata; } IW_IMPL(void*) iw_get_userdata(struct iw_context *ctx) { return ctx->userdata; } IW_IMPL(void) iw_set_translate_fn(struct iw_context *ctx, iw_translatefn_type xlatefn) { ctx->translate_fn = xlatefn; } IW_IMPL(void) iw_set_warning_fn(struct iw_context *ctx, iw_warningfn_type warnfn) { ctx->warning_fn = warnfn; } IW_IMPL(void) iw_set_input_image(struct iw_context *ctx, const struct iw_image *img) { ctx->img1 = *img; // struct copy } IW_IMPL(void) iw_set_resize_alg(struct iw_context *ctx, int dimension, int family, double blur, double param1, double param2) { struct iw_resize_settings *rs; if(dimension<0 || dimension>1) dimension=0; rs=&ctx->resize_settings[dimension]; rs->family = family; rs->blur_factor = blur; rs->param1 = param1; rs->param2 = param2; } IW_IMPL(void) iw_reorient_image(struct iw_context *ctx, unsigned int x) { static const unsigned int transpose_tbl[8] = { 4,6,5,7,0,2,1,3 }; int tmpi; double tmpd; x = x & 0x07; // If needed, perform a 'transpose' of the current transform. if(x&0x04) { ctx->img1.orient_transform = transpose_tbl[ctx->img1.orient_transform]; // We swapped the width and height, so we need to fix up some things. tmpi = ctx->img1.width; ctx->img1.width = ctx->img1.height; ctx->img1.height = tmpi; tmpd = ctx->img1.density_x; ctx->img1.density_x = ctx->img1.density_y; ctx->img1.density_y = tmpd; } // Do horizontal and vertical mirroring. ctx->img1.orient_transform ^= (x&0x03); } IW_IMPL(int) iw_get_sample_size(void) { return (int)sizeof(iw_float32); } IW_IMPL(int) iw_get_version_int(void) { return IW_VERSION_INT; } IW_IMPL(char*) iw_get_version_string(struct iw_context *ctx, char *s, int s_len) { int ver; ver = iw_get_version_int(); iw_snprintf(s,s_len,"%d.%d.%d", (ver&0xff0000)>>16, (ver&0xff00)>>8, (ver&0xff) ); return s; } IW_IMPL(char*) iw_get_copyright_string(struct iw_context *ctx, char *dst, int dstlen) { iw_translatef(ctx,0,dst,dstlen,"Copyright \xc2\xa9 %s %s",IW_COPYRIGHT_YEAR,"Jason Summers"); return dst; } IW_IMPL(void) iw_set_zlib_module(struct iw_context *ctx, struct iw_zlib_module *z) { ctx->zlib_module = z; } IW_IMPL(struct iw_zlib_module*) iw_get_zlib_module(struct iw_context *ctx) { return ctx->zlib_module; } IW_IMPL(void) iw_set_allow_opt(struct iw_context *ctx, int opt, int n) { iw_byte v; v = n?1:0; switch(opt) { case IW_OPT_GRAYSCALE: ctx->opt_grayscale = v; break; case IW_OPT_PALETTE: ctx->opt_palette = v; break; case IW_OPT_16_TO_8: ctx->opt_16_to_8 = v; break; case IW_OPT_STRIP_ALPHA: ctx->opt_strip_alpha = v; break; case IW_OPT_BINARY_TRNS: ctx->opt_binary_trns = v; break; } } IW_IMPL(void) iw_set_grayscale_weights(struct iw_context *ctx, double r, double g, double b) { double tot; //ctx->grayscale_formula = IW_GSF_WEIGHTED; // Normalize, so the weights add up to 1. tot = r+g+b; if(tot==0.0) tot=1.0; ctx->grayscale_weight[0] = r/tot; ctx->grayscale_weight[1] = g/tot; ctx->grayscale_weight[2] = b/tot; } IW_IMPL(unsigned int) iw_color_get_int_sample(struct iw_color *clr, int channel, unsigned int maxcolorcode) { int n; n = (int)(0.5+(clr->c[channel] * (double)maxcolorcode)); if(n<0) n=0; else if(n>(int)maxcolorcode) n=(int)maxcolorcode; return (unsigned int)n; } IW_IMPL(void) iw_set_value(struct iw_context *ctx, int code, int n) { switch(code) { case IW_VAL_API_VERSION: ctx->caller_api_version = n; break; case IW_VAL_CVT_TO_GRAYSCALE: ctx->to_grayscale = n; break; case IW_VAL_DISABLE_GAMMA: ctx->no_gamma = n; break; case IW_VAL_NO_CSLABEL: ctx->req.suppress_output_cslabel = n; break; case IW_VAL_INT_CLAMP: ctx->intclamp = n; break; case IW_VAL_EDGE_POLICY_X: ctx->resize_settings[IW_DIMENSION_H].edge_policy = n; break; case IW_VAL_EDGE_POLICY_Y: ctx->resize_settings[IW_DIMENSION_V].edge_policy = n; break; case IW_VAL_PREF_UNITS: ctx->pref_units = n; break; case IW_VAL_GRAYSCALE_FORMULA: ctx->grayscale_formula = n; break; case IW_VAL_INPUT_NATIVE_GRAYSCALE: ctx->img1.native_grayscale = n; break; case IW_VAL_COMPRESSION: ctx->req.compression = n; break; case IW_VAL_PAGE_TO_READ: ctx->req.page_to_read = n; break; case IW_VAL_INCLUDE_SCREEN: ctx->req.include_screen = n; break; case IW_VAL_JPEG_QUALITY: // For backward compatibility only. iw_set_option(ctx, "jpeg:quality", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_JPEG_SAMP_FACTOR_H: // For backward compatibility only. iw_set_option(ctx, "jpeg:sampling-x", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_JPEG_SAMP_FACTOR_V: // For backward compatibility only. iw_set_option(ctx, "jpeg:sampling-y", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_JPEG_ARITH_CODING: // For backward compatibility only. iw_set_option(ctx, "jpeg:arith", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_DEFLATE_CMPR_LEVEL: // For backward compatibility only. iw_set_option(ctx, "deflate:cmprlevel", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_OUTPUT_INTERLACED: ctx->req.interlaced = n; break; case IW_VAL_USE_BKGD_LABEL: ctx->req.use_bkgd_label_from_file = n; break; case IW_VAL_BMP_NO_FILEHEADER: ctx->req.bmp_no_fileheader = n; break; case IW_VAL_BMP_VERSION: // For backward compatibility only. iw_set_option(ctx, "bmp:version", iwpvt_strdup_dbl(ctx, (double)n)); break; case IW_VAL_MAX_WIDTH: ctx->max_width = n; break; case IW_VAL_MAX_HEIGHT: ctx->max_height = n; break; case IW_VAL_NO_BKGD_LABEL: ctx->req.suppress_output_bkgd_label = n; break; case IW_VAL_INTENT: ctx->req.output_rendering_intent = n; break; case IW_VAL_OUTPUT_SAMPLE_TYPE: ctx->req.output_sample_type = n; break; case IW_VAL_OUTPUT_COLOR_TYPE: // For backward compatibility only. if(n==IW_COLORTYPE_RGB) { iw_set_option(ctx, "deflate:colortype", "rgb"); } break; case IW_VAL_OUTPUT_FORMAT: ctx->req.output_format = n; break; case IW_VAL_NEGATE_TARGET: ctx->req.negate_target = n; break; } } IW_IMPL(int) iw_get_value(struct iw_context *ctx, int code) { int ret=0; switch(code) { case IW_VAL_API_VERSION: ret = ctx->caller_api_version; break; case IW_VAL_CVT_TO_GRAYSCALE: ret = ctx->to_grayscale; break; case IW_VAL_DISABLE_GAMMA: ret = ctx->no_gamma; break; case IW_VAL_NO_CSLABEL: ret = ctx->req.suppress_output_cslabel; break; case IW_VAL_INT_CLAMP: ret = ctx->intclamp; break; case IW_VAL_EDGE_POLICY_X: ret = ctx->resize_settings[IW_DIMENSION_H].edge_policy; break; case IW_VAL_EDGE_POLICY_Y: ret = ctx->resize_settings[IW_DIMENSION_V].edge_policy; break; case IW_VAL_PREF_UNITS: ret = ctx->pref_units; break; case IW_VAL_GRAYSCALE_FORMULA: ret = ctx->grayscale_formula; break; case IW_VAL_INPUT_NATIVE_GRAYSCALE: ret = ctx->img1.native_grayscale; break; case IW_VAL_INPUT_WIDTH: if(ctx->img1.width<1) ret=1; else ret = ctx->img1.width; break; case IW_VAL_INPUT_HEIGHT: if(ctx->img1.height<1) ret=1; else ret = ctx->img1.height; break; case IW_VAL_INPUT_IMAGE_TYPE: ret = ctx->img1.imgtype; break; case IW_VAL_INPUT_DEPTH: ret = ctx->img1.bit_depth; break; case IW_VAL_COMPRESSION: ret = ctx->req.compression; break; case IW_VAL_PAGE_TO_READ: ret = ctx->req.page_to_read; break; case IW_VAL_INCLUDE_SCREEN: ret = ctx->req.include_screen; break; case IW_VAL_OUTPUT_PALETTE_GRAYSCALE: ret = ctx->optctx.palette_is_grayscale; break; case IW_VAL_OUTPUT_INTERLACED: ret = ctx->req.interlaced; break; case IW_VAL_USE_BKGD_LABEL: ret = ctx->req.use_bkgd_label_from_file; break; case IW_VAL_BMP_NO_FILEHEADER: ret = ctx->req.bmp_no_fileheader; break; case IW_VAL_MAX_WIDTH: ret = ctx->max_width; break; case IW_VAL_MAX_HEIGHT: ret = ctx->max_height; break; case IW_VAL_PRECISION: ret = 32; break; case IW_VAL_NO_BKGD_LABEL: ret = ctx->req.suppress_output_bkgd_label; break; case IW_VAL_INTENT: ret = ctx->req.output_rendering_intent; break; case IW_VAL_OUTPUT_SAMPLE_TYPE: ret = ctx->req.output_sample_type; break; case IW_VAL_OUTPUT_FORMAT: ret = ctx->req.output_format; break; case IW_VAL_NEGATE_TARGET: ret = ctx->req.negate_target; break; } return ret; } IW_IMPL(void) iw_set_value_dbl(struct iw_context *ctx, int code, double n) { switch(code) { case IW_VAL_WEBP_QUALITY: // For backward compatibility only. iw_set_option(ctx, "webp:quality", iwpvt_strdup_dbl(ctx, n)); break; case IW_VAL_TRANSLATE_X: ctx->resize_settings[IW_DIMENSION_H].translate = n; break; case IW_VAL_TRANSLATE_Y: ctx->resize_settings[IW_DIMENSION_V].translate = n; break; } } IW_IMPL(double) iw_get_value_dbl(struct iw_context *ctx, int code) { double ret = 0.0; switch(code) { case IW_VAL_TRANSLATE_X: ret = ctx->resize_settings[IW_DIMENSION_H].translate; break; case IW_VAL_TRANSLATE_Y: ret = ctx->resize_settings[IW_DIMENSION_V].translate; break; } return ret; } IW_IMPL(void) iw_set_option(struct iw_context *ctx, const char *name, const char *val) { #define IW_MAX_OPTIONS 32 int i; if(val==NULL || val[0]=='\0') { // An empty value can be used to mean "turn on this option". // To make that easier, set such values to "1". val = "1"; } // Allocate req.options if that hasn't been done yet. if(!ctx->req.options) { ctx->req.options = iw_mallocz(ctx, IW_MAX_OPTIONS*sizeof(struct iw_option_struct)); if(!ctx->req.options) return; ctx->req.options_numalloc = IW_MAX_OPTIONS; ctx->req.options_count = 0; } // If option already exists, replace it. for(i=0; i<ctx->req.options_count; i++) { if(ctx->req.options[i].name && !strcmp(ctx->req.options[i].name, name)) { iw_free(ctx, ctx->req.options[i].val); ctx->req.options[i].val = iw_strdup(ctx, val); return; } } // Add the new option. if(ctx->req.options_count>=IW_MAX_OPTIONS) return; ctx->req.options[ctx->req.options_count].name = iw_strdup(ctx, name); ctx->req.options[ctx->req.options_count].val = iw_strdup(ctx, val); ctx->req.options_count++; } // Return the value of the first option with the given name. // Return NULL if not found. IW_IMPL(const char*) iw_get_option(struct iw_context *ctx, const char *name) { int i; for(i=0; i<ctx->req.options_count; i++) { if(ctx->req.options[i].name && !strcmp(ctx->req.options[i].name, name)) { return ctx->req.options[i].val; } } return NULL; }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_3367_0
crossvul-cpp_data_good_4853_1
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library. * Scanline-oriented Read Support */ #include "tiffiop.h" #include <stdio.h> #define TIFF_SIZE_T_MAX ((size_t) ~ ((size_t)0)) #define TIFF_TMSIZE_T_MAX (tmsize_t)(TIFF_SIZE_T_MAX >> 1) int TIFFFillStrip(TIFF* tif, uint32 strip); int TIFFFillTile(TIFF* tif, uint32 tile); static int TIFFStartStrip(TIFF* tif, uint32 strip); static int TIFFStartTile(TIFF* tif, uint32 tile); static int TIFFCheckRead(TIFF*, int); static tmsize_t TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size,const char* module); static tmsize_t TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module); #define NOSTRIP ((uint32)(-1)) /* undefined state */ #define NOTILE ((uint32)(-1)) /* undefined state */ static int TIFFFillStripPartial( TIFF *tif, int strip, tmsize_t read_ahead, int restart ) { static const char module[] = "TIFFFillStripPartial"; register TIFFDirectory *td = &tif->tif_dir; tmsize_t unused_data; uint64 read_offset; tmsize_t cc, to_read; /* tmsize_t bytecountm; */ if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; /* * Expand raw data buffer, if needed, to hold data * strip coming from file (perhaps should set upper * bound on the size of a buffer we'll use?). */ /* bytecountm=(tmsize_t) td->td_stripbytecount[strip]; */ if (read_ahead*2 > tif->tif_rawdatasize) { assert( restart ); tif->tif_curstrip = NOSTRIP; if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Data buffer too small to hold part of strip %lu", (unsigned long) strip); return (0); } if (!TIFFReadBufferSetup(tif, 0, read_ahead*2)) return (0); } if( restart ) { tif->tif_rawdataloaded = 0; tif->tif_rawdataoff = 0; } /* ** If we are reading more data, move any unused data to the ** start of the buffer. */ if( tif->tif_rawdataloaded > 0 ) unused_data = tif->tif_rawdataloaded - (tif->tif_rawcp - tif->tif_rawdata); else unused_data = 0; if( unused_data > 0 ) { assert((tif->tif_flags&TIFF_BUFFERMMAP)==0); memmove( tif->tif_rawdata, tif->tif_rawcp, unused_data ); } /* ** Seek to the point in the file where more data should be read. */ read_offset = td->td_stripoffset[strip] + tif->tif_rawdataoff + tif->tif_rawdataloaded; if (!SeekOK(tif, read_offset)) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at scanline %lu, strip %lu", (unsigned long) tif->tif_row, (unsigned long) strip); return 0; } /* ** How much do we want to read? */ to_read = tif->tif_rawdatasize - unused_data; if( (uint64) to_read > td->td_stripbytecount[strip] - tif->tif_rawdataoff - tif->tif_rawdataloaded ) { to_read = (tmsize_t) td->td_stripbytecount[strip] - tif->tif_rawdataoff - tif->tif_rawdataloaded; } assert((tif->tif_flags&TIFF_BUFFERMMAP)==0); cc = TIFFReadFile(tif, tif->tif_rawdata + unused_data, to_read); if (cc != to_read) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned __int64) cc, (unsigned __int64) to_read); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long long) cc, (unsigned long long) to_read); #endif return 0; } tif->tif_rawdataoff = tif->tif_rawdataoff + tif->tif_rawdataloaded - unused_data ; tif->tif_rawdataloaded = unused_data + to_read; tif->tif_rawcp = tif->tif_rawdata; if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) { assert((tif->tif_flags&TIFF_BUFFERMMAP)==0); TIFFReverseBits(tif->tif_rawdata + unused_data, to_read ); } /* ** When starting a strip from the beginning we need to ** restart the decoder. */ if( restart ) return TIFFStartStrip(tif, strip); else return 1; } /* * Seek to a random row+sample in a file. * * Only used by TIFFReadScanline, and is only used on * strip organized files. We do some tricky stuff to try * and avoid reading the whole compressed raw data for big * strips. */ static int TIFFSeek(TIFF* tif, uint32 row, uint16 sample ) { register TIFFDirectory *td = &tif->tif_dir; uint32 strip; int whole_strip; tmsize_t read_ahead = 0; /* ** Establish what strip we are working from. */ if (row >= td->td_imagelength) { /* out of range */ TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%lu: Row out of range, max %lu", (unsigned long) row, (unsigned long) td->td_imagelength); return (0); } if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { if (sample >= td->td_samplesperpixel) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "%lu: Sample out of range, max %lu", (unsigned long) sample, (unsigned long) td->td_samplesperpixel); return (0); } strip = (uint32)sample*td->td_stripsperimage + row/td->td_rowsperstrip; } else strip = row / td->td_rowsperstrip; /* * Do we want to treat this strip as one whole chunk or * read it a few lines at a time? */ #if defined(CHUNKY_STRIP_READ_SUPPORT) if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; whole_strip = tif->tif_dir.td_stripbytecount[strip] < 10 || isMapped(tif); #else whole_strip = 1; #endif if( !whole_strip ) { read_ahead = tif->tif_scanlinesize * 16 + 5000; } /* * If we haven't loaded this strip, do so now, possibly * only reading the first part. */ if (strip != tif->tif_curstrip) { /* different strip, refill */ if( whole_strip ) { if (!TIFFFillStrip(tif, strip)) return (0); } else { if( !TIFFFillStripPartial(tif,strip,read_ahead,1) ) return 0; } } /* ** If we already have some data loaded, do we need to read some more? */ else if( !whole_strip ) { if( ((tif->tif_rawdata + tif->tif_rawdataloaded) - tif->tif_rawcp) < read_ahead && (uint64) tif->tif_rawdataoff+tif->tif_rawdataloaded < td->td_stripbytecount[strip] ) { if( !TIFFFillStripPartial(tif,strip,read_ahead,0) ) return 0; } } if (row < tif->tif_row) { /* * Moving backwards within the same strip: backup * to the start and then decode forward (below). * * NB: If you're planning on lots of random access within a * strip, it's better to just read and decode the entire * strip, and then access the decoded data in a random fashion. */ if( tif->tif_rawdataoff != 0 ) { if( !TIFFFillStripPartial(tif,strip,read_ahead,1) ) return 0; } else { if (!TIFFStartStrip(tif, strip)) return (0); } } if (row != tif->tif_row) { /* * Seek forward to the desired row. */ /* TODO: Will this really work with partial buffers? */ if (!(*tif->tif_seek)(tif, row - tif->tif_row)) return (0); tif->tif_row = row; } return (1); } int TIFFReadScanline(TIFF* tif, void* buf, uint32 row, uint16 sample) { int e; if (!TIFFCheckRead(tif, 0)) return (-1); if( (e = TIFFSeek(tif, row, sample)) != 0) { /* * Decompress desired row into user buffer. */ e = (*tif->tif_decoderow) (tif, (uint8*) buf, tif->tif_scanlinesize, sample); /* we are now poised at the beginning of the next row */ tif->tif_row = row + 1; if (e) (*tif->tif_postdecode)(tif, (uint8*) buf, tif->tif_scanlinesize); } return (e > 0 ? 1 : -1); } /* * Read a strip of data and decompress the specified * amount into the user-supplied buffer. */ tmsize_t TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedStrip"; TIFFDirectory *td = &tif->tif_dir; uint32 rowsperstrip; uint32 stripsperplane; uint32 stripinplane; uint16 plane; uint32 rows; tmsize_t stripsize; if (!TIFFCheckRead(tif,0)) return((tmsize_t)(-1)); if (strip>=td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata,module, "%lu: Strip out of range, max %lu",(unsigned long)strip, (unsigned long)td->td_nstrips); return((tmsize_t)(-1)); } /* * Calculate the strip size according to the number of * rows in the strip (check for truncated last strip on any * of the separations). */ rowsperstrip=td->td_rowsperstrip; if (rowsperstrip>td->td_imagelength) rowsperstrip=td->td_imagelength; stripsperplane= TIFFhowmany_32_maxuint_compat(td->td_imagelength, rowsperstrip); stripinplane=(strip%stripsperplane); plane=(uint16)(strip/stripsperplane); rows=td->td_imagelength-stripinplane*rowsperstrip; if (rows>rowsperstrip) rows=rowsperstrip; stripsize=TIFFVStripSize(tif,rows); if (stripsize==0) return((tmsize_t)(-1)); /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE && size!=(tmsize_t)(-1) && size >= stripsize && !isMapped(tif) && ((tif->tif_flags&TIFF_NOREADRAW)==0) ) { if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize) return ((tmsize_t)(-1)); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(buf,stripsize); (*tif->tif_postdecode)(tif,buf,stripsize); return (stripsize); } if ((size!=(tmsize_t)(-1))&&(size<stripsize)) stripsize=size; if (!TIFFFillStrip(tif,strip)) return((tmsize_t)(-1)); if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0) return((tmsize_t)(-1)); (*tif->tif_postdecode)(tif,buf,stripsize); return(stripsize); } static tmsize_t TIFFReadRawStrip1(TIFF* tif, uint32 strip, void* buf, tmsize_t size, const char* module) { TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif )) return ((tmsize_t)(-1)); assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (!isMapped(tif)) { tmsize_t cc; if (!SeekOK(tif, td->td_stripoffset[strip])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at scanline %lu, strip %lu", (unsigned long) tif->tif_row, (unsigned long) strip); return ((tmsize_t)(-1)); } cc = TIFFReadFile(tif, buf, size); if (cc != size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned __int64) cc, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long long) cc, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } } else { tmsize_t ma,mb; tmsize_t n; ma=(tmsize_t)td->td_stripoffset[strip]; mb=ma+size; if ((td->td_stripoffset[strip] > (uint64)TIFF_TMSIZE_T_MAX)||(ma>tif->tif_size)) n=0; else if ((mb<ma)||(mb<size)||(mb>tif->tif_size)) n=tif->tif_size-ma; else n=size; if (n!=size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu, strip %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned long) strip, (unsigned __int64) n, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at scanline %lu, strip %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) strip, (unsigned long long) n, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } _TIFFmemcpy(buf, tif->tif_base + ma, size); } return (size); } /* * Read a strip of data from the file. */ tmsize_t TIFFReadRawStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadRawStrip"; TIFFDirectory *td = &tif->tif_dir; uint64 bytecount; tmsize_t bytecountm; if (!TIFFCheckRead(tif, 0)) return ((tmsize_t)(-1)); if (strip >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Strip out of range, max %lu", (unsigned long) strip, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } if (tif->tif_flags&TIFF_NOREADRAW) { TIFFErrorExt(tif->tif_clientdata, module, "Compression scheme does not support access to raw uncompressed data"); return ((tmsize_t)(-1)); } bytecount = td->td_stripbytecount[strip]; if ((int64)bytecount <= 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "%I64u: Invalid strip byte count, strip %lu", (unsigned __int64) bytecount, (unsigned long) strip); #else TIFFErrorExt(tif->tif_clientdata, module, "%llu: Invalid strip byte count, strip %lu", (unsigned long long) bytecount, (unsigned long) strip); #endif return ((tmsize_t)(-1)); } bytecountm = (tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata, module, "Integer overflow"); return ((tmsize_t)(-1)); } if (size != (tmsize_t)(-1) && size < bytecountm) bytecountm = size; return (TIFFReadRawStrip1(tif, strip, buf, bytecountm, module)); } /* * Read the specified strip and setup for decoding. The data buffer is * expanded, as necessary, to hold the strip's data. */ int TIFFFillStrip(TIFF* tif, uint32 strip) { static const char module[] = "TIFFFillStrip"; TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; if ((tif->tif_flags&TIFF_NOREADRAW)==0) { uint64 bytecount = td->td_stripbytecount[strip]; if ((int64)bytecount <= 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Invalid strip byte count %I64u, strip %lu", (unsigned __int64) bytecount, (unsigned long) strip); #else TIFFErrorExt(tif->tif_clientdata, module, "Invalid strip byte count %llu, strip %lu", (unsigned long long) bytecount, (unsigned long) strip); #endif return (0); } if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) || (tif->tif_flags & TIFF_NOBITREV))) { /* * The image is mapped into memory and we either don't * need to flip bits or the compression routine is * going to handle this operation itself. In this * case, avoid copying the raw data and instead just * reference the data from the memory mapped file * image. This assumes that the decompression * routines do not modify the contents of the raw data * buffer (if they try to, the application will get a * fault since the file is mapped read-only). */ if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) { _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; tif->tif_rawdatasize = 0; } tif->tif_flags &= ~TIFF_MYBUFFER; /* * We must check for overflow, potentially causing * an OOB read. Instead of simple * * td->td_stripoffset[strip]+bytecount > tif->tif_size * * comparison (which can overflow) we do the following * two comparisons: */ if (bytecount > (uint64)tif->tif_size || td->td_stripoffset[strip] > (uint64)tif->tif_size - bytecount) { /* * This error message might seem strange, but * it's what would happen if a read were done * instead. */ #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error on strip %lu; " "got %I64u bytes, expected %I64u", (unsigned long) strip, (unsigned __int64) tif->tif_size - td->td_stripoffset[strip], (unsigned __int64) bytecount); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error on strip %lu; " "got %llu bytes, expected %llu", (unsigned long) strip, (unsigned long long) tif->tif_size - td->td_stripoffset[strip], (unsigned long long) bytecount); #endif tif->tif_curstrip = NOSTRIP; return (0); } tif->tif_rawdatasize = (tmsize_t)bytecount; tif->tif_rawdata = tif->tif_base + (tmsize_t)td->td_stripoffset[strip]; tif->tif_rawdataoff = 0; tif->tif_rawdataloaded = (tmsize_t) bytecount; /* * When we have tif_rawdata reference directly into the memory mapped file * we need to be pretty careful about how we use the rawdata. It is not * a general purpose working buffer as it normally otherwise is. So we * keep track of this fact to avoid using it improperly. */ tif->tif_flags |= TIFF_BUFFERMMAP; } else { /* * Expand raw data buffer, if needed, to hold data * strip coming from file (perhaps should set upper * bound on the size of a buffer we'll use?). */ tmsize_t bytecountm; bytecountm=(tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return(0); } if (bytecountm > tif->tif_rawdatasize) { tif->tif_curstrip = NOSTRIP; if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Data buffer too small to hold strip %lu", (unsigned long) strip); return (0); } if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (tif->tif_flags&TIFF_BUFFERMMAP) { tif->tif_curstrip = NOSTRIP; if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (TIFFReadRawStrip1(tif, strip, tif->tif_rawdata, bytecountm, module) != bytecountm) return (0); tif->tif_rawdataoff = 0; tif->tif_rawdataloaded = bytecountm; if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(tif->tif_rawdata, bytecountm); } } return (TIFFStartStrip(tif, strip)); } /* * Tile-oriented Read Support * Contributed by Nancy Cam (Silicon Graphics). */ /* * Read and decompress a tile of data. The * tile is selected by the (x,y,z,s) coordinates. */ tmsize_t TIFFReadTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s) { if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s)) return ((tmsize_t)(-1)); return (TIFFReadEncodedTile(tif, TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1))); } /* * Read a tile of data and decompress the specified * amount into the user-supplied buffer. */ tmsize_t TIFFReadEncodedTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedTile"; TIFFDirectory *td = &tif->tif_dir; tmsize_t tilesize = tif->tif_tilesize; if (!TIFFCheckRead(tif, 1)) return ((tmsize_t)(-1)); if (tile >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Tile out of range, max %lu", (unsigned long) tile, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE && size!=(tmsize_t)(-1) && size >= tilesize && !isMapped(tif) && ((tif->tif_flags&TIFF_NOREADRAW)==0) ) { if (TIFFReadRawTile1(tif, tile, buf, tilesize, module) != tilesize) return ((tmsize_t)(-1)); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(buf,tilesize); (*tif->tif_postdecode)(tif,buf,tilesize); return (tilesize); } if (size == (tmsize_t)(-1)) size = tilesize; else if (size > tilesize) size = tilesize; if (TIFFFillTile(tif, tile) && (*tif->tif_decodetile)(tif, (uint8*) buf, size, (uint16)(tile/td->td_stripsperimage))) { (*tif->tif_postdecode)(tif, (uint8*) buf, size); return (size); } else return ((tmsize_t)(-1)); } static tmsize_t TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module) { TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif )) return ((tmsize_t)(-1)); assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (!isMapped(tif)) { tmsize_t cc; if (!SeekOK(tif, td->td_stripoffset[tile])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at row %lu, col %lu, tile %lu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile); return ((tmsize_t)(-1)); } cc = TIFFReadFile(tif, buf, size); if (cc != size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned __int64) cc, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long long) cc, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } } else { tmsize_t ma,mb; tmsize_t n; ma=(tmsize_t)td->td_stripoffset[tile]; mb=ma+size; if ((td->td_stripoffset[tile] > (uint64)TIFF_TMSIZE_T_MAX)||(ma>tif->tif_size)) n=0; else if ((mb<ma)||(mb<size)||(mb>tif->tif_size)) n=tif->tif_size-ma; else n=size; if (n!=size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu, tile %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile, (unsigned __int64) n, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu, tile %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile, (unsigned long long) n, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } _TIFFmemcpy(buf, tif->tif_base + ma, size); } return (size); } /* * Read a tile of data from the file. */ tmsize_t TIFFReadRawTile(TIFF* tif, uint32 tile, void* buf, tmsize_t size) { static const char module[] = "TIFFReadRawTile"; TIFFDirectory *td = &tif->tif_dir; uint64 bytecount64; tmsize_t bytecountm; if (!TIFFCheckRead(tif, 1)) return ((tmsize_t)(-1)); if (tile >= td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata, module, "%lu: Tile out of range, max %lu", (unsigned long) tile, (unsigned long) td->td_nstrips); return ((tmsize_t)(-1)); } if (tif->tif_flags&TIFF_NOREADRAW) { TIFFErrorExt(tif->tif_clientdata, module, "Compression scheme does not support access to raw uncompressed data"); return ((tmsize_t)(-1)); } bytecount64 = td->td_stripbytecount[tile]; if (size != (tmsize_t)(-1) && (uint64)size < bytecount64) bytecount64 = (uint64)size; bytecountm = (tmsize_t)bytecount64; if ((uint64)bytecountm!=bytecount64) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return ((tmsize_t)(-1)); } return (TIFFReadRawTile1(tif, tile, buf, bytecountm, module)); } /* * Read the specified tile and setup for decoding. The data buffer is * expanded, as necessary, to hold the tile's data. */ int TIFFFillTile(TIFF* tif, uint32 tile) { static const char module[] = "TIFFFillTile"; TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; if ((tif->tif_flags&TIFF_NOREADRAW)==0) { uint64 bytecount = td->td_stripbytecount[tile]; if ((int64)bytecount <= 0) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "%I64u: Invalid tile byte count, tile %lu", (unsigned __int64) bytecount, (unsigned long) tile); #else TIFFErrorExt(tif->tif_clientdata, module, "%llu: Invalid tile byte count, tile %lu", (unsigned long long) bytecount, (unsigned long) tile); #endif return (0); } if (isMapped(tif) && (isFillOrder(tif, td->td_fillorder) || (tif->tif_flags & TIFF_NOBITREV))) { /* * The image is mapped into memory and we either don't * need to flip bits or the compression routine is * going to handle this operation itself. In this * case, avoid copying the raw data and instead just * reference the data from the memory mapped file * image. This assumes that the decompression * routines do not modify the contents of the raw data * buffer (if they try to, the application will get a * fault since the file is mapped read-only). */ if ((tif->tif_flags & TIFF_MYBUFFER) && tif->tif_rawdata) { _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; tif->tif_rawdatasize = 0; } tif->tif_flags &= ~TIFF_MYBUFFER; /* * We must check for overflow, potentially causing * an OOB read. Instead of simple * * td->td_stripoffset[tile]+bytecount > tif->tif_size * * comparison (which can overflow) we do the following * two comparisons: */ if (bytecount > (uint64)tif->tif_size || td->td_stripoffset[tile] > (uint64)tif->tif_size - bytecount) { tif->tif_curtile = NOTILE; return (0); } tif->tif_rawdatasize = (tmsize_t)bytecount; tif->tif_rawdata = tif->tif_base + (tmsize_t)td->td_stripoffset[tile]; tif->tif_rawdataoff = 0; tif->tif_rawdataloaded = (tmsize_t) bytecount; tif->tif_flags |= TIFF_BUFFERMMAP; } else { /* * Expand raw data buffer, if needed, to hold data * tile coming from file (perhaps should set upper * bound on the size of a buffer we'll use?). */ tmsize_t bytecountm; bytecountm=(tmsize_t)bytecount; if ((uint64)bytecountm!=bytecount) { TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); return(0); } if (bytecountm > tif->tif_rawdatasize) { tif->tif_curtile = NOTILE; if ((tif->tif_flags & TIFF_MYBUFFER) == 0) { TIFFErrorExt(tif->tif_clientdata, module, "Data buffer too small to hold tile %lu", (unsigned long) tile); return (0); } if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (tif->tif_flags&TIFF_BUFFERMMAP) { tif->tif_curtile = NOTILE; if (!TIFFReadBufferSetup(tif, 0, bytecountm)) return (0); } if (TIFFReadRawTile1(tif, tile, tif->tif_rawdata, bytecountm, module) != bytecountm) return (0); tif->tif_rawdataoff = 0; tif->tif_rawdataloaded = bytecountm; if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(tif->tif_rawdata, tif->tif_rawdataloaded); } } return (TIFFStartTile(tif, tile)); } /* * Setup the raw data buffer in preparation for * reading a strip of raw data. If the buffer * is specified as zero, then a buffer of appropriate * size is allocated by the library. Otherwise, * the client must guarantee that the buffer is * large enough to hold any individual strip of * raw data. */ int TIFFReadBufferSetup(TIFF* tif, void* bp, tmsize_t size) { static const char module[] = "TIFFReadBufferSetup"; assert((tif->tif_flags&TIFF_NOREADRAW)==0); tif->tif_flags &= ~TIFF_BUFFERMMAP; if (tif->tif_rawdata) { if (tif->tif_flags & TIFF_MYBUFFER) _TIFFfree(tif->tif_rawdata); tif->tif_rawdata = NULL; tif->tif_rawdatasize = 0; } if (bp) { tif->tif_rawdatasize = size; tif->tif_rawdata = (uint8*) bp; tif->tif_flags &= ~TIFF_MYBUFFER; } else { tif->tif_rawdatasize = (tmsize_t)TIFFroundup_64((uint64)size, 1024); if (tif->tif_rawdatasize==0) { TIFFErrorExt(tif->tif_clientdata, module, "Invalid buffer size"); return (0); } tif->tif_rawdata = (uint8*) _TIFFmalloc(tif->tif_rawdatasize); tif->tif_flags |= TIFF_MYBUFFER; } if (tif->tif_rawdata == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "No space for data buffer at scanline %lu", (unsigned long) tif->tif_row); tif->tif_rawdatasize = 0; return (0); } return (1); } /* * Set state to appear as if a * strip has just been read in. */ static int TIFFStartStrip(TIFF* tif, uint32 strip) { TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupdecode)(tif)) return (0); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_curstrip = strip; tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip; tif->tif_flags &= ~TIFF_BUF4WRITE; if (tif->tif_flags&TIFF_NOREADRAW) { tif->tif_rawcp = NULL; tif->tif_rawcc = 0; } else { tif->tif_rawcp = tif->tif_rawdata; tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[strip]; } return ((*tif->tif_predecode)(tif, (uint16)(strip / td->td_stripsperimage))); } /* * Set state to appear as if a * tile has just been read in. */ static int TIFFStartTile(TIFF* tif, uint32 tile) { static const char module[] = "TIFFStartTile"; TIFFDirectory *td = &tif->tif_dir; uint32 howmany32; if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) return 0; if ((tif->tif_flags & TIFF_CODERSETUP) == 0) { if (!(*tif->tif_setupdecode)(tif)) return (0); tif->tif_flags |= TIFF_CODERSETUP; } tif->tif_curtile = tile; howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth); if (howmany32 == 0) { TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles"); return 0; } tif->tif_row = (tile % howmany32) * td->td_tilelength; howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength); if (howmany32 == 0) { TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles"); return 0; } tif->tif_col = (tile % howmany32) * td->td_tilewidth; tif->tif_flags &= ~TIFF_BUF4WRITE; if (tif->tif_flags&TIFF_NOREADRAW) { tif->tif_rawcp = NULL; tif->tif_rawcc = 0; } else { tif->tif_rawcp = tif->tif_rawdata; tif->tif_rawcc = (tmsize_t)td->td_stripbytecount[tile]; } return ((*tif->tif_predecode)(tif, (uint16)(tile/td->td_stripsperimage))); } static int TIFFCheckRead(TIFF* tif, int tiles) { if (tif->tif_mode == O_WRONLY) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, "File not open for reading"); return (0); } if (tiles ^ isTiled(tif)) { TIFFErrorExt(tif->tif_clientdata, tif->tif_name, tiles ? "Can not read tiles from a stripped image" : "Can not read scanlines from a tiled image"); return (0); } return (1); } void _TIFFNoPostDecode(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; (void) buf; (void) cc; } void _TIFFSwab16BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 1) == 0); TIFFSwabArrayOfShort((uint16*) buf, cc/2); } void _TIFFSwab24BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc % 3) == 0); TIFFSwabArrayOfTriples((uint8*) buf, cc/3); } void _TIFFSwab32BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 3) == 0); TIFFSwabArrayOfLong((uint32*) buf, cc/4); } void _TIFFSwab64BitData(TIFF* tif, uint8* buf, tmsize_t cc) { (void) tif; assert((cc & 7) == 0); TIFFSwabArrayOfDouble((double*) buf, cc/8); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-369/c/good_4853_1
crossvul-cpp_data_bad_4413_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % L AAA Y Y EEEEE RRRR % % L A A Y Y E R R % % L AAAAA Y EEE RRRR % % L A A Y E R R % % LLLLL A A Y EEEEE R R % % % % MagickCore Image Layering Methods % % % % Software Design % % Cristy % % Anthony Thyssen % % January 2006 % % % % % % Copyright 1999-2020 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://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/artifact.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/composite.h" #include "MagickCore/effect.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/profile.h" #include "MagickCore/resource_.h" #include "MagickCore/resize.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l e a r B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClearBounds() Clear the area specified by the bounds in an image to % transparency. This typically used to handle Background Disposal for the % previous frame in an animation sequence. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % void ClearBounds(Image *image,RectangleInfo *bounds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to had the area cleared in % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static void ClearBounds(Image *image,RectangleInfo *bounds, ExceptionInfo *exception) { ssize_t y; if (bounds->x < 0) return; if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); for (y=0; y < (ssize_t) bounds->height; y++) { register ssize_t x; register Quantum *magick_restrict q; q=GetAuthenticPixels(image,bounds->x,bounds->y+y,bounds->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) bounds->width; x++) { SetPixelAlpha(image,TransparentAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s B o u n d s C l e a r e d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsBoundsCleared() tests whether any pixel in the bounds given, gets cleared % when going from the first image to the second image. This typically used % to check if a proposed disposal method will work successfully to generate % the second frame image from the first disposed form of the previous frame. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % MagickBooleanType IsBoundsCleared(const Image *image1, % const Image *image2,RectangleInfo bounds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image1, image 2: the images to check for cleared pixels % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsBoundsCleared(const Image *image1, const Image *image2,RectangleInfo *bounds,ExceptionInfo *exception) { register const Quantum *p, *q; register ssize_t x; ssize_t y; if (bounds->x < 0) return(MagickFalse); for (y=0; y < (ssize_t) bounds->height; y++) { p=GetVirtualPixels(image1,bounds->x,bounds->y+y,bounds->width,1,exception); q=GetVirtualPixels(image2,bounds->x,bounds->y+y,bounds->width,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) bounds->width; x++) { if ((GetPixelAlpha(image1,p) >= (Quantum) (QuantumRange/2)) && (GetPixelAlpha(image2,q) < (Quantum) (QuantumRange/2))) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) bounds->width) break; } return(y < (ssize_t) bounds->height ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o a l e s c e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CoalesceImages() composites a set of images while respecting any page % offsets and disposal methods. GIF, MIFF, and MNG animation sequences % typically start with an image background and each subsequent image % varies in size and offset. A new image sequence is returned with all % images the same size as the first images virtual canvas and composited % with the next image in the sequence. % % The format of the CoalesceImages method is: % % Image *CoalesceImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CoalesceImages(const Image *image,ExceptionInfo *exception) { Image *coalesce_image, *dispose_image, *previous; register Image *next; RectangleInfo bounds; /* Coalesce the image sequence. */ 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); next=GetFirstImageInList(image); bounds=next->page; if (bounds.width == 0) { bounds.width=next->columns; if (bounds.x > 0) bounds.width+=bounds.x; } if (bounds.height == 0) { bounds.height=next->rows; if (bounds.y > 0) bounds.height+=bounds.y; } bounds.x=0; bounds.y=0; coalesce_image=CloneImage(next,bounds.width,bounds.height,MagickTrue, exception); if (coalesce_image == (Image *) NULL) return((Image *) NULL); coalesce_image->background_color.alpha_trait=BlendPixelTrait; coalesce_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(coalesce_image,exception); coalesce_image->alpha_trait=next->alpha_trait; coalesce_image->page=bounds; coalesce_image->dispose=NoneDispose; /* Coalesce rest of the images. */ dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); if (dispose_image == (Image *) NULL) { coalesce_image=DestroyImage(coalesce_image); return((Image *) NULL); } dispose_image->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(coalesce_image,next,CopyCompositeOp,MagickTrue, next->page.x,next->page.y,exception); next=GetNextImageInList(next); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { const char *attribute; /* Determine the bounds that was overlaid in the previous image. */ previous=GetPreviousImageInList(next); bounds=previous->page; bounds.width=previous->columns; bounds.height=previous->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) coalesce_image->columns) bounds.width=coalesce_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) coalesce_image->rows) bounds.height=coalesce_image->rows-bounds.y; /* Replace the dispose image with the new coalesced image. */ if (GetPreviousImageInList(next)->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); if (dispose_image == (Image *) NULL) { coalesce_image=DestroyImageList(coalesce_image); return((Image *) NULL); } dispose_image->background_color.alpha_trait=BlendPixelTrait; } /* Clear the overlaid area of the coalesced bounds for background disposal */ if (next->previous->dispose == BackgroundDispose) ClearBounds(dispose_image,&bounds,exception); /* Next image is the dispose image, overlaid with next frame in sequence. */ coalesce_image->next=CloneImage(dispose_image,0,0,MagickTrue,exception); coalesce_image->next->previous=coalesce_image; previous=coalesce_image; coalesce_image=GetNextImageInList(coalesce_image); coalesce_image->background_color.alpha_trait=BlendPixelTrait; attribute=GetImageProperty(next,"webp:mux-blend",exception); if (attribute == (const char *) NULL) (void) CompositeImage(coalesce_image,next, next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp,MagickTrue,next->page.x,next->page.y,exception); else (void) CompositeImage(coalesce_image,next, LocaleCompare(attribute,"AtopBackgroundAlphaBlend") == 0 ? OverCompositeOp : CopyCompositeOp,MagickTrue,next->page.x,next->page.y, exception); (void) CloneImageProfiles(coalesce_image,next); (void) CloneImageProperties(coalesce_image,next); (void) CloneImageArtifacts(coalesce_image,next); coalesce_image->page=previous->page; /* If a pixel goes opaque to transparent, use background dispose. */ if (IsBoundsCleared(previous,coalesce_image,&bounds,exception) != MagickFalse) coalesce_image->dispose=BackgroundDispose; else coalesce_image->dispose=NoneDispose; previous->dispose=coalesce_image->dispose; } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(coalesce_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D i s p o s e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisposeImages() returns the coalesced frames of a GIF animation as it would % appear after the GIF dispose method of that frame has been applied. That is % it returned the appearance of each frame before the next is overlaid. % % The format of the DisposeImages method is: % % Image *DisposeImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *DisposeImages(const Image *images,ExceptionInfo *exception) { Image *dispose_image, *dispose_images; RectangleInfo bounds; register Image *image, *next; /* Run the image through the animation sequence */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(images); dispose_image=CloneImage(image,image->page.width,image->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return((Image *) NULL); dispose_image->page=image->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.alpha_trait=BlendPixelTrait; dispose_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(dispose_image,exception); dispose_images=NewImageList(); for (next=image; image != (Image *) NULL; image=GetNextImageInList(image)) { Image *current_image; /* Overlay this frame's image over the previous disposal image. */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } current_image->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(current_image,next, next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp, MagickTrue,next->page.x,next->page.y,exception); /* Handle Background dispose: image is displayed for the delay period. */ if (next->dispose == BackgroundDispose) { bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds,exception); } /* Select the appropriate previous/disposed image. */ if (next->dispose == PreviousDispose) current_image=DestroyImage(current_image); else { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; current_image=(Image *) NULL; } /* Save the dispose image just calculated for return. */ { Image *dispose; dispose=CloneImage(dispose_image,0,0,MagickTrue,exception); if (dispose == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } dispose_image->background_color.alpha_trait=BlendPixelTrait; (void) CloneImageProfiles(dispose,next); (void) CloneImageProperties(dispose,next); (void) CloneImageArtifacts(dispose,next); dispose->page.x=0; dispose->page.y=0; dispose->dispose=next->dispose; AppendImageToList(&dispose_images,dispose); } } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(dispose_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComparePixels() Compare the two pixels and return true if the pixels % differ according to the given LayerType comparision method. % % This currently only used internally by CompareImagesBounds(). It is % doubtful that this sub-routine will be useful outside this module. % % The format of the ComparePixels method is: % % MagickBooleanType *ComparePixels(const LayerMethod method, % const PixelInfo *p,const PixelInfo *q) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o p, q: the pixels to test for appropriate differences. % */ static MagickBooleanType ComparePixels(const LayerMethod method, const PixelInfo *p,const PixelInfo *q) { double o1, o2; /* Any change in pixel values */ if (method == CompareAnyLayer) return(IsFuzzyEquivalencePixelInfo(p,q) == MagickFalse ? MagickTrue : MagickFalse); o1 = (p->alpha_trait != UndefinedPixelTrait) ? p->alpha : OpaqueAlpha; o2 = (q->alpha_trait != UndefinedPixelTrait) ? q->alpha : OpaqueAlpha; /* Pixel goes from opaque to transprency. */ if (method == CompareClearLayer) return((MagickBooleanType) ( (o1 >= ((double) QuantumRange/2.0)) && (o2 < ((double) QuantumRange/2.0)) ) ); /* Overlay would change first pixel by second. */ if (method == CompareOverlayLayer) { if (o2 < ((double) QuantumRange/2.0)) return MagickFalse; return(IsFuzzyEquivalencePixelInfo(p,q) == MagickFalse ? MagickTrue : MagickFalse); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e I m a g e B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImagesBounds() Given two images return the smallest rectangular area % by which the two images differ, accourding to the given 'Compare...' % layer method. % % This currently only used internally in this module, but may eventually % be used by other modules. % % The format of the CompareImagesBounds method is: % % RectangleInfo *CompareImagesBounds(const LayerMethod method, % const Image *image1,const Image *image2,ExceptionInfo *exception) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of CompareAnyLayer, % CompareClearLayer, CompareOverlayLayer. % % o image1, image2: the two images to compare. % % o exception: return any errors or warnings in this structure. % */ static RectangleInfo CompareImagesBounds(const Image *image1, const Image *image2,const LayerMethod method,ExceptionInfo *exception) { RectangleInfo bounds; PixelInfo pixel1, pixel2; register const Quantum *p, *q; register ssize_t x; ssize_t y; /* Set bounding box of the differences between images. */ GetPixelInfo(image1,&pixel1); GetPixelInfo(image2,&pixel2); for (x=0; x < (ssize_t) image1->columns; x++) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (y=0; y < (ssize_t) image1->rows; y++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (y < (ssize_t) image1->rows) break; } if (x >= (ssize_t) image1->columns) { /* Images are identical, return a null image. */ bounds.x=-1; bounds.y=-1; bounds.width=1; bounds.height=1; return(bounds); } bounds.x=x; for (x=(ssize_t) image1->columns-1; x >= 0; x--) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (y=0; y < (ssize_t) image1->rows; y++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (y < (ssize_t) image1->rows) break; } bounds.width=(size_t) (x-bounds.x+1); for (y=0; y < (ssize_t) image1->rows; y++) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image1->columns; x++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) image1->columns) break; } bounds.y=y; for (y=(ssize_t) image1->rows-1; y >= 0; y--) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image1->columns; x++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) image1->columns) break; } bounds.height=(size_t) (y-bounds.y+1); return(bounds); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p a r e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImagesLayers() compares each image with the next in a sequence and % returns the minimum bounding region of all the pixel differences (of the % LayerMethod specified) it discovers. % % Images do NOT have to be the same size, though it is best that all the % images are 'coalesced' (images are all the same size, on a flattened % canvas, so as to represent exactly how an specific frame should look). % % No GIF dispose methods are applied, so GIF animations must be coalesced % before applying this image operator to find differences to them. % % The format of the CompareImagesLayers method is: % % Image *CompareImagesLayers(const Image *images, % const LayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers type to compare images with. Must be one of... % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CompareImagesLayers(const Image *image, const LayerMethod method,ExceptionInfo *exception) { Image *image_a, *image_b, *layers; RectangleInfo *bounds; register const Image *next; register ssize_t i; assert(image != (const 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); assert((method == CompareAnyLayer) || (method == CompareClearLayer) || (method == CompareOverlayLayer)); /* Allocate bounds memory. */ next=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(next),sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Set up first comparision images. */ image_a=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (image_a == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_a->background_color.alpha_trait=BlendPixelTrait; image_a->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(image_a,exception); image_a->page=next->page; image_a->page.x=0; image_a->page.y=0; (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); /* Compute the bounding box of changes for the later images */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { image_b=CloneImage(image_a,0,0,MagickTrue,exception); if (image_b == (Image *) NULL) { image_a=DestroyImage(image_a); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_b->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); bounds[i]=CompareImagesBounds(image_b,image_a,method,exception); image_b=DestroyImage(image_b); i++; } image_a=DestroyImage(image_a); /* Clone first image in sequence. */ next=GetFirstImageInList(image); layers=CloneImage(next,0,0,MagickTrue,exception); if (layers == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } layers->background_color.alpha_trait=BlendPixelTrait; /* Deconstruct the image sequence. */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { if ((bounds[i].x == -1) && (bounds[i].y == -1) && (bounds[i].width == 1) && (bounds[i].height == 1)) { /* An empty frame is returned from CompareImageBounds(), which means the current frame is identical to the previous frame. */ i++; continue; } image_a=CloneImage(next,0,0,MagickTrue,exception); if (image_a == (Image *) NULL) break; image_a->background_color.alpha_trait=BlendPixelTrait; image_b=CropImage(image_a,&bounds[i],exception); image_a=DestroyImage(image_a); if (image_b == (Image *) NULL) break; AppendImageToList(&layers,image_b); i++; } bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); if (next != (Image *) NULL) { layers=DestroyImageList(layers); return((Image *) NULL); } return(GetFirstImageInList(layers)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p t i m i z e L a y e r F r a m e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeLayerFrames() takes a coalesced GIF animation, and compares each % frame against the three different 'disposal' forms of the previous frame. % From this it then attempts to select the smallest cropped image and % disposal method needed to reproduce the resulting image. % % Note that this not easy, and may require the expansion of the bounds % of previous frame, simply clear pixels for the next animation frame to % transparency according to the selected dispose method. % % The format of the OptimizeLayerFrames method is: % % Image *OptimizeLayerFrames(const Image *image, % const LayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers technique to optimize with. Must be one of... % OptimizeImageLayer, or OptimizePlusLayer. The Plus form allows % the addition of extra 'zero delay' frames to clear pixels from % the previous frame, and the removal of frames that done change, % merging the delay times together. % % o exception: return any errors or warnings in this structure. % */ /* Define a 'fake' dispose method where the frame is duplicated, (for OptimizePlusLayer) with a extra zero time delay frame which does a BackgroundDisposal to clear the pixels that need to be cleared. */ #define DupDispose ((DisposeType)9) /* Another 'fake' dispose method used to removed frames that don't change. */ #define DelDispose ((DisposeType)8) #define DEBUG_OPT_FRAME 0 static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method, ExceptionInfo *exception) { ExceptionInfo *sans_exception; Image *prev_image, *dup_image, *bgnd_image, *optimized_image; RectangleInfo try_bounds, bgnd_bounds, dup_bounds, *bounds; MagickBooleanType add_frames, try_cleared, cleared; DisposeType *disposals; register const Image *curr; register ssize_t i; assert(image != (const 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); assert(method == OptimizeLayer || method == OptimizeImageLayer || method == OptimizePlusLayer); /* Are we allowed to add/remove frames from animation? */ add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse; /* Ensure all the images are the same size. */ curr=GetFirstImageInList(image); for (; curr != (Image *) NULL; curr=GetNextImageInList(curr)) { if ((curr->columns != image->columns) || (curr->rows != image->rows)) ThrowImageException(OptionError,"ImagesAreNotTheSameSize"); if ((curr->page.x != 0) || (curr->page.y != 0) || (curr->page.width != image->page.width) || (curr->page.height != image->page.height)) ThrowImageException(OptionError,"ImagePagesAreNotCoalesced"); } /* Allocate memory (times 2 if we allow the use of frame duplications) */ curr=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); disposals=(DisposeType *) AcquireQuantumMemory((size_t) GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*disposals)); if (disposals == (DisposeType *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialise Previous Image as fully transparent */ prev_image=CloneImage(curr,curr->columns,curr->rows,MagickTrue,exception); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */ prev_image->page.x=0; prev_image->page.y=0; prev_image->dispose=NoneDispose; prev_image->background_color.alpha_trait=BlendPixelTrait; prev_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(prev_image,exception); /* Figure out the area of overlay of the first frame No pixel could be cleared as all pixels are already cleared. */ #if DEBUG_OPT_FRAME i=0; (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif disposals[0]=NoneDispose; bounds[0]=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g\n\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); #endif /* Compute the bounding box of changes for each pair of images. */ i=1; bgnd_image=(Image *) NULL; dup_image=(Image *) NULL; dup_bounds.width=0; dup_bounds.height=0; dup_bounds.x=0; dup_bounds.y=0; curr=GetNextImageInList(curr); for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr)) { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif /* Assume none disposal is the best */ bounds[i]=CompareImagesBounds(curr->previous,curr,CompareAnyLayer,exception); cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception); disposals[i-1]=NoneDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g%s%s\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y, bounds[i].x < 0?" (unchanged)":"", cleared?" (pixels cleared)":""); #endif if ( bounds[i].x < 0 ) { /* Image frame is exactly the same as the previous frame! If not adding frames leave it to be cropped down to a null image. Otherwise mark previous image for deleted, transfering its crop bounds to the current image. */ if ( add_frames && i>=2 ) { disposals[i-1]=DelDispose; disposals[i]=NoneDispose; bounds[i]=bounds[i-1]; i++; continue; } } else { /* Compare a none disposal against a previous disposal */ try_bounds=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "test_prev: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels were cleared)":""); #endif if ( (!try_cleared && cleared ) || try_bounds.width * try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=try_cleared; bounds[i]=try_bounds; disposals[i-1]=PreviousDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"previous: accepted\n"); } else { (void) FormatLocaleFile(stderr,"previous: rejected\n"); #endif } /* If we are allowed lets try a complex frame duplication. It is useless if the previous image already clears pixels correctly. This method will always clear all the pixels that need to be cleared. */ dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */ if ( add_frames ) { dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (dup_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); return((Image *) NULL); } dup_image->background_color.alpha_trait=BlendPixelTrait; dup_bounds=CompareImagesBounds(dup_image,curr,CompareClearLayer,exception); ClearBounds(dup_image,&dup_bounds,exception); try_bounds=CompareImagesBounds(dup_image,curr,CompareAnyLayer,exception); if ( cleared || dup_bounds.width*dup_bounds.height +try_bounds.width*try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=MagickFalse; bounds[i]=try_bounds; disposals[i-1]=DupDispose; /* to be finalised later, if found to be optimial */ } else dup_bounds.width=dup_bounds.height=0; } /* Now compare against a simple background disposal */ bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (bgnd_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); return((Image *) NULL); } bgnd_image->background_color.alpha_trait=BlendPixelTrait; bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */ ClearBounds(bgnd_image,&bgnd_bounds,exception); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "background: %s\n", try_cleared?"(pixels cleared)":""); #endif if ( try_cleared ) { /* Straight background disposal failed to clear pixels needed! Lets try expanding the disposal area of the previous frame, to include the pixels that are cleared. This guaranteed to work, though may not be the most optimized solution. */ try_bounds=CompareImagesBounds(curr->previous,curr,CompareClearLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_clear: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_bounds.x<0?" (no expand nessary)":""); #endif if ( bgnd_bounds.x < 0 ) bgnd_bounds = try_bounds; else { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_bgnd: %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif if ( try_bounds.x < bgnd_bounds.x ) { bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; bgnd_bounds.x = try_bounds.x; } else { try_bounds.width += try_bounds.x - bgnd_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; } if ( try_bounds.y < bgnd_bounds.y ) { bgnd_bounds.height += bgnd_bounds.y - try_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; bgnd_bounds.y = try_bounds.y; } else { try_bounds.height += try_bounds.y - bgnd_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; } #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, " to : %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif } ClearBounds(bgnd_image,&bgnd_bounds,exception); #if DEBUG_OPT_FRAME /* Something strange is happening with a specific animation * CompareAnyLayers (normal method) and CompareClearLayers returns the whole * image, which is not posibly correct! As verified by previous tests. * Something changed beyond the bgnd_bounds clearing. But without being able * to see, or writet he image at this point it is hard to tell what is wrong! * Only CompareOverlay seemed to return something sensible. */ try_bounds=CompareImagesBounds(bgnd_image,curr,CompareClearLayer,exception); (void) FormatLocaleFile(stderr, "expand_ctst: %.20gx%.20g%+.20g%+.20g\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y ); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_any : %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif try_bounds=CompareImagesBounds(bgnd_image,curr,CompareOverlayLayer,exception); #if DEBUG_OPT_FRAME try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_test: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif } /* Test if this background dispose is smaller than any of the other methods we tryed before this (including duplicated frame) */ if ( cleared || bgnd_bounds.width*bgnd_bounds.height +try_bounds.width*try_bounds.height < bounds[i-1].width*bounds[i-1].height +dup_bounds.width*dup_bounds.height +bounds[i].width*bounds[i].height ) { cleared=MagickFalse; bounds[i-1]=bgnd_bounds; bounds[i]=try_bounds; if ( disposals[i-1] == DupDispose ) dup_image=DestroyImage(dup_image); disposals[i-1]=BackgroundDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"expand_bgnd: accepted\n"); } else { (void) FormatLocaleFile(stderr,"expand_bgnd: reject\n"); #endif } } /* Finalise choice of dispose, set new prev_image, and junk any extra images as appropriate, */ if ( disposals[i-1] == DupDispose ) { if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); prev_image=DestroyImage(prev_image); prev_image=dup_image, dup_image=(Image *) NULL; bounds[i+1]=bounds[i]; bounds[i]=dup_bounds; disposals[i-1]=DupDispose; disposals[i]=BackgroundDispose; i++; } else { if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); if ( disposals[i-1] != PreviousDispose ) prev_image=DestroyImage(prev_image); if ( disposals[i-1] == BackgroundDispose ) prev_image=bgnd_image, bgnd_image=(Image *) NULL; if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); if ( disposals[i-1] == NoneDispose ) { prev_image=ReferenceImage(curr->previous); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } } } assert(prev_image != (Image *) NULL); disposals[i]=disposals[i-1]; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "final %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i-1, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]), (double) bounds[i-1].width,(double) bounds[i-1].height, (double) bounds[i-1].x,(double) bounds[i-1].y ); #endif #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "interum %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]), (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); (void) FormatLocaleFile(stderr,"\n"); #endif i++; } prev_image=DestroyImage(prev_image); /* Optimize all images in sequence. */ sans_exception=AcquireExceptionInfo(); i=0; curr=GetFirstImageInList(image); optimized_image=NewImageList(); while ( curr != (const Image *) NULL ) { prev_image=CloneImage(curr,0,0,MagickTrue,exception); if (prev_image == (Image *) NULL) break; prev_image->background_color.alpha_trait=BlendPixelTrait; if ( disposals[i] == DelDispose ) { size_t time = 0; while ( disposals[i] == DelDispose ) { time += curr->delay*1000/curr->ticks_per_second; curr=GetNextImageInList(curr); i++; } time += curr->delay*1000/curr->ticks_per_second; prev_image->ticks_per_second = 100L; prev_image->delay = time*prev_image->ticks_per_second/1000; } bgnd_image=CropImage(prev_image,&bounds[i],sans_exception); prev_image=DestroyImage(prev_image); if (bgnd_image == (Image *) NULL) break; bgnd_image->dispose=disposals[i]; if ( disposals[i] == DupDispose ) { bgnd_image->delay=0; bgnd_image->dispose=NoneDispose; } else curr=GetNextImageInList(curr); AppendImageToList(&optimized_image,bgnd_image); i++; } sans_exception=DestroyExceptionInfo(sans_exception); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); if (curr != (Image *) NULL) { optimized_image=DestroyImageList(optimized_image); return((Image *) NULL); } return(GetFirstImageInList(optimized_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageLayers() compares each image the GIF disposed forms of the % previous image in the sequence. From this it attempts to select the % smallest cropped image to replace each frame, while preserving the results % of the GIF animation. % % The format of the OptimizeImageLayers method is: % % Image *OptimizeImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizeImageLayers(const Image *image, ExceptionInfo *exception) { return(OptimizeLayerFrames(image,OptimizeImageLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e P l u s I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImagePlusLayers() is exactly as OptimizeImageLayers(), but may % also add or even remove extra frames in the animation, if it improves % the total number of pixels in the resulting GIF animation. % % The format of the OptimizePlusImageLayers method is: % % Image *OptimizePlusImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizePlusImageLayers(const Image *image, ExceptionInfo *exception) { return OptimizeLayerFrames(image,OptimizePlusLayer,exception); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e T r a n s p a r e n c y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageTransparency() takes a frame optimized GIF animation, and % compares the overlayed pixels against the disposal image resulting from all % the previous frames in the animation. Any pixel that does not change the % disposal image (and thus does not effect the outcome of an overlay) is made % transparent. % % WARNING: This modifies the current images directly, rather than generate % a new image sequence. % % The format of the OptimizeImageTransperency method is: % % void OptimizeImageTransperency(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence % % o exception: return any errors or warnings in this structure. % */ MagickExport void OptimizeImageTransparency(const Image *image, ExceptionInfo *exception) { Image *dispose_image; register Image *next; /* Run the image through the animation sequence */ 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); next=GetFirstImageInList(image); dispose_image=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return; dispose_image->page=next->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.alpha_trait=BlendPixelTrait; dispose_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(dispose_image,exception); while ( next != (Image *) NULL ) { Image *current_image; /* Overlay this frame's image over the previous disposal image */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_image=DestroyImage(dispose_image); return; } current_image->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(current_image,next,next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp,MagickTrue,next->page.x,next->page.y, exception); /* At this point the image would be displayed, for the delay period ** Work out the disposal of the previous image */ if (next->dispose == BackgroundDispose) { RectangleInfo bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds,exception); } if (next->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; } else current_image=DestroyImage(current_image); /* Optimize Transparency of the next frame (if present) */ next=GetNextImageInList(next); if (next != (Image *) NULL) { (void) CompositeImage(next,dispose_image,ChangeMaskCompositeOp, MagickTrue,-(next->page.x),-(next->page.y),exception); } } dispose_image=DestroyImage(dispose_image); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e D u p l i c a t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveDuplicateLayers() removes any image that is exactly the same as the % next image in the given image list. Image size and virtual canvas offset % must also match, though not the virtual canvas size itself. % % No check is made with regards to image disposal setting, though it is the % dispose setting of later image that is kept. Also any time delays are also % added together. As such coalesced image animations should still produce the % same result, though with duplicte frames merged into a single frame. % % The format of the RemoveDuplicateLayers method is: % % void RemoveDuplicateLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception) { RectangleInfo bounds; register Image *image, *next; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(*images); for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next) { if ((image->columns != next->columns) || (image->rows != next->rows) || (image->page.x != next->page.x) || (image->page.y != next->page.y)) continue; bounds=CompareImagesBounds(image,next,CompareAnyLayer,exception); if (bounds.x < 0) { /* Two images are the same, merge time delays and delete one. */ size_t time; time=(size_t) (1000.0*image->delay* PerceptibleReciprocal((double) image->ticks_per_second)); time+=(size_t) (1000.0*next->delay* PerceptibleReciprocal((double) next->ticks_per_second)); next->ticks_per_second=100L; next->delay=time*image->ticks_per_second/1000; next->iterations=image->iterations; *images=image; (void) DeleteImageFromList(images); } } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e Z e r o D e l a y L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveZeroDelayLayers() removes any image that as a zero delay time. Such % images generally represent intermediate or partial updates in GIF % animations used for file optimization. They are not ment to be displayed % to users of the animation. Viewable images in an animation should have a % time delay of 3 or more centi-seconds (hundredths of a second). % % However if all the frames have a zero time delay, then either the animation % is as yet incomplete, or it is not a GIF animation. This a non-sensible % situation, so no image will be removed and a 'Zero Time Animation' warning % (exception) given. % % No warning will be given if no image was removed because all images had an % appropriate non-zero time delay set. % % Due to the special requirements of GIF disposal handling, GIF animations % should be coalesced first, before calling this function, though that is not % a requirement. % % The format of the RemoveZeroDelayLayers method is: % % void RemoveZeroDelayLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveZeroDelayLayers(Image **images, ExceptionInfo *exception) { Image *i; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); i=GetFirstImageInList(*images); for ( ; i != (Image *) NULL; i=GetNextImageInList(i)) if ( i->delay != 0L ) break; if ( i == (Image *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ZeroTimeAnimation","`%s'",GetFirstImageInList(*images)->filename); return; } i=GetFirstImageInList(*images); while ( i != (Image *) NULL ) { if ( i->delay == 0L ) { (void) DeleteImageFromList(&i); *images=i; } else i=GetNextImageInList(i); } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeLayers() compose the source image sequence over the destination % image sequence, starting with the current image in both lists. % % Each layer from the two image lists are composted together until the end of % one of the image lists is reached. The offset of each composition is also % adjusted to match the virtual canvas offsets of each layer. As such the % given offset is relative to the virtual canvas, and not the actual image. % % Composition uses given x and y offsets, as the 'origin' location of the % source images virtual canvas (not the real image) allowing you to compose a % list of 'layer images' into the destiantioni images. This makes it well % sutiable for directly composing 'Clears Frame Animations' or 'Coaleased % Animations' onto a static or other 'Coaleased Animation' destination image % list. GIF disposal handling is not looked at. % % Special case:- If one of the image sequences is the last image (just a % single image remaining), that image is repeatally composed with all the % images in the other image list. Either the source or destination lists may % be the single image, for this situation. % % In the case of a single destination image (or last image given), that image % will ve cloned to match the number of images remaining in the source image % list. % % This is equivelent to the "-layer Composite" Shell API operator. % % % The format of the CompositeLayers method is: % % void CompositeLayers(Image *destination, const CompositeOperator % compose, Image *source, const ssize_t x_offset, const ssize_t y_offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o destination: the destination images and results % % o source: source image(s) for the layer composition % % o compose, x_offset, y_offset: arguments passed on to CompositeImages() % % o exception: return any errors or warnings in this structure. % */ static inline void CompositeCanvas(Image *destination, const CompositeOperator compose,Image *source,ssize_t x_offset, ssize_t y_offset,ExceptionInfo *exception) { const char *value; x_offset+=source->page.x-destination->page.x; y_offset+=source->page.y-destination->page.y; value=GetImageArtifact(source,"compose:outside-overlay"); (void) CompositeImage(destination,source,compose, (value != (const char *) NULL) && (IsStringTrue(value) != MagickFalse) ? MagickFalse : MagickTrue,x_offset,y_offset,exception); } MagickExport void CompositeLayers(Image *destination, const CompositeOperator compose, Image *source,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { assert(destination != (Image *) NULL); assert(destination->signature == MagickCoreSignature); assert(source != (Image *) NULL); assert(source->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (source->debug != MagickFalse || destination->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s - %s", source->filename,destination->filename); /* Overlay single source image over destation image/list */ if ( source->next == (Image *) NULL ) while ( destination != (Image *) NULL ) { CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); destination=GetNextImageInList(destination); } /* Overlay source image list over single destination. Multiple clones of destination image are created to match source list. Original Destination image becomes first image of generated list. As such the image list pointer does not require any change in caller. Some animation attributes however also needs coping in this case. */ else if ( destination->next == (Image *) NULL ) { Image *dest = CloneImage(destination,0,0,MagickTrue,exception); if (dest != (Image *) NULL) { dest->background_color.alpha_trait=BlendPixelTrait; CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); /* copy source image attributes ? */ if ( source->next != (Image *) NULL ) { destination->delay=source->delay; destination->iterations=source->iterations; } source=GetNextImageInList(source); while (source != (Image *) NULL) { AppendImageToList(&destination, CloneImage(dest,0,0,MagickTrue,exception)); destination->background_color.alpha_trait=BlendPixelTrait; destination=GetLastImageInList(destination); CompositeCanvas(destination,compose,source,x_offset,y_offset, exception); destination->delay=source->delay; destination->iterations=source->iterations; source=GetNextImageInList(source); } dest=DestroyImage(dest); } } /* Overlay a source image list over a destination image list until either list runs out of images. (Does not repeat) */ else while ( source != (Image *) NULL && destination != (Image *) NULL ) { CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); source=GetNextImageInList(source); destination=GetNextImageInList(destination); } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e r g e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MergeImageLayers() composes all the image layers from the current given % image onward to produce a single image of the merged layers. % % The inital canvas's size depends on the given LayerMethod, and is % initialized using the first images background color. The images % are then compositied onto that image in sequence using the given % composition that has been assigned to each individual image. % % The format of the MergeImageLayers is: % % Image *MergeImageLayers(Image *image,const LayerMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image list to be composited together % % o method: the method of selecting the size of the initial canvas. % % MergeLayer: Merge all layers onto a canvas just large enough % to hold all the actual images. The virtual canvas of the % first image is preserved but otherwise ignored. % % FlattenLayer: Use the virtual canvas size of first image. % Images which fall outside this canvas is clipped. % This can be used to 'fill out' a given virtual canvas. % % MosaicLayer: Start with the virtual canvas of the first image, % enlarging left and right edges to contain all images. % Images with negative offsets will be clipped. % % TrimBoundsLayer: Determine the overall bounds of all the image % layers just as in "MergeLayer", then adjust the canvas % and offsets to be relative to those bounds, without overlaying % the images. % % WARNING: a new image is not returned, the original image % sequence page data is modified instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MergeImageLayers(Image *image,const LayerMethod method, ExceptionInfo *exception) { #define MergeLayersTag "Merge/Layers" Image *canvas; MagickBooleanType proceed; RectangleInfo page; register const Image *next; size_t number_images, height, width; ssize_t scene; 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); /* Determine canvas image size, and its virtual canvas size and offset */ page=image->page; width=image->columns; height=image->rows; switch (method) { case TrimBoundsLayer: case MergeLayer: default: { next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (page.x > next->page.x) { width+=page.x-next->page.x; page.x=next->page.x; } if (page.y > next->page.y) { height+=page.y-next->page.y; page.y=next->page.y; } if ((ssize_t) width < (next->page.x+(ssize_t) next->columns-page.x)) width=(size_t) next->page.x+(ssize_t) next->columns-page.x; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows-page.y)) height=(size_t) next->page.y+(ssize_t) next->rows-page.y; } break; } case FlattenLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; page.x=0; page.y=0; break; } case MosaicLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { if (method == MosaicLayer) { page.x=next->page.x; page.y=next->page.y; if ((ssize_t) width < (next->page.x+(ssize_t) next->columns)) width=(size_t) next->page.x+next->columns; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows)) height=(size_t) next->page.y+next->rows; } } page.width=width; page.height=height; page.x=0; page.y=0; } break; } /* Set virtual canvas size if not defined. */ if (page.width == 0) page.width=page.x < 0 ? width : width+page.x; if (page.height == 0) page.height=page.y < 0 ? height : height+page.y; /* Handle "TrimBoundsLayer" method separately to normal 'layer merge'. */ if (method == TrimBoundsLayer) { number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { image->page.x-=page.x; image->page.y-=page.y; image->page.width=width; image->page.height=height; proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return((Image *) NULL); } /* Create canvas size of width and height, and background color. */ canvas=CloneImage(image,width,height,MagickTrue,exception); if (canvas == (Image *) NULL) return((Image *) NULL); canvas->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(canvas,exception); canvas->page=page; canvas->dispose=UndefinedDispose; /* Compose images onto canvas, with progress monitor */ number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { (void) CompositeImage(canvas,image,image->compose,MagickTrue,image->page.x- canvas->page.x,image->page.y-canvas->page.y,exception); proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return(canvas); }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_4413_0
crossvul-cpp_data_bad_2580_0
/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* vim: set sw=4 sts=4 expandtab: */ /* rsvg-filter.c: Provides filters Copyright (C) 2004 Caleb Moore This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Author: Caleb Moore <c.moore@student.unsw.edu.au> */ #include "config.h" #include "rsvg-private.h" #include "rsvg-filter.h" #include "rsvg-styles.h" #include "rsvg-image.h" #include "rsvg-css.h" #include "rsvg-cairo-render.h" #include <string.h> #include <math.h> /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveOutput RsvgFilterPrimitiveOutput; struct _RsvgFilterPrimitiveOutput { cairo_surface_t *surface; RsvgIRect bounds; }; typedef struct _RsvgFilterContext RsvgFilterContext; struct _RsvgFilterContext { gint width, height; RsvgFilter *filter; GHashTable *results; cairo_surface_t *source_surface; cairo_surface_t *bg_surface; RsvgFilterPrimitiveOutput lastresult; cairo_matrix_t affine; cairo_matrix_t paffine; int channelmap[4]; RsvgDrawingCtx *ctx; }; typedef struct _RsvgFilterPrimitive RsvgFilterPrimitive; /* We don't have real subclassing here. If you derive something from * RsvgFilterPrimitive, and don't need any special code to free your * RsvgFilterPrimitiveFoo structure, you can just pass rsvg_filter_primitive_free * to rsvg_rust_cnode_new() for the destructor. Otherwise, create a custom destructor like this: * * static void * rsvg_filter_primitive_foo_free (gpointer impl) * { * RsvgFilterPrimitiveFoo *foo = impl; * * g_free (foo->my_custom_stuff); * g_free (foo->more_custom_stuff); * ... etc ... * * rsvg_filter_primitive_free (impl); * } * * That last call to rsvg_filter_primitive_free() will free the base RsvgFilterPrimitive's own fields, * and your whole structure itself, via g_free(). */ struct _RsvgFilterPrimitive { RsvgLength x, y, width, height; gboolean x_specified; gboolean y_specified; gboolean width_specified; gboolean height_specified; GString *in; GString *result; void (*render) (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx); }; /*************************************************************/ /*************************************************************/ static void rsvg_filter_primitive_free (gpointer impl) { RsvgFilterPrimitive *primitive = impl; g_string_free (primitive->in, TRUE); g_string_free (primitive->result, TRUE); g_free (primitive); } static void filter_primitive_set_x_y_width_height_atts (RsvgFilterPrimitive *prim, RsvgPropertyBag *atts) { const char *value; if ((value = rsvg_property_bag_lookup (atts, "x"))) { prim->x = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); prim->x_specified = TRUE; } if ((value = rsvg_property_bag_lookup (atts, "y"))) { prim->y = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); prim->y_specified = TRUE; } if ((value = rsvg_property_bag_lookup (atts, "width"))) { prim->width = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); prim->width_specified = TRUE; } if ((value = rsvg_property_bag_lookup (atts, "height"))) { prim->height = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); prim->height_specified = TRUE; } } static void rsvg_filter_primitive_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { primitive->render (node, primitive, ctx); } static RsvgIRect rsvg_filter_primitive_get_bounds (RsvgFilterPrimitive * self, RsvgFilterContext * ctx) { RsvgBbox box, otherbox; cairo_matrix_t affine; cairo_matrix_init_identity (&affine); rsvg_bbox_init (&box, &affine); rsvg_bbox_init (&otherbox, &ctx->affine); otherbox.virgin = 0; if (ctx->filter->filterunits == objectBoundingBox) rsvg_drawing_ctx_push_view_box (ctx->ctx, 1., 1.); otherbox.rect.x = rsvg_length_normalize (&ctx->filter->x, ctx->ctx); otherbox.rect.y = rsvg_length_normalize (&ctx->filter->y, ctx->ctx); otherbox.rect.width = rsvg_length_normalize (&ctx->filter->width, ctx->ctx); otherbox.rect.height = rsvg_length_normalize (&ctx->filter->height, ctx->ctx); if (ctx->filter->filterunits == objectBoundingBox) rsvg_drawing_ctx_pop_view_box (ctx->ctx); rsvg_bbox_insert (&box, &otherbox); if (self != NULL) { if (self->x_specified || self->y_specified || self->width_specified || self->height_specified) { rsvg_bbox_init (&otherbox, &ctx->paffine); otherbox.virgin = 0; if (ctx->filter->primitiveunits == objectBoundingBox) rsvg_drawing_ctx_push_view_box (ctx->ctx, 1., 1.); if (self->x_specified) otherbox.rect.x = rsvg_length_normalize (&self->x, ctx->ctx); else otherbox.rect.x = 0; if (self->y_specified) otherbox.rect.y = rsvg_length_normalize (&self->y, ctx->ctx); else otherbox.rect.y = 0; if (self->width_specified || self->height_specified) { double curr_vbox_w, curr_vbox_h; rsvg_drawing_ctx_get_view_box_size (ctx->ctx, &curr_vbox_w, &curr_vbox_h); if (self->width_specified) otherbox.rect.width = rsvg_length_normalize (&self->width, ctx->ctx); else otherbox.rect.width = curr_vbox_w; if (self->height_specified) otherbox.rect.height = rsvg_length_normalize (&self->height, ctx->ctx); else otherbox.rect.height = curr_vbox_h; } if (ctx->filter->primitiveunits == objectBoundingBox) rsvg_drawing_ctx_pop_view_box (ctx->ctx); rsvg_bbox_clip (&box, &otherbox); } } rsvg_bbox_init (&otherbox, &affine); otherbox.virgin = 0; otherbox.rect.x = 0; otherbox.rect.y = 0; otherbox.rect.width = ctx->width; otherbox.rect.height = ctx->height; rsvg_bbox_clip (&box, &otherbox); { RsvgIRect output = { box.rect.x, box.rect.y, box.rect.x + box.rect.width, box.rect.y + box.rect.height }; return output; } } static cairo_surface_t * _rsvg_image_surface_new (int width, int height) { cairo_surface_t *surface; surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); if (cairo_surface_status (surface) != CAIRO_STATUS_SUCCESS) { cairo_surface_destroy (surface); return NULL; } return surface; } static guchar get_interp_pixel (guchar * src, gdouble ox, gdouble oy, guchar ch, RsvgIRect boundarys, guint rowstride) { double xmod, ymod; double dist1, dist2, dist3, dist4; double c, c1, c2, c3, c4; double fox, foy, cox, coy; xmod = fmod (ox, 1.0); ymod = fmod (oy, 1.0); dist1 = (1 - xmod) * (1 - ymod); dist2 = (xmod) * (1 - ymod); dist3 = (xmod) * (ymod); dist4 = (1 - xmod) * (ymod); fox = floor (ox); foy = floor (oy); cox = ceil (ox); coy = ceil (oy); if (fox <= boundarys.x0 || fox >= boundarys.x1 || foy <= boundarys.y0 || foy >= boundarys.y1) c1 = 0; else c1 = src[(guint) foy * rowstride + (guint) fox * 4 + ch]; if (cox <= boundarys.x0 || cox >= boundarys.x1 || foy <= boundarys.y0 || foy >= boundarys.y1) c2 = 0; else c2 = src[(guint) foy * rowstride + (guint) cox * 4 + ch]; if (cox <= boundarys.x0 || cox >= boundarys.x1 || coy <= boundarys.y0 || coy >= boundarys.y1) c3 = 0; else c3 = src[(guint) coy * rowstride + (guint) cox * 4 + ch]; if (fox <= boundarys.x0 || fox >= boundarys.x1 || coy <= boundarys.y0 || coy >= boundarys.y1) c4 = 0; else c4 = src[(guint) coy * rowstride + (guint) fox * 4 + ch]; c = (c1 * dist1 + c2 * dist2 + c3 * dist3 + c4 * dist4) / (dist1 + dist2 + dist3 + dist4); return (guchar) c; } static void rsvg_filter_fix_coordinate_system (RsvgFilterContext * ctx, RsvgState * state, RsvgBbox *bbox) { int x, y, height, width; x = bbox->rect.x; y = bbox->rect.y; width = bbox->rect.width; height = bbox->rect.height; ctx->width = cairo_image_surface_get_width (ctx->source_surface); ctx->height = cairo_image_surface_get_height (ctx->source_surface); ctx->affine = state->affine; if (ctx->filter->filterunits == objectBoundingBox) { cairo_matrix_t affine; cairo_matrix_init (&affine, width, 0, 0, height, x, y); cairo_matrix_multiply (&ctx->affine, &affine, &ctx->affine); } ctx->paffine = state->affine; if (ctx->filter->primitiveunits == objectBoundingBox) { cairo_matrix_t affine; cairo_matrix_init (&affine, width, 0, 0, height, x, y); cairo_matrix_multiply (&ctx->paffine, &affine, &ctx->paffine); } } static gboolean rectangle_intersect (gint ax, gint ay, gint awidth, gint aheight, gint bx, gint by, gint bwidth, gint bheight, gint *rx, gint *ry, gint *rwidth, gint *rheight) { gint rx1, ry1, rx2, ry2; rx1 = MAX (ax, bx); ry1 = MAX (ay, by); rx2 = MIN (ax + awidth, bx + bwidth); ry2 = MIN (ay + aheight, by + bheight); if (rx2 > rx1 && ry2 > ry1) { *rx = rx1; *ry = ry1; *rwidth = rx2 - rx1; *rheight = ry2 - ry1; return TRUE; } else { *rx = *ry = *rwidth = *rheight = 0; return FALSE; } } static void rsvg_alpha_blt (cairo_surface_t *src, gint srcx, gint srcy, gint srcwidth, gint srcheight, cairo_surface_t *dst, gint dstx, gint dsty) { gint src_surf_width, src_surf_height; gint dst_surf_width, dst_surf_height; gint src_clipped_x, src_clipped_y, src_clipped_width, src_clipped_height; gint dst_clipped_x, dst_clipped_y, dst_clipped_width, dst_clipped_height; gint x, y, srcrowstride, dstrowstride, sx, sy, dx, dy; guchar *src_pixels, *dst_pixels; g_assert (cairo_image_surface_get_format (src) == CAIRO_FORMAT_ARGB32); g_assert (cairo_image_surface_get_format (dst) == CAIRO_FORMAT_ARGB32); cairo_surface_flush (src); src_surf_width = cairo_image_surface_get_width (src); src_surf_height = cairo_image_surface_get_height (src); dst_surf_width = cairo_image_surface_get_width (dst); dst_surf_height = cairo_image_surface_get_height (dst); if (!rectangle_intersect (0, 0, src_surf_width, src_surf_height, srcx, srcy, srcwidth, srcheight, &src_clipped_x, &src_clipped_y, &src_clipped_width, &src_clipped_height)) return; /* source rectangle is not in source surface */ if (!rectangle_intersect (0, 0, dst_surf_width, dst_surf_height, dstx, dsty, src_clipped_width, src_clipped_height, &dst_clipped_x, &dst_clipped_y, &dst_clipped_width, &dst_clipped_height)) return; /* dest rectangle is not in dest surface */ srcrowstride = cairo_image_surface_get_stride (src); dstrowstride = cairo_image_surface_get_stride (dst); src_pixels = cairo_image_surface_get_data (src); dst_pixels = cairo_image_surface_get_data (dst); for (y = 0; y < dst_clipped_height; y++) for (x = 0; x < dst_clipped_width; x++) { guint a, c, ad, cd, ar, cr, i; sx = x + src_clipped_x; sy = y + src_clipped_y; dx = x + dst_clipped_x; dy = y + dst_clipped_y; a = src_pixels[4 * sx + sy * srcrowstride + 3]; if (a) { ad = dst_pixels[4 * dx + dy * dstrowstride + 3]; ar = a + ad * (255 - a) / 255; dst_pixels[4 * dx + dy * dstrowstride + 3] = ar; for (i = 0; i < 3; i++) { c = src_pixels[4 * sx + sy * srcrowstride + i]; cd = dst_pixels[4 * dx + dy * dstrowstride + i]; cr = c + cd * (255 - a) / 255; dst_pixels[4 * dx + dy * dstrowstride + i] = cr; } } } cairo_surface_mark_dirty (dst); } static gboolean rsvg_art_affine_image (cairo_surface_t *img, cairo_surface_t *intermediate, cairo_matrix_t *affine, double w, double h) { cairo_matrix_t inv_affine, raw_inv_affine; gint intstride; gint basestride; gint basex, basey; gdouble fbasex, fbasey; gdouble rawx, rawy; guchar *intpix; guchar *basepix; gint i, j, k, basebpp, ii, jj; gboolean has_alpha; gdouble pixsum[4]; gboolean xrunnoff, yrunnoff; gint iwidth, iheight; gint width, height; g_assert (cairo_image_surface_get_format (intermediate) == CAIRO_FORMAT_ARGB32); cairo_surface_flush (img); width = cairo_image_surface_get_width (img); height = cairo_image_surface_get_height (img); iwidth = cairo_image_surface_get_width (intermediate); iheight = cairo_image_surface_get_height (intermediate); has_alpha = cairo_image_surface_get_format (img) == CAIRO_FORMAT_ARGB32; basestride = cairo_image_surface_get_stride (img); intstride = cairo_image_surface_get_stride (intermediate); basepix = cairo_image_surface_get_data (img); intpix = cairo_image_surface_get_data (intermediate); basebpp = has_alpha ? 4 : 3; raw_inv_affine = *affine; if (cairo_matrix_invert (&raw_inv_affine) != CAIRO_STATUS_SUCCESS) return FALSE; cairo_matrix_init_scale (&inv_affine, w, h); cairo_matrix_multiply (&inv_affine, &inv_affine, affine); if (cairo_matrix_invert (&inv_affine) != CAIRO_STATUS_SUCCESS) return FALSE; /*apply the transformation */ for (i = 0; i < iwidth; i++) for (j = 0; j < iheight; j++) { fbasex = (inv_affine.xx * (double) i + inv_affine.xy * (double) j + inv_affine.x0) * (double) width; fbasey = (inv_affine.yx * (double) i + inv_affine.yy * (double) j + inv_affine.y0) * (double) height; basex = floor (fbasex); basey = floor (fbasey); rawx = raw_inv_affine.xx * i + raw_inv_affine.xy * j + raw_inv_affine.x0; rawy = raw_inv_affine.yx * i + raw_inv_affine.yy * j + raw_inv_affine.y0; if (rawx < 0 || rawy < 0 || rawx >= w || rawy >= h || basex < 0 || basey < 0 || basex >= width || basey >= height) { for (k = 0; k < 4; k++) intpix[i * 4 + j * intstride + k] = 0; } else { if (basex < 0 || basex + 1 >= width) xrunnoff = TRUE; else xrunnoff = FALSE; if (basey < 0 || basey + 1 >= height) yrunnoff = TRUE; else yrunnoff = FALSE; for (k = 0; k < basebpp; k++) pixsum[k] = 0; for (ii = 0; ii < 2; ii++) for (jj = 0; jj < 2; jj++) { if (basex + ii < 0 || basey + jj < 0 || basex + ii >= width || basey + jj >= height); else { for (k = 0; k < basebpp; k++) { pixsum[k] += (double) basepix[basebpp * (basex + ii) + (basey + jj) * basestride + k] * (xrunnoff ? 1 : fabs (fbasex - (double) (basex + (1 - ii)))) * (yrunnoff ? 1 : fabs (fbasey - (double) (basey + (1 - jj)))); } } } for (k = 0; k < basebpp; k++) intpix[i * 4 + j * intstride + k] = pixsum[k]; if (!has_alpha) intpix[i * 4 + j * intstride + 3] = 255; } } /* Don't need cairo_surface_mark_dirty(intermediate) here since * the only caller does further work and then calls that himself. */ return TRUE; } static void rsvg_filter_free_pair (gpointer value) { RsvgFilterPrimitiveOutput *output; output = (RsvgFilterPrimitiveOutput *) value; cairo_surface_destroy (output->surface); g_free (output); } static void rsvg_filter_context_free (RsvgFilterContext * ctx) { if (!ctx) return; if (ctx->bg_surface) cairo_surface_destroy (ctx->bg_surface); g_free (ctx); } static gboolean node_is_filter_primitive (RsvgNode *node) { RsvgNodeType type = rsvg_node_get_type (node); return type > RSVG_NODE_TYPE_FILTER_PRIMITIVE_FIRST && type < RSVG_NODE_TYPE_FILTER_PRIMITIVE_LAST; } static gboolean render_child_if_filter_primitive (RsvgNode *node, gpointer data) { RsvgFilterContext *filter_ctx = data; if (node_is_filter_primitive (node)) { RsvgFilterPrimitive *primitive; primitive = rsvg_rust_cnode_get_impl (node); rsvg_filter_primitive_render (node, primitive, filter_ctx); } return TRUE; } /** * rsvg_filter_render: * @node: a pointer to the filter node to use * @source: the a #cairo_surface_t of type %CAIRO_SURFACE_TYPE_IMAGE * @context: the context * * Create a new surface applied the filter. This function will create * a context for itself, set up the coordinate systems execute all its * little primatives and then clean up its own mess. * * Returns: (transfer full): a new #cairo_surface_t **/ cairo_surface_t * rsvg_filter_render (RsvgNode *filter_node, cairo_surface_t *source, RsvgDrawingCtx *context, RsvgBbox *bounds, char *channelmap) { RsvgFilter *filter; RsvgFilterContext *ctx; guint i; cairo_surface_t *output; g_return_val_if_fail (source != NULL, NULL); g_return_val_if_fail (cairo_surface_get_type (source) == CAIRO_SURFACE_TYPE_IMAGE, NULL); g_assert (rsvg_node_get_type (filter_node) == RSVG_NODE_TYPE_FILTER); filter = rsvg_rust_cnode_get_impl (filter_node); ctx = g_new0 (RsvgFilterContext, 1); ctx->filter = filter; ctx->source_surface = source; ctx->bg_surface = NULL; ctx->results = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, rsvg_filter_free_pair); ctx->ctx = context; rsvg_filter_fix_coordinate_system (ctx, rsvg_current_state (context), bounds); ctx->lastresult.surface = cairo_surface_reference (source); ctx->lastresult.bounds = rsvg_filter_primitive_get_bounds (NULL, ctx); for (i = 0; i < 4; i++) ctx->channelmap[i] = channelmap[i] - '0'; rsvg_node_foreach_child (filter_node, render_child_if_filter_primitive, ctx); output = ctx->lastresult.surface; g_hash_table_destroy (ctx->results); rsvg_filter_context_free (ctx); return output; } /** * rsvg_filter_store_result: * @name: The name of the result * @result: The pointer to the result * @ctx: the context that this was called in * * Puts the new result into the hash for easy finding later, also * Stores it as the last result **/ static void rsvg_filter_store_output (GString * name, RsvgFilterPrimitiveOutput result, RsvgFilterContext * ctx) { RsvgFilterPrimitiveOutput *store; cairo_surface_destroy (ctx->lastresult.surface); store = g_new0 (RsvgFilterPrimitiveOutput, 1); *store = result; if (name->str[0] != '\0') { cairo_surface_reference (result.surface); /* increments the references for the table */ g_hash_table_insert (ctx->results, g_strdup (name->str), store); } cairo_surface_reference (result.surface); /* increments the references for the last result */ ctx->lastresult = result; } static void rsvg_filter_store_result (GString * name, cairo_surface_t *surface, RsvgFilterContext * ctx) { RsvgFilterPrimitiveOutput output; output.bounds.x0 = 0; output.bounds.y0 = 0; output.bounds.x1 = ctx->width; output.bounds.y1 = ctx->height; output.surface = surface; rsvg_filter_store_output (name, output, ctx); } static cairo_surface_t * surface_get_alpha (cairo_surface_t *source, RsvgFilterContext * ctx) { guchar *data; guchar *pbdata; gsize i, pbsize; cairo_surface_t *surface; if (source == NULL) return NULL; cairo_surface_flush (source); pbsize = cairo_image_surface_get_width (source) * cairo_image_surface_get_height (source); surface = _rsvg_image_surface_new (cairo_image_surface_get_width (source), cairo_image_surface_get_height (source)); if (surface == NULL) return NULL; data = cairo_image_surface_get_data (surface); pbdata = cairo_image_surface_get_data (source); /* FIXMEchpe: rewrite this into nested width, height loops */ for (i = 0; i < pbsize; i++) data[i * 4 + ctx->channelmap[3]] = pbdata[i * 4 + ctx->channelmap[3]]; cairo_surface_mark_dirty (surface); return surface; } static cairo_surface_t * rsvg_compile_bg (RsvgDrawingCtx * ctx) { RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render); cairo_surface_t *surface; cairo_t *cr; GList *i; surface = _rsvg_image_surface_new (render->width, render->height); if (surface == NULL) return NULL; cr = cairo_create (surface); for (i = g_list_last (render->cr_stack); i != NULL; i = g_list_previous (i)) { cairo_t *draw = i->data; gboolean nest = draw != render->initial_cr; cairo_set_source_surface (cr, cairo_get_target (draw), nest ? 0 : -render->offset_x, nest ? 0 : -render->offset_y); cairo_paint (cr); } cairo_destroy (cr); return surface; } /** * rsvg_filter_get_bg: * * Returns: (transfer none) (nullable): a #cairo_surface_t, or %NULL */ static cairo_surface_t * rsvg_filter_get_bg (RsvgFilterContext * ctx) { if (!ctx->bg_surface) ctx->bg_surface = rsvg_compile_bg (ctx->ctx); return ctx->bg_surface; } /* FIXMEchpe: proper return value and out param! */ /** * rsvg_filter_get_result: * @name: The name of the surface * @ctx: the context that this was called in * * Gets a surface for a primitive * * Returns: (nullable): a pointer to the result that the name refers to, a special * surface if the name is a special keyword or %NULL if nothing was found **/ static RsvgFilterPrimitiveOutput rsvg_filter_get_result (GString * name, RsvgFilterContext * ctx) { RsvgFilterPrimitiveOutput output; RsvgFilterPrimitiveOutput *outputpointer; output.bounds.x0 = output.bounds.x1 = output.bounds.y0 = output.bounds.y1 = 0; if (!strcmp (name->str, "SourceGraphic")) { output.surface = cairo_surface_reference (ctx->source_surface); return output; } else if (!strcmp (name->str, "BackgroundImage")) { output.surface = rsvg_filter_get_bg (ctx); if (output.surface) cairo_surface_reference (output.surface); return output; } else if (!strcmp (name->str, "") || !strcmp (name->str, "none")) { output = ctx->lastresult; cairo_surface_reference (output.surface); return output; } else if (!strcmp (name->str, "SourceAlpha")) { output.surface = surface_get_alpha (ctx->source_surface, ctx); return output; } else if (!strcmp (name->str, "BackgroundAlpha")) { output.surface = surface_get_alpha (rsvg_filter_get_bg (ctx), ctx); return output; } outputpointer = (RsvgFilterPrimitiveOutput *) (g_hash_table_lookup (ctx->results, name->str)); if (outputpointer != NULL) { output = *outputpointer; cairo_surface_reference (output.surface); return output; } /* g_warning (_("%s not found\n"), name->str); */ output = ctx->lastresult; cairo_surface_reference (output.surface); return output; } /** * rsvg_filter_get_in: * @name: * @ctx: * * Returns: (transfer full) (nullable): a new #cairo_surface_t, or %NULL */ static cairo_surface_t * rsvg_filter_get_in (GString * name, RsvgFilterContext * ctx) { return rsvg_filter_get_result (name, ctx).surface; } static void rsvg_filter_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilter *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "filterUnits"))) { if (!strcmp (value, "userSpaceOnUse")) filter->filterunits = userSpaceOnUse; else filter->filterunits = objectBoundingBox; } if ((value = rsvg_property_bag_lookup (atts, "primitiveUnits"))) { if (!strcmp (value, "objectBoundingBox")) filter->primitiveunits = objectBoundingBox; else filter->primitiveunits = userSpaceOnUse; } if ((value = rsvg_property_bag_lookup (atts, "x"))) filter->x = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); if ((value = rsvg_property_bag_lookup (atts, "y"))) filter->y = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); if ((value = rsvg_property_bag_lookup (atts, "width"))) filter->width = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); if ((value = rsvg_property_bag_lookup (atts, "height"))) filter->height = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); } static void rsvg_filter_draw (RsvgNode *node, gpointer impl, RsvgDrawingCtx *ctx, int dominate) { /* nothing; filters are drawn in rsvg-cairo-draw.c */ } static void rsvg_filter_free (gpointer impl) { RsvgFilter *filter = impl; g_free (filter); } /** * rsvg_new_filter: * * Creates a blank filter and assigns default values to everything **/ RsvgNode * rsvg_new_filter (const char *element_name, RsvgNode *parent) { RsvgFilter *filter; filter = g_new0 (RsvgFilter, 1); filter->filterunits = objectBoundingBox; filter->primitiveunits = userSpaceOnUse; filter->x = rsvg_length_parse ("-10%", LENGTH_DIR_HORIZONTAL); filter->y = rsvg_length_parse ("-10%", LENGTH_DIR_VERTICAL); filter->width = rsvg_length_parse ("120%", LENGTH_DIR_HORIZONTAL); filter->height = rsvg_length_parse ("120%", LENGTH_DIR_VERTICAL); return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER, parent, rsvg_state_new (), filter, rsvg_filter_set_atts, rsvg_filter_draw, rsvg_filter_free); } /*************************************************************/ /*************************************************************/ typedef enum { normal, multiply, screen, darken, lighten, softlight, hardlight, colordodge, colorburn, overlay, exclusion, difference } RsvgFilterPrimitiveBlendMode; typedef struct _RsvgFilterPrimitiveBlend RsvgFilterPrimitiveBlend; struct _RsvgFilterPrimitiveBlend { RsvgFilterPrimitive super; RsvgFilterPrimitiveBlendMode mode; GString *in2; }; static void rsvg_filter_blend (RsvgFilterPrimitiveBlendMode mode, cairo_surface_t *in, cairo_surface_t *in2, cairo_surface_t* output, RsvgIRect boundarys, int *channelmap) { guchar i; gint x, y; gint rowstride, rowstride2, rowstrideo, height, width; guchar *in_pixels; guchar *in2_pixels; guchar *output_pixels; cairo_surface_flush (in); cairo_surface_flush (in2); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); rowstride2 = cairo_image_surface_get_stride (in2); rowstrideo = cairo_image_surface_get_stride (output); output_pixels = cairo_image_surface_get_data (output); in_pixels = cairo_image_surface_get_data (in); in2_pixels = cairo_image_surface_get_data (in2); if (boundarys.x0 < 0) boundarys.x0 = 0; if (boundarys.y0 < 0) boundarys.y0 = 0; if (boundarys.x1 >= width) boundarys.x1 = width; if (boundarys.y1 >= height) boundarys.y1 = height; for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { double qr, cr, qa, qb, ca, cb, bca, bcb; int ch; qa = (double) in_pixels[4 * x + y * rowstride + channelmap[3]] / 255.0; qb = (double) in2_pixels[4 * x + y * rowstride2 + channelmap[3]] / 255.0; qr = 1 - (1 - qa) * (1 - qb); cr = 0; for (ch = 0; ch < 3; ch++) { i = channelmap[ch]; ca = (double) in_pixels[4 * x + y * rowstride + i] / 255.0; cb = (double) in2_pixels[4 * x + y * rowstride2 + i] / 255.0; /*these are the ca and cb that are used in the non-standard blend functions */ bcb = (1 - qa) * cb + ca; bca = (1 - qb) * ca + cb; switch (mode) { case normal: cr = (1 - qa) * cb + ca; break; case multiply: cr = (1 - qa) * cb + (1 - qb) * ca + ca * cb; break; case screen: cr = cb + ca - ca * cb; break; case darken: cr = MIN ((1 - qa) * cb + ca, (1 - qb) * ca + cb); break; case lighten: cr = MAX ((1 - qa) * cb + ca, (1 - qb) * ca + cb); break; case softlight: if (bcb < 0.5) cr = 2 * bca * bcb + bca * bca * (1 - 2 * bcb); else cr = sqrt (bca) * (2 * bcb - 1) + (2 * bca) * (1 - bcb); break; case hardlight: if (cb < 0.5) cr = 2 * bca * bcb; else cr = 1 - 2 * (1 - bca) * (1 - bcb); break; case colordodge: if (bcb == 1) cr = 1; else cr = MIN (bca / (1 - bcb), 1); break; case colorburn: if (bcb == 0) cr = 0; else cr = MAX (1 - (1 - bca) / bcb, 0); break; case overlay: if (bca < 0.5) cr = 2 * bca * bcb; else cr = 1 - 2 * (1 - bca) * (1 - bcb); break; case exclusion: cr = bca + bcb - 2 * bca * bcb; break; case difference: cr = abs (bca - bcb); break; } cr *= 255.0; if (cr > 255) cr = 255; if (cr < 0) cr = 0; output_pixels[4 * x + y * rowstrideo + i] = (guchar) cr; } output_pixels[4 * x + y * rowstrideo + channelmap[3]] = qr * 255.0; } cairo_surface_mark_dirty (output); } static void rsvg_filter_primitive_blend_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveBlend *blend = (RsvgFilterPrimitiveBlend *) primitive; RsvgIRect boundarys; cairo_surface_t *output, *in, *in2; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; in2 = rsvg_filter_get_in (blend->in2, ctx); if (in2 == NULL) { cairo_surface_destroy (in); return; } output = _rsvg_image_surface_new (cairo_image_surface_get_width (in), cairo_image_surface_get_height (in)); if (output == NULL) { cairo_surface_destroy (in); cairo_surface_destroy (in2); return; } rsvg_filter_blend (blend->mode, in, in2, output, boundarys, ctx->channelmap); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (in2); cairo_surface_destroy (output); } static void rsvg_filter_primitive_blend_free (gpointer impl) { RsvgFilterPrimitiveBlend *blend = impl; g_string_free (blend->in2, TRUE); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_blend_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveBlend *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "mode"))) { if (!strcmp (value, "multiply")) filter->mode = multiply; else if (!strcmp (value, "screen")) filter->mode = screen; else if (!strcmp (value, "darken")) filter->mode = darken; else if (!strcmp (value, "lighten")) filter->mode = lighten; else filter->mode = normal; } if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "in2"))) g_string_assign (filter->in2, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_blend (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveBlend *filter; filter = g_new0 (RsvgFilterPrimitiveBlend, 1); filter->mode = normal; filter->super.in = g_string_new ("none"); filter->in2 = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->super.render = rsvg_filter_primitive_blend_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_BLEND, parent, rsvg_state_new (), filter, rsvg_filter_primitive_blend_set_atts, rsvg_filter_draw, rsvg_filter_primitive_blend_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveConvolveMatrix RsvgFilterPrimitiveConvolveMatrix; typedef enum { EDGE_MODE_DUPLICATE, EDGE_MODE_WRAP, EDGE_MODE_NONE } EdgeMode; struct _RsvgFilterPrimitiveConvolveMatrix { RsvgFilterPrimitive super; double *KernelMatrix; double divisor; gint orderx, ordery; double dx, dy; double bias; gint targetx, targety; gboolean preservealpha; EdgeMode edgemode; }; static void rsvg_filter_primitive_convolve_matrix_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveConvolveMatrix *convolve = (RsvgFilterPrimitiveConvolveMatrix *) primitive; guchar ch; gint x, y; gint i, j; gint rowstride, height, width; RsvgIRect boundarys; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; gint sx, sy, kx, ky; guchar sval; double kval, sum, dx, dy, targetx, targety; int umch; gint tempresult; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); targetx = convolve->targetx * ctx->paffine.xx; targety = convolve->targety * ctx->paffine.yy; if (convolve->dx != 0 || convolve->dy != 0) { dx = convolve->dx * ctx->paffine.xx; dy = convolve->dy * ctx->paffine.yy; } else dx = dy = 1; rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); for (y = boundarys.y0; y < boundarys.y1; y++) { for (x = boundarys.x0; x < boundarys.x1; x++) { for (umch = 0; umch < 3 + !convolve->preservealpha; umch++) { ch = ctx->channelmap[umch]; sum = 0; for (i = 0; i < convolve->ordery; i++) { for (j = 0; j < convolve->orderx; j++) { int alpha; sx = x - targetx + j * dx; sy = y - targety + i * dy; if (convolve->edgemode == EDGE_MODE_DUPLICATE) { if (sx < boundarys.x0) sx = boundarys.x0; if (sx >= boundarys.x1) sx = boundarys.x1 - 1; if (sy < boundarys.y0) sy = boundarys.y0; if (sy >= boundarys.y1) sy = boundarys.y1 - 1; } else if (convolve->edgemode == EDGE_MODE_WRAP) { if (sx < boundarys.x0 || (sx >= boundarys.x1)) sx = boundarys.x0 + (sx - boundarys.x0) % (boundarys.x1 - boundarys.x0); if (sy < boundarys.y0 || (sy >= boundarys.y1)) sy = boundarys.y0 + (sy - boundarys.y0) % (boundarys.y1 - boundarys.y0); } else if (convolve->edgemode == EDGE_MODE_NONE) { if (sx < boundarys.x0 || (sx >= boundarys.x1) || sy < boundarys.y0 || (sy >= boundarys.y1)) continue; } else { g_assert_not_reached (); } kx = convolve->orderx - j - 1; ky = convolve->ordery - i - 1; alpha = in_pixels[4 * sx + sy * rowstride + 3]; if (ch == 3) sval = alpha; else if (alpha) sval = in_pixels[4 * sx + sy * rowstride + ch] * 255 / alpha; else sval = 0; kval = convolve->KernelMatrix[kx + ky * convolve->orderx]; sum += (double) sval *kval; } } tempresult = sum / convolve->divisor + convolve->bias; if (tempresult > 255) tempresult = 255; if (tempresult < 0) tempresult = 0; output_pixels[4 * x + y * rowstride + ch] = tempresult; } if (convolve->preservealpha) output_pixels[4 * x + y * rowstride + ctx->channelmap[3]] = in_pixels[4 * x + y * rowstride + ctx->channelmap[3]]; for (umch = 0; umch < 3; umch++) { ch = ctx->channelmap[umch]; output_pixels[4 * x + y * rowstride + ch] = output_pixels[4 * x + y * rowstride + ch] * output_pixels[4 * x + y * rowstride + ctx->channelmap[3]] / 255; } } } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_convolve_matrix_free (gpointer impl) { RsvgFilterPrimitiveConvolveMatrix *convolve = impl; g_free (convolve->KernelMatrix); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_convolve_matrix_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveConvolveMatrix *filter = impl; gint i, j; const char *value; gboolean has_target_x, has_target_y; has_target_x = 0; has_target_y = 0; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "targetX"))) { has_target_x = 1; filter->targetx = atoi (value); } if ((value = rsvg_property_bag_lookup (atts, "targetY"))) { has_target_y = 1; filter->targety = atoi (value); } if ((value = rsvg_property_bag_lookup (atts, "bias"))) filter->bias = atof (value); if ((value = rsvg_property_bag_lookup (atts, "preserveAlpha"))) { if (!strcmp (value, "true")) filter->preservealpha = TRUE; else filter->preservealpha = FALSE; } if ((value = rsvg_property_bag_lookup (atts, "divisor"))) filter->divisor = atof (value); if ((value = rsvg_property_bag_lookup (atts, "order"))) { double tempx, tempy; if (rsvg_css_parse_number_optional_number (value, &tempx, &tempy) && tempx >= 1.0 && tempy <= 100.0 && tempy >= 1.0 && tempy <= 100.0) { filter->orderx = (int) tempx; filter->ordery = (int) tempy; g_assert (filter->orderx >= 1); g_assert (filter->ordery >= 1); #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b))) if (SIZE_OVERFLOWS (filter->orderx, filter->ordery)) { rsvg_node_set_attribute_parse_error (node, "order", "number of kernelMatrix elements would be too big"); return; } } else { rsvg_node_set_attribute_parse_error (node, "order", "invalid size for convolve matrix"); return; } } if ((value = rsvg_property_bag_lookup (atts, "kernelUnitLength"))) { if (!rsvg_css_parse_number_optional_number (value, &filter->dx, &filter->dy)) { rsvg_node_set_attribute_parse_error (node, "kernelUnitLength", "expected number-optional-number"); return; } } if ((value = rsvg_property_bag_lookup (atts, "kernelMatrix"))) { gsize num_elems; gsize got_num_elems; num_elems = filter->orderx * filter->ordery; if (!rsvg_css_parse_number_list (value, NUMBER_LIST_LENGTH_EXACT, num_elems, &filter->KernelMatrix, &got_num_elems)) { rsvg_node_set_attribute_parse_error (node, "kernelMatrix", "expected a matrix of numbers"); return; } g_assert (num_elems == got_num_elems); } if ((value = rsvg_property_bag_lookup (atts, "edgeMode"))) { if (!strcmp (value, "duplicate")) { filter->edgemode = EDGE_MODE_DUPLICATE; } else if (!strcmp (value, "wrap")) { filter->edgemode = EDGE_MODE_WRAP; } else if (!strcmp (value, "none")) { filter->edgemode = EDGE_MODE_NONE; } else { rsvg_node_set_attribute_parse_error (node, "edgeMode", "expected 'duplicate' | 'wrap' | 'none'"); return; } } if (filter->divisor == 0) { for (j = 0; j < filter->orderx; j++) for (i = 0; i < filter->ordery; i++) filter->divisor += filter->KernelMatrix[j + i * filter->orderx]; } if (filter->divisor == 0) filter->divisor = 1; if (!has_target_x) { filter->targetx = floor (filter->orderx / 2); } if (!has_target_y) { filter->targety = floor (filter->ordery / 2); } } RsvgNode * rsvg_new_filter_primitive_convolve_matrix (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveConvolveMatrix *filter; filter = g_new0 (RsvgFilterPrimitiveConvolveMatrix, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->KernelMatrix = NULL; filter->divisor = 0; filter->bias = 0; filter->dx = 0; filter->dy = 0; filter->preservealpha = FALSE; filter->edgemode = EDGE_MODE_DUPLICATE; filter->super.render = rsvg_filter_primitive_convolve_matrix_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_CONVOLVE_MATRIX, parent, rsvg_state_new (), filter, rsvg_filter_primitive_convolve_matrix_set_atts, rsvg_filter_draw, rsvg_filter_primitive_convolve_matrix_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveGaussianBlur RsvgFilterPrimitiveGaussianBlur; struct _RsvgFilterPrimitiveGaussianBlur { RsvgFilterPrimitive super; double sdx, sdy; }; static void box_blur_line (gint box_width, gint even_offset, guchar *src, guchar *dest, gint len, gint bpp) { gint i; gint lead; /* This marks the leading edge of the kernel */ gint output; /* This marks the center of the kernel */ gint trail; /* This marks the pixel BEHIND the last 1 in the kernel; it's the pixel to remove from the accumulator. */ gint *ac; /* Accumulator for each channel */ ac = g_new0 (gint, bpp); /* The algorithm differs for even and odd-sized kernels. * With the output at the center, * If odd, the kernel might look like this: 0011100 * If even, the kernel will either be centered on the boundary between * the output and its left neighbor, or on the boundary between the * output and its right neighbor, depending on even_lr. * So it might be 0111100 or 0011110, where output is on the center * of these arrays. */ lead = 0; if (box_width % 2 != 0) { /* Odd-width kernel */ output = lead - (box_width - 1) / 2; trail = lead - box_width; } else { /* Even-width kernel. */ if (even_offset == 1) { /* Right offset */ output = lead + 1 - box_width / 2; trail = lead - box_width; } else if (even_offset == -1) { /* Left offset */ output = lead - box_width / 2; trail = lead - box_width; } else { /* If even_offset isn't 1 or -1, there's some error. */ g_assert_not_reached (); } } /* Initialize accumulator */ for (i = 0; i < bpp; i++) ac[i] = 0; /* As the kernel moves across the image, it has a leading edge and a * trailing edge, and the output is in the middle. */ while (output < len) { /* The number of pixels that are both in the image and * currently covered by the kernel. This is necessary to * handle edge cases. */ guint coverage = (lead < len ? lead : len - 1) - (trail >= 0 ? trail : -1); #ifdef READABLE_BOXBLUR_CODE /* The code here does the same as the code below, but the code below * has been optimized by moving the if statements out of the tight for * loop, and is harder to understand. * Don't use both this code and the code below. */ for (i = 0; i < bpp; i++) { /* If the leading edge of the kernel is still on the image, * add the value there to the accumulator. */ if (lead < len) ac[i] += src[bpp * lead + i]; /* If the trailing edge of the kernel is on the image, * subtract the value there from the accumulator. */ if (trail >= 0) ac[i] -= src[bpp * trail + i]; /* Take the averaged value in the accumulator and store * that value in the output. The number of pixels currently * stored in the accumulator can be less than the nominal * width of the kernel because the kernel can go "over the edge" * of the image. */ if (output >= 0) dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } #endif /* If the leading edge of the kernel is still on the image... */ if (lead < len) { if (trail >= 0) { /* If the trailing edge of the kernel is on the image. (Since * the output is in between the lead and trail, it must be on * the image. */ for (i = 0; i < bpp; i++) { ac[i] += src[bpp * lead + i]; ac[i] -= src[bpp * trail + i]; dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } } else if (output >= 0) { /* If the output is on the image, but the trailing edge isn't yet * on the image. */ for (i = 0; i < bpp; i++) { ac[i] += src[bpp * lead + i]; dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } } else { /* If leading edge is on the image, but the output and trailing * edge aren't yet on the image. */ for (i = 0; i < bpp; i++) ac[i] += src[bpp * lead + i]; } } else if (trail >= 0) { /* If the leading edge has gone off the image, but the output and * trailing edge are on the image. (The big loop exits when the * output goes off the image. */ for (i = 0; i < bpp; i++) { ac[i] -= src[bpp * trail + i]; dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } } else if (output >= 0) { /* Leading has gone off the image and trailing isn't yet in it * (small image) */ for (i = 0; i < bpp; i++) dest[bpp * output + i] = (ac[i] + (coverage >> 1)) / coverage; } lead++; output++; trail++; } g_free (ac); } static gint compute_box_blur_width (double radius) { double width; width = radius * 3 * sqrt (2 * G_PI) / 4; return (gint) (width + 0.5); } #define SQR(x) ((x) * (x)) static void make_gaussian_convolution_matrix (gdouble radius, gdouble **out_matrix, gint *out_matrix_len) { gdouble *matrix; gdouble std_dev; gdouble sum; gint matrix_len; gint i, j; std_dev = radius + 1.0; radius = std_dev * 2; matrix_len = 2 * ceil (radius - 0.5) + 1; if (matrix_len <= 0) matrix_len = 1; matrix = g_new0 (gdouble, matrix_len); /* Fill the matrix by doing numerical integration approximation * from -2*std_dev to 2*std_dev, sampling 50 points per pixel. * We do the bottom half, mirror it to the top half, then compute the * center point. Otherwise asymmetric quantization errors will occur. * The formula to integrate is e^-(x^2/2s^2). */ for (i = matrix_len / 2 + 1; i < matrix_len; i++) { gdouble base_x = i - (matrix_len / 2) - 0.5; sum = 0; for (j = 1; j <= 50; j++) { gdouble r = base_x + 0.02 * j; if (r <= radius) sum += exp (- SQR (r) / (2 * SQR (std_dev))); } matrix[i] = sum / 50; } /* mirror to the bottom half */ for (i = 0; i <= matrix_len / 2; i++) matrix[i] = matrix[matrix_len - 1 - i]; /* find center val -- calculate an odd number of quanta to make it * symmetric, even if the center point is weighted slightly higher * than others. */ sum = 0; for (j = 0; j <= 50; j++) sum += exp (- SQR (- 0.5 + 0.02 * j) / (2 * SQR (std_dev))); matrix[matrix_len / 2] = sum / 51; /* normalize the distribution by scaling the total sum to one */ sum = 0; for (i = 0; i < matrix_len; i++) sum += matrix[i]; for (i = 0; i < matrix_len; i++) matrix[i] = matrix[i] / sum; *out_matrix = matrix; *out_matrix_len = matrix_len; } static void gaussian_blur_line (gdouble *matrix, gint matrix_len, guchar *src, guchar *dest, gint len, gint bpp) { guchar *src_p; guchar *src_p1; gint matrix_middle; gint row; gint i, j; matrix_middle = matrix_len / 2; /* picture smaller than the matrix? */ if (matrix_len > len) { for (row = 0; row < len; row++) { /* find the scale factor */ gdouble scale = 0; for (j = 0; j < len; j++) { /* if the index is in bounds, add it to the scale counter */ if (j + matrix_middle - row >= 0 && j + matrix_middle - row < matrix_len) scale += matrix[j]; } src_p = src; for (i = 0; i < bpp; i++) { gdouble sum = 0; src_p1 = src_p++; for (j = 0; j < len; j++) { if (j + matrix_middle - row >= 0 && j + matrix_middle - row < matrix_len) sum += *src_p1 * matrix[j]; src_p1 += bpp; } *dest++ = (guchar) (sum / scale + 0.5); } } } else { /* left edge */ for (row = 0; row < matrix_middle; row++) { /* find scale factor */ gdouble scale = 0; for (j = matrix_middle - row; j < matrix_len; j++) scale += matrix[j]; src_p = src; for (i = 0; i < bpp; i++) { gdouble sum = 0; src_p1 = src_p++; for (j = matrix_middle - row; j < matrix_len; j++) { sum += *src_p1 * matrix[j]; src_p1 += bpp; } *dest++ = (guchar) (sum / scale + 0.5); } } /* go through each pixel in each col */ for (; row < len - matrix_middle; row++) { src_p = src + (row - matrix_middle) * bpp; for (i = 0; i < bpp; i++) { gdouble sum = 0; src_p1 = src_p++; for (j = 0; j < matrix_len; j++) { sum += matrix[j] * *src_p1; src_p1 += bpp; } *dest++ = (guchar) (sum + 0.5); } } /* for the edge condition, we only use available info and scale to one */ for (; row < len; row++) { /* find scale factor */ gdouble scale = 0; for (j = 0; j < len - row + matrix_middle; j++) scale += matrix[j]; src_p = src + (row - matrix_middle) * bpp; for (i = 0; i < bpp; i++) { gdouble sum = 0; src_p1 = src_p++; for (j = 0; j < len - row + matrix_middle; j++) { sum += *src_p1 * matrix[j]; src_p1 += bpp; } *dest++ = (guchar) (sum / scale + 0.5); } } } } static void get_column (guchar *column_data, guchar *src_data, gint src_stride, gint bpp, gint height, gint x) { gint y; gint c; for (y = 0; y < height; y++) { guchar *src = src_data + y * src_stride + x * bpp; for (c = 0; c < bpp; c++) column_data[c] = src[c]; column_data += bpp; } } static void put_column (guchar *column_data, guchar *dest_data, gint dest_stride, gint bpp, gint height, gint x) { gint y; gint c; for (y = 0; y < height; y++) { guchar *dst = dest_data + y * dest_stride + x * bpp; for (c = 0; c < bpp; c++) dst[c] = column_data[c]; column_data += bpp; } } static void gaussian_blur_surface (cairo_surface_t *in, cairo_surface_t *out, gdouble sx, gdouble sy) { gboolean use_box_blur; gint width, height; cairo_format_t in_format, out_format; gint in_stride; gint out_stride; guchar *in_data, *out_data; gint bpp; gboolean out_has_data; cairo_surface_flush (in); width = cairo_image_surface_get_width (in); height = cairo_image_surface_get_height (in); g_assert (width == cairo_image_surface_get_width (out) && height == cairo_image_surface_get_height (out)); in_format = cairo_image_surface_get_format (in); out_format = cairo_image_surface_get_format (out); g_assert (in_format == out_format); g_assert (in_format == CAIRO_FORMAT_ARGB32 || in_format == CAIRO_FORMAT_A8); if (in_format == CAIRO_FORMAT_ARGB32) bpp = 4; else if (in_format == CAIRO_FORMAT_A8) bpp = 1; else { g_assert_not_reached (); return; } in_stride = cairo_image_surface_get_stride (in); out_stride = cairo_image_surface_get_stride (out); in_data = cairo_image_surface_get_data (in); out_data = cairo_image_surface_get_data (out); if (sx < 0.0) sx = 0.0; if (sy < 0.0) sy = 0.0; /* For small radiuses, use a true gaussian kernel; otherwise use three box blurs with * clever offsets. */ if (sx < 10.0 && sy < 10.0) use_box_blur = FALSE; else use_box_blur = TRUE; /* Bail out by just copying? */ if ((sx == 0.0 && sy == 0.0) || sx > 1000 || sy > 1000) { cairo_t *cr; cr = cairo_create (out); cairo_set_source_surface (cr, in, 0, 0); cairo_paint (cr); cairo_destroy (cr); return; } if (sx != 0.0) { gint box_width; gdouble *gaussian_matrix; gint gaussian_matrix_len; int y; guchar *row_buffer = NULL; guchar *row1, *row2; if (use_box_blur) { box_width = compute_box_blur_width (sx); /* twice the size so we can have "two" scratch rows */ row_buffer = g_new0 (guchar, width * bpp * 2); row1 = row_buffer; row2 = row_buffer + width * bpp; } else make_gaussian_convolution_matrix (sx, &gaussian_matrix, &gaussian_matrix_len); for (y = 0; y < height; y++) { guchar *in_row, *out_row; in_row = in_data + in_stride * y; out_row = out_data + out_stride * y; if (use_box_blur) { if (box_width % 2 != 0) { /* Odd-width box blur: repeat 3 times, centered on output pixel */ box_blur_line (box_width, 0, in_row, row1, width, bpp); box_blur_line (box_width, 0, row1, row2, width, bpp); box_blur_line (box_width, 0, row2, out_row, width, bpp); } else { /* Even-width box blur: * This method is suggested by the specification for SVG. * One pass with width n, centered between output and right pixel * One pass with width n, centered between output and left pixel * One pass with width n+1, centered on output pixel */ box_blur_line (box_width, -1, in_row, row1, width, bpp); box_blur_line (box_width, 1, row1, row2, width, bpp); box_blur_line (box_width + 1, 0, row2, out_row, width, bpp); } } else gaussian_blur_line (gaussian_matrix, gaussian_matrix_len, in_row, out_row, width, bpp); } if (!use_box_blur) g_free (gaussian_matrix); g_free (row_buffer); out_has_data = TRUE; } else out_has_data = FALSE; if (sy != 0.0) { gint box_height; gdouble *gaussian_matrix = NULL; gint gaussian_matrix_len; guchar *col_buffer; guchar *col1, *col2; int x; /* twice the size so we can have the source pixels and the blurred pixels */ col_buffer = g_new0 (guchar, height * bpp * 2); col1 = col_buffer; col2 = col_buffer + height * bpp; if (use_box_blur) { box_height = compute_box_blur_width (sy); } else make_gaussian_convolution_matrix (sy, &gaussian_matrix, &gaussian_matrix_len); for (x = 0; x < width; x++) { if (out_has_data) get_column (col1, out_data, out_stride, bpp, height, x); else get_column (col1, in_data, in_stride, bpp, height, x); if (use_box_blur) { if (box_height % 2 != 0) { /* Odd-width box blur */ box_blur_line (box_height, 0, col1, col2, height, bpp); box_blur_line (box_height, 0, col2, col1, height, bpp); box_blur_line (box_height, 0, col1, col2, height, bpp); } else { /* Even-width box blur */ box_blur_line (box_height, -1, col1, col2, height, bpp); box_blur_line (box_height, 1, col2, col1, height, bpp); box_blur_line (box_height + 1, 0, col1, col2, height, bpp); } } else gaussian_blur_line (gaussian_matrix, gaussian_matrix_len, col1, col2, height, bpp); put_column (col2, out_data, out_stride, bpp, height, x); } g_free (gaussian_matrix); g_free (col_buffer); } cairo_surface_mark_dirty (out); } static void rsvg_filter_primitive_gaussian_blur_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveGaussianBlur *gaussian = (RsvgFilterPrimitiveGaussianBlur *) primitive; int width, height; cairo_surface_t *output, *in; RsvgIRect boundarys; gdouble sdx, sdy; RsvgFilterPrimitiveOutput op; cairo_t *cr; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); op = rsvg_filter_get_result (primitive->in, ctx); in = op.surface; width = cairo_image_surface_get_width (in); height = cairo_image_surface_get_height (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } /* scale the SD values */ sdx = fabs (gaussian->sdx * ctx->paffine.xx); sdy = fabs (gaussian->sdy * ctx->paffine.yy); gaussian_blur_surface (in, output, sdx, sdy); /* Hard-clip to the filter area */ if (!(boundarys.x0 == 0 && boundarys.y0 == 0 && boundarys.x1 == width && boundarys.y1 == height)) { cr = cairo_create (output); cairo_set_operator (cr, CAIRO_OPERATOR_CLEAR); cairo_set_fill_rule (cr, CAIRO_FILL_RULE_EVEN_ODD); cairo_rectangle (cr, 0, 0, width, height); cairo_rectangle (cr, boundarys.x0, boundarys.y0, boundarys.x1 - boundarys.x0, boundarys.y1 - boundarys.y0); cairo_fill (cr); cairo_destroy (cr); } op.surface = output; op.bounds = boundarys; rsvg_filter_store_output (primitive->result, op, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_gaussian_blur_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveGaussianBlur *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "stdDeviation"))) { if (!rsvg_css_parse_number_optional_number (value, &filter->sdx, &filter->sdy)) { rsvg_node_set_attribute_parse_error (node, "stdDeviation", "expected number-optional-number"); return; } } } RsvgNode * rsvg_new_filter_primitive_gaussian_blur (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveGaussianBlur *filter; filter = g_new0 (RsvgFilterPrimitiveGaussianBlur, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->sdx = 0; filter->sdy = 0; filter->super.render = rsvg_filter_primitive_gaussian_blur_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_GAUSSIAN_BLUR, parent, rsvg_state_new (), filter, rsvg_filter_primitive_gaussian_blur_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveOffset RsvgFilterPrimitiveOffset; struct _RsvgFilterPrimitiveOffset { RsvgFilterPrimitive super; RsvgLength dx, dy; }; static void rsvg_filter_primitive_offset_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveOffset *offset = (RsvgFilterPrimitiveOffset *) primitive; guchar ch; gint x, y; gint rowstride, height, width; RsvgIRect boundarys; guchar *in_pixels; guchar *output_pixels; RsvgFilterPrimitiveOutput out; cairo_surface_t *output, *in; double dx, dy; int ox, oy; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); dx = rsvg_length_normalize (&offset->dx, ctx->ctx); dy = rsvg_length_normalize (&offset->dy, ctx->ctx); ox = ctx->paffine.xx * dx + ctx->paffine.xy * dy; oy = ctx->paffine.yx * dx + ctx->paffine.yy * dy; for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { if (x - ox < boundarys.x0 || x - ox >= boundarys.x1) continue; if (y - oy < boundarys.y0 || y - oy >= boundarys.y1) continue; for (ch = 0; ch < 4; ch++) { output_pixels[y * rowstride + x * 4 + ch] = in_pixels[(y - oy) * rowstride + (x - ox) * 4 + ch]; } } cairo_surface_mark_dirty (output); out.surface = output; out.bounds = boundarys; rsvg_filter_store_output (primitive->result, out, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_offset_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag * atts) { RsvgFilterPrimitiveOffset *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "dx"))) filter->dx = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); if ((value = rsvg_property_bag_lookup (atts, "dy"))) filter->dy = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); } RsvgNode * rsvg_new_filter_primitive_offset (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveOffset *filter; filter = g_new0 (RsvgFilterPrimitiveOffset, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->dx = rsvg_length_parse ("0", LENGTH_DIR_HORIZONTAL); filter->dy = rsvg_length_parse ("0", LENGTH_DIR_VERTICAL); filter->super.render = rsvg_filter_primitive_offset_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_OFFSET, parent, rsvg_state_new (), filter, rsvg_filter_primitive_offset_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveMerge RsvgFilterPrimitiveMerge; struct _RsvgFilterPrimitiveMerge { RsvgFilterPrimitive super; }; struct merge_render_closure { cairo_surface_t *output; RsvgIRect boundarys; RsvgFilterContext *ctx; }; static gboolean merge_render_child (RsvgNode *node, gpointer data) { struct merge_render_closure *closure = data; RsvgFilterPrimitive *fp; cairo_surface_t *in; if (rsvg_node_get_type (node) != RSVG_NODE_TYPE_FILTER_PRIMITIVE_MERGE_NODE) return TRUE; fp = rsvg_rust_cnode_get_impl (node); in = rsvg_filter_get_in (fp->in, closure->ctx); if (in == NULL) return TRUE; rsvg_alpha_blt (in, closure->boundarys.x0, closure->boundarys.y0, closure->boundarys.x1 - closure->boundarys.x0, closure->boundarys.y1 - closure->boundarys.y0, closure->output, closure->boundarys.x0, closure->boundarys.y0); cairo_surface_destroy (in); return TRUE; } static void rsvg_filter_primitive_merge_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { struct merge_render_closure closure; closure.boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); closure.output = _rsvg_image_surface_new (ctx->width, ctx->height); if (closure.output == NULL) { return; } closure.ctx = ctx; rsvg_node_foreach_child (node, merge_render_child, &closure); rsvg_filter_store_result (primitive->result, closure.output, ctx); cairo_surface_destroy (closure.output); } static void rsvg_filter_primitive_merge_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveMerge *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_merge (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveMerge *filter; filter = g_new0 (RsvgFilterPrimitiveMerge, 1); filter->super.result = g_string_new ("none"); filter->super.render = rsvg_filter_primitive_merge_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_MERGE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_merge_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } static void rsvg_filter_primitive_merge_node_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitive *primitive = impl; const char *value; /* see bug 145149 - sodipodi generates bad SVG... */ if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (primitive->in, value); } static void rsvg_filter_primitive_merge_node_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { /* todo */ } RsvgNode * rsvg_new_filter_primitive_merge_node (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitive *filter; filter = g_new0 (RsvgFilterPrimitive, 1); filter->in = g_string_new ("none"); filter->render = rsvg_filter_primitive_merge_node_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_MERGE_NODE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_merge_node_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveColorMatrix RsvgFilterPrimitiveColorMatrix; struct _RsvgFilterPrimitiveColorMatrix { RsvgFilterPrimitive super; gint *KernelMatrix; }; static void rsvg_filter_primitive_color_matrix_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveColorMatrix *color_matrix = (RsvgFilterPrimitiveColorMatrix *) primitive; guchar ch; gint x, y; gint i; gint rowstride, height, width; RsvgIRect boundarys; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; int sum; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { int umch; int alpha = in_pixels[4 * x + y * rowstride + ctx->channelmap[3]]; if (!alpha) for (umch = 0; umch < 4; umch++) { sum = color_matrix->KernelMatrix[umch * 5 + 4]; if (sum > 255) sum = 255; if (sum < 0) sum = 0; output_pixels[4 * x + y * rowstride + ctx->channelmap[umch]] = sum; } else for (umch = 0; umch < 4; umch++) { int umi; ch = ctx->channelmap[umch]; sum = 0; for (umi = 0; umi < 4; umi++) { i = ctx->channelmap[umi]; if (umi != 3) sum += color_matrix->KernelMatrix[umch * 5 + umi] * in_pixels[4 * x + y * rowstride + i] / alpha; else sum += color_matrix->KernelMatrix[umch * 5 + umi] * in_pixels[4 * x + y * rowstride + i] / 255; } sum += color_matrix->KernelMatrix[umch * 5 + 4]; if (sum > 255) sum = 255; if (sum < 0) sum = 0; output_pixels[4 * x + y * rowstride + ch] = sum; } for (umch = 0; umch < 3; umch++) { ch = ctx->channelmap[umch]; output_pixels[4 * x + y * rowstride + ch] = output_pixels[4 * x + y * rowstride + ch] * output_pixels[4 * x + y * rowstride + ctx->channelmap[3]] / 255; } } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_color_matrix_free (gpointer impl) { RsvgFilterPrimitiveColorMatrix *matrix = impl; g_free (matrix->KernelMatrix); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_color_matrix_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveColorMatrix *filter = impl; gint type; gsize listlen = 0; const char *value; type = 0; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "values"))) { unsigned int i; double *temp; if (!rsvg_css_parse_number_list (value, NUMBER_LIST_LENGTH_MAXIMUM, 20, &temp, &listlen)) { rsvg_node_set_attribute_parse_error (node, "values", "invalid number list"); return; } filter->KernelMatrix = g_new0 (int, listlen); for (i = 0; i < listlen; i++) filter->KernelMatrix[i] = temp[i] * 255.; g_free (temp); } if ((value = rsvg_property_bag_lookup (atts, "type"))) { if (!strcmp (value, "matrix")) type = 0; else if (!strcmp (value, "saturate")) type = 1; else if (!strcmp (value, "hueRotate")) type = 2; else if (!strcmp (value, "luminanceToAlpha")) type = 3; else type = 0; } if (type == 0) { if (listlen != 20) { if (filter->KernelMatrix != NULL) g_free (filter->KernelMatrix); filter->KernelMatrix = g_new0 (int, 20); } } else if (type == 1) { float s; if (listlen != 0) { s = filter->KernelMatrix[0]; g_free (filter->KernelMatrix); } else s = 255; filter->KernelMatrix = g_new0 (int, 20); filter->KernelMatrix[0] = 0.213 * 255. + 0.787 * s; filter->KernelMatrix[1] = 0.715 * 255. - 0.715 * s; filter->KernelMatrix[2] = 0.072 * 255. - 0.072 * s; filter->KernelMatrix[5] = 0.213 * 255. - 0.213 * s; filter->KernelMatrix[6] = 0.715 * 255. + 0.285 * s; filter->KernelMatrix[7] = 0.072 * 255. - 0.072 * s; filter->KernelMatrix[10] = 0.213 * 255. - 0.213 * s; filter->KernelMatrix[11] = 0.715 * 255. - 0.715 * s; filter->KernelMatrix[12] = 0.072 * 255. + 0.928 * s; filter->KernelMatrix[18] = 255; } else if (type == 2) { double cosval, sinval, arg; if (listlen != 0) { arg = (double) filter->KernelMatrix[0] / 255.; g_free (filter->KernelMatrix); } else arg = 0; cosval = cos (arg); sinval = sin (arg); filter->KernelMatrix = g_new0 (int, 20); filter->KernelMatrix[0] = (0.213 + cosval * 0.787 + sinval * -0.213) * 255.; filter->KernelMatrix[1] = (0.715 + cosval * -0.715 + sinval * -0.715) * 255.; filter->KernelMatrix[2] = (0.072 + cosval * -0.072 + sinval * 0.928) * 255.; filter->KernelMatrix[5] = (0.213 + cosval * -0.213 + sinval * 0.143) * 255.; filter->KernelMatrix[6] = (0.715 + cosval * 0.285 + sinval * 0.140) * 255.; filter->KernelMatrix[7] = (0.072 + cosval * -0.072 + sinval * -0.283) * 255.; filter->KernelMatrix[10] = (0.213 + cosval * -0.213 + sinval * -0.787) * 255.; filter->KernelMatrix[11] = (0.715 + cosval * -0.715 + sinval * 0.715) * 255.; filter->KernelMatrix[12] = (0.072 + cosval * 0.928 + sinval * 0.072) * 255.; filter->KernelMatrix[18] = 255; } else if (type == 3) { if (filter->KernelMatrix != NULL) g_free (filter->KernelMatrix); filter->KernelMatrix = g_new0 (int, 20); filter->KernelMatrix[15] = 0.2125 * 255.; filter->KernelMatrix[16] = 0.7154 * 255.; filter->KernelMatrix[17] = 0.0721 * 255.; } else { g_assert_not_reached (); } } RsvgNode * rsvg_new_filter_primitive_color_matrix (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveColorMatrix *filter; filter = g_new0 (RsvgFilterPrimitiveColorMatrix, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->KernelMatrix = NULL; filter->super.render = rsvg_filter_primitive_color_matrix_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_COLOR_MATRIX, parent, rsvg_state_new (), filter, rsvg_filter_primitive_color_matrix_set_atts, rsvg_filter_draw, rsvg_filter_primitive_color_matrix_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgNodeComponentTransferFunc RsvgNodeComponentTransferFunc; typedef gint (*ComponentTransferFunc) (gint C, RsvgNodeComponentTransferFunc * user_data); typedef struct _RsvgFilterPrimitiveComponentTransfer RsvgFilterPrimitiveComponentTransfer; struct _RsvgNodeComponentTransferFunc { ComponentTransferFunc function; gint *tableValues; gsize nbTableValues; gint slope; gint intercept; gint amplitude; gint offset; gdouble exponent; char channel; }; struct _RsvgFilterPrimitiveComponentTransfer { RsvgFilterPrimitive super; }; static gint identity_component_transfer_func (gint C, RsvgNodeComponentTransferFunc * user_data) { return C; } static gint table_component_transfer_func (gint C, RsvgNodeComponentTransferFunc * user_data) { guint k; gint vk, vk1, distancefromlast; guint num_values; if (!user_data->nbTableValues) return C; num_values = user_data->nbTableValues; k = (C * (num_values - 1)) / 255; vk = user_data->tableValues[MIN (k, num_values - 1)]; vk1 = user_data->tableValues[MIN (k + 1, num_values - 1)]; distancefromlast = (C * (user_data->nbTableValues - 1)) - k * 255; return vk + distancefromlast * (vk1 - vk) / 255; } static gint discrete_component_transfer_func (gint C, RsvgNodeComponentTransferFunc * user_data) { gint k; if (!user_data->nbTableValues) return C; k = (C * user_data->nbTableValues) / 255; return user_data->tableValues[CLAMP (k, 0, user_data->nbTableValues - 1)]; } static gint linear_component_transfer_func (gint C, RsvgNodeComponentTransferFunc * user_data) { return (user_data->slope * C) / 255 + user_data->intercept; } static gint fixpow (gint base, gint exp) { int out = 255; for (; exp > 0; exp--) out = out * base / 255; return out; } static gint gamma_component_transfer_func (gint C, RsvgNodeComponentTransferFunc * user_data) { if (floor (user_data->exponent) == user_data->exponent) return user_data->amplitude * fixpow (C, user_data->exponent) / 255 + user_data->offset; else return (double) user_data->amplitude * pow ((double) C / 255., user_data->exponent) + user_data->offset; } struct component_transfer_closure { int channel_num; char channel; gboolean set_func; RsvgNodeComponentTransferFunc *channels[4]; ComponentTransferFunc functions[4]; RsvgFilterContext *ctx; }; static gboolean component_transfer_render_child (RsvgNode *node, gpointer data) { struct component_transfer_closure *closure = data; RsvgNodeComponentTransferFunc *f; if (rsvg_node_get_type (node) != RSVG_NODE_TYPE_COMPONENT_TRANFER_FUNCTION) return TRUE; f = rsvg_rust_cnode_get_impl (node); if (f->channel == closure->channel) { closure->functions[closure->ctx->channelmap[closure->channel_num]] = f->function; closure->channels[closure->ctx->channelmap[closure->channel_num]] = f; closure->set_func = TRUE; } return TRUE; } static void rsvg_filter_primitive_component_transfer_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { gint x, y, c; gint rowstride, height, width; RsvgIRect boundarys; guchar *inpix, outpix[4]; gint achan = ctx->channelmap[3]; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; struct component_transfer_closure closure; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); closure.ctx = ctx; for (c = 0; c < 4; c++) { closure.channel_num = c; closure.channel = "rgba"[c]; /* see rsvg_new_node_component_transfer_function() for where these chars come from */ closure.set_func = FALSE; rsvg_node_foreach_child (node, component_transfer_render_child, &closure); if (!closure.set_func) closure.functions[ctx->channelmap[c]] = identity_component_transfer_func; } in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { inpix = in_pixels + (y * rowstride + x * 4); for (c = 0; c < 4; c++) { gint temp; int inval; if (c != achan) { if (inpix[achan] == 0) inval = 0; else inval = inpix[c] * 255 / inpix[achan]; } else inval = inpix[c]; temp = closure.functions[c] (inval, closure.channels[c]); if (temp > 255) temp = 255; else if (temp < 0) temp = 0; outpix[c] = temp; } for (c = 0; c < 3; c++) output_pixels[y * rowstride + x * 4 + ctx->channelmap[c]] = outpix[ctx->channelmap[c]] * outpix[achan] / 255; output_pixels[y * rowstride + x * 4 + achan] = outpix[achan]; } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_component_transfer_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveComponentTransfer *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_component_transfer (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveComponentTransfer *filter; filter = g_new0 (RsvgFilterPrimitiveComponentTransfer, 1); filter->super.result = g_string_new ("none"); filter->super.in = g_string_new ("none"); filter->super.render = rsvg_filter_primitive_component_transfer_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_COMPONENT_TRANSFER, parent, rsvg_state_new (), filter, rsvg_filter_primitive_component_transfer_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } static void rsvg_node_component_transfer_function_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgNodeComponentTransferFunc *data = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "type"))) { if (!strcmp (value, "identity")) data->function = identity_component_transfer_func; else if (!strcmp (value, "table")) data->function = table_component_transfer_func; else if (!strcmp (value, "discrete")) data->function = discrete_component_transfer_func; else if (!strcmp (value, "linear")) data->function = linear_component_transfer_func; else if (!strcmp (value, "gamma")) data->function = gamma_component_transfer_func; } if ((value = rsvg_property_bag_lookup (atts, "tableValues"))) { unsigned int i; double *temp; if (!rsvg_css_parse_number_list (value, NUMBER_LIST_LENGTH_MAXIMUM, 256, &temp, &data->nbTableValues)) { rsvg_node_set_attribute_parse_error (node, "tableValues", "invalid number list"); return; } data->tableValues = g_new0 (gint, data->nbTableValues); for (i = 0; i < data->nbTableValues; i++) data->tableValues[i] = temp[i] * 255.; g_free (temp); } if ((value = rsvg_property_bag_lookup (atts, "slope"))) { data->slope = g_ascii_strtod (value, NULL) * 255.; } if ((value = rsvg_property_bag_lookup (atts, "intercept"))) { data->intercept = g_ascii_strtod (value, NULL) * 255.; } if ((value = rsvg_property_bag_lookup (atts, "amplitude"))) { data->amplitude = g_ascii_strtod (value, NULL) * 255.; } if ((value = rsvg_property_bag_lookup (atts, "exponent"))) { data->exponent = g_ascii_strtod (value, NULL); } if ((value = rsvg_property_bag_lookup (atts, "offset"))) { data->offset = g_ascii_strtod (value, NULL) * 255.; } } static void rsvg_node_component_transfer_function_free (gpointer impl) { RsvgNodeComponentTransferFunc *filter = impl; if (filter->nbTableValues) g_free (filter->tableValues); g_free (filter); } RsvgNode * rsvg_new_node_component_transfer_function (const char *element_name, RsvgNode *parent) { RsvgNodeComponentTransferFunc *filter; char channel; if (strcmp (element_name, "feFuncR") == 0) channel = 'r'; else if (strcmp (element_name, "feFuncG") == 0) channel = 'g'; else if (strcmp (element_name, "feFuncB") == 0) channel = 'b'; else if (strcmp (element_name, "feFuncA") == 0) channel = 'a'; else { g_assert_not_reached (); channel = '\0'; } filter = g_new0 (RsvgNodeComponentTransferFunc, 1); filter->function = identity_component_transfer_func; filter->nbTableValues = 0; filter->channel = channel; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_COMPONENT_TRANFER_FUNCTION, parent, rsvg_state_new (), filter, rsvg_node_component_transfer_function_set_atts, rsvg_filter_draw, rsvg_node_component_transfer_function_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveErode RsvgFilterPrimitiveErode; struct _RsvgFilterPrimitiveErode { RsvgFilterPrimitive super; double rx, ry; int mode; }; static void rsvg_filter_primitive_erode_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveErode *erode = (RsvgFilterPrimitiveErode *) primitive; guchar ch, extreme; gint x, y; gint i, j; gint rowstride, height, width; RsvgIRect boundarys; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; gint kx, ky; guchar val; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); /* scale the radius values */ kx = erode->rx * ctx->paffine.xx; ky = erode->ry * ctx->paffine.yy; output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) for (ch = 0; ch < 4; ch++) { if (erode->mode == 0) extreme = 255; else extreme = 0; for (i = -ky; i < ky + 1; i++) for (j = -kx; j < kx + 1; j++) { if (y + i >= height || y + i < 0 || x + j >= width || x + j < 0) continue; val = in_pixels[(y + i) * rowstride + (x + j) * 4 + ch]; if (erode->mode == 0) { if (extreme > val) extreme = val; } else { if (extreme < val) extreme = val; } } output_pixels[y * rowstride + x * 4 + ch] = extreme; } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_erode_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveErode *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "radius"))) { if (!rsvg_css_parse_number_optional_number (value, &filter->rx, &filter->ry)) { rsvg_node_set_attribute_parse_error (node, "radius", "expected number-optional-number"); return; } } if ((value = rsvg_property_bag_lookup (atts, "operator"))) { if (!strcmp (value, "erode")) filter->mode = 0; else if (!strcmp (value, "dilate")) filter->mode = 1; } } RsvgNode * rsvg_new_filter_primitive_erode (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveErode *filter; filter = g_new0 (RsvgFilterPrimitiveErode, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->rx = 0; filter->ry = 0; filter->mode = 0; filter->super.render = rsvg_filter_primitive_erode_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_ERODE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_erode_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef enum { COMPOSITE_MODE_OVER, COMPOSITE_MODE_IN, COMPOSITE_MODE_OUT, COMPOSITE_MODE_ATOP, COMPOSITE_MODE_XOR, COMPOSITE_MODE_ARITHMETIC } RsvgFilterPrimitiveCompositeMode; typedef struct _RsvgFilterPrimitiveComposite RsvgFilterPrimitiveComposite; struct _RsvgFilterPrimitiveComposite { RsvgFilterPrimitive super; RsvgFilterPrimitiveCompositeMode mode; GString *in2; int k1, k2, k3, k4; }; static cairo_operator_t composite_mode_to_cairo_operator (RsvgFilterPrimitiveCompositeMode mode) { switch (mode) { case COMPOSITE_MODE_OVER: return CAIRO_OPERATOR_OVER; case COMPOSITE_MODE_IN: return CAIRO_OPERATOR_IN; case COMPOSITE_MODE_OUT: return CAIRO_OPERATOR_OUT; case COMPOSITE_MODE_ATOP: return CAIRO_OPERATOR_ATOP; case COMPOSITE_MODE_XOR: return CAIRO_OPERATOR_XOR; default: g_assert_not_reached (); return CAIRO_OPERATOR_CLEAR; } } static void rsvg_filter_primitive_composite_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveComposite *composite = (RsvgFilterPrimitiveComposite *) primitive; RsvgIRect boundarys; cairo_surface_t *output, *in, *in2; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; in2 = rsvg_filter_get_in (composite->in2, ctx); if (in2 == NULL) { cairo_surface_destroy (in); return; } if (composite->mode == COMPOSITE_MODE_ARITHMETIC) { guchar i; gint x, y; gint rowstride, height, width; guchar *in_pixels; guchar *in2_pixels; guchar *output_pixels; height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); cairo_surface_destroy (in2); return; } cairo_surface_flush (in); cairo_surface_flush (in2); in_pixels = cairo_image_surface_get_data (in); in2_pixels = cairo_image_surface_get_data (in2); output_pixels = cairo_image_surface_get_data (output); for (y = boundarys.y0; y < boundarys.y1; y++) { for (x = boundarys.x0; x < boundarys.x1; x++) { int qr, qa, qb; qa = in_pixels[4 * x + y * rowstride + 3]; qb = in2_pixels[4 * x + y * rowstride + 3]; qr = (composite->k1 * qa * qb / 255 + composite->k2 * qa + composite->k3 * qb) / 255; if (qr > 255) qr = 255; if (qr < 0) qr = 0; output_pixels[4 * x + y * rowstride + 3] = qr; if (qr) { for (i = 0; i < 3; i++) { int ca, cb, cr; ca = in_pixels[4 * x + y * rowstride + i]; cb = in2_pixels[4 * x + y * rowstride + i]; cr = (ca * cb * composite->k1 / 255 + ca * composite->k2 + cb * composite->k3 + composite->k4 * qr) / 255; if (cr > qr) cr = qr; if (cr < 0) cr = 0; output_pixels[4 * x + y * rowstride + i] = cr; } } } } cairo_surface_mark_dirty (output); } else { cairo_t *cr; cairo_surface_reference (in2); output = in2; cr = cairo_create (output); cairo_set_source_surface (cr, in, 0, 0); cairo_rectangle (cr, boundarys.x0, boundarys.y0, boundarys.x1 - boundarys.x0, boundarys.y1 - boundarys.y0); cairo_clip (cr); cairo_set_operator (cr, composite_mode_to_cairo_operator (composite->mode)); cairo_paint (cr); cairo_destroy (cr); } rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (in2); cairo_surface_destroy (output); } static void rsvg_filter_primitive_composite_free (gpointer impl) { RsvgFilterPrimitiveComposite *composite = impl; g_string_free (composite->in2, TRUE); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_composite_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveComposite *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "operator"))) { if (!strcmp (value, "in")) filter->mode = COMPOSITE_MODE_IN; else if (!strcmp (value, "out")) filter->mode = COMPOSITE_MODE_OUT; else if (!strcmp (value, "atop")) filter->mode = COMPOSITE_MODE_ATOP; else if (!strcmp (value, "xor")) filter->mode = COMPOSITE_MODE_XOR; else if (!strcmp (value, "arithmetic")) filter->mode = COMPOSITE_MODE_ARITHMETIC; else filter->mode = COMPOSITE_MODE_OVER; } if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "in2"))) g_string_assign (filter->in2, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "k1"))) filter->k1 = g_ascii_strtod (value, NULL) * 255.; if ((value = rsvg_property_bag_lookup (atts, "k2"))) filter->k2 = g_ascii_strtod (value, NULL) * 255.; if ((value = rsvg_property_bag_lookup (atts, "k3"))) filter->k3 = g_ascii_strtod (value, NULL) * 255.; if ((value = rsvg_property_bag_lookup (atts, "k4"))) filter->k4 = g_ascii_strtod (value, NULL) * 255.; } RsvgNode * rsvg_new_filter_primitive_composite (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveComposite *filter; filter = g_new0 (RsvgFilterPrimitiveComposite, 1); filter->mode = COMPOSITE_MODE_OVER; filter->super.in = g_string_new ("none"); filter->in2 = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->k1 = 0; filter->k2 = 0; filter->k3 = 0; filter->k4 = 0; filter->super.render = rsvg_filter_primitive_composite_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_COMPOSITE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_composite_set_atts, rsvg_filter_draw, rsvg_filter_primitive_composite_free); } /*************************************************************/ /*************************************************************/ static void rsvg_filter_primitive_flood_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgState *state; guchar i; gint x, y; gint rowstride, height, width; RsvgIRect boundarys; guchar *output_pixels; cairo_surface_t *output; char pixcolor[4]; RsvgFilterPrimitiveOutput out; state = rsvg_node_get_state (node); guint32 color = state->flood_color; guint8 opacity = state->flood_opacity; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); height = ctx->height; width = ctx->width; output = _rsvg_image_surface_new (width, height); if (output == NULL) return; rowstride = cairo_image_surface_get_stride (output); output_pixels = cairo_image_surface_get_data (output); for (i = 0; i < 3; i++) pixcolor[i] = (int) (((unsigned char *) (&color))[2 - i]) * opacity / 255; pixcolor[3] = opacity; for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) for (i = 0; i < 4; i++) output_pixels[4 * x + y * rowstride + ctx->channelmap[i]] = pixcolor[i]; cairo_surface_mark_dirty (output); out.surface = output; out.bounds = boundarys; rsvg_filter_store_output (primitive->result, out, ctx); cairo_surface_destroy (output); } static void rsvg_filter_primitive_flood_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitive *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_flood (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitive *filter; filter = g_new0 (RsvgFilterPrimitive, 1); filter->in = g_string_new ("none"); filter->result = g_string_new ("none"); filter->render = rsvg_filter_primitive_flood_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_FLOOD, parent, rsvg_state_new (), filter, rsvg_filter_primitive_flood_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveDisplacementMap RsvgFilterPrimitiveDisplacementMap; struct _RsvgFilterPrimitiveDisplacementMap { RsvgFilterPrimitive super; gint dx, dy; char xChannelSelector, yChannelSelector; GString *in2; double scale; }; static void rsvg_filter_primitive_displacement_map_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveDisplacementMap *displacement_map = (RsvgFilterPrimitiveDisplacementMap *) primitive; guchar ch, xch, ych; gint x, y; gint rowstride, height, width; RsvgIRect boundarys; guchar *in_pixels; guchar *in2_pixels; guchar *output_pixels; cairo_surface_t *output, *in, *in2; double ox, oy; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in2 = rsvg_filter_get_in (displacement_map->in2, ctx); if (in2 == NULL) { cairo_surface_destroy (in); return; } cairo_surface_flush (in2); in_pixels = cairo_image_surface_get_data (in); in2_pixels = cairo_image_surface_get_data (in2); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); cairo_surface_destroy (in2); return; } output_pixels = cairo_image_surface_get_data (output); switch (displacement_map->xChannelSelector) { case 'R': xch = 0; break; case 'G': xch = 1; break; case 'B': xch = 2; break; case 'A': xch = 3; break; default: xch = 0; break; } switch (displacement_map->yChannelSelector) { case 'R': ych = 0; break; case 'G': ych = 1; break; case 'B': ych = 2; break; case 'A': ych = 3; break; default: ych = 1; break; } xch = ctx->channelmap[xch]; ych = ctx->channelmap[ych]; for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { if (xch != 4) ox = x + displacement_map->scale * ctx->paffine.xx * ((double) in2_pixels[y * rowstride + x * 4 + xch] / 255.0 - 0.5); else ox = x; if (ych != 4) oy = y + displacement_map->scale * ctx->paffine.yy * ((double) in2_pixels[y * rowstride + x * 4 + ych] / 255.0 - 0.5); else oy = y; for (ch = 0; ch < 4; ch++) { output_pixels[y * rowstride + x * 4 + ch] = get_interp_pixel (in_pixels, ox, oy, ch, boundarys, rowstride); } } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (in2); cairo_surface_destroy (output); } static void rsvg_filter_primitive_displacement_map_free (gpointer impl) { RsvgFilterPrimitiveDisplacementMap *dmap = impl; g_string_free (dmap->in2, TRUE); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_displacement_map_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveDisplacementMap *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "in2"))) g_string_assign (filter->in2, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "xChannelSelector"))) filter->xChannelSelector = (value)[0]; if ((value = rsvg_property_bag_lookup (atts, "yChannelSelector"))) filter->yChannelSelector = (value)[0]; if ((value = rsvg_property_bag_lookup (atts, "scale"))) filter->scale = g_ascii_strtod (value, NULL); } RsvgNode * rsvg_new_filter_primitive_displacement_map (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveDisplacementMap *filter; filter = g_new0 (RsvgFilterPrimitiveDisplacementMap, 1); filter->super.in = g_string_new ("none"); filter->in2 = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->xChannelSelector = ' '; filter->yChannelSelector = ' '; filter->scale = 0; filter->super.render = rsvg_filter_primitive_displacement_map_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_DISPLACEMENT_MAP, parent, rsvg_state_new (), filter, rsvg_filter_primitive_displacement_map_set_atts, rsvg_filter_draw, rsvg_filter_primitive_displacement_map_free); } /*************************************************************/ /*************************************************************/ /* Produces results in the range [1, 2**31 - 2]. Algorithm is: r = (a * r) mod m where a = 16807 and m = 2**31 - 1 = 2147483647 See [Park & Miller], CACM vol. 31 no. 10 p. 1195, Oct. 1988 To test: the algorithm should produce the result 1043618065 as the 10,000th generated number if the original seed is 1. */ #define feTurbulence_RAND_m 2147483647 /* 2**31 - 1 */ #define feTurbulence_RAND_a 16807 /* 7**5; primitive root of m */ #define feTurbulence_RAND_q 127773 /* m / a */ #define feTurbulence_RAND_r 2836 /* m % a */ #define feTurbulence_BSize 0x100 #define feTurbulence_BM 0xff #define feTurbulence_PerlinN 0x1000 #define feTurbulence_NP 12 /* 2^PerlinN */ #define feTurbulence_NM 0xfff typedef struct _RsvgFilterPrimitiveTurbulence RsvgFilterPrimitiveTurbulence; struct _RsvgFilterPrimitiveTurbulence { RsvgFilterPrimitive super; int uLatticeSelector[feTurbulence_BSize + feTurbulence_BSize + 2]; double fGradient[4][feTurbulence_BSize + feTurbulence_BSize + 2][2]; int seed; double fBaseFreqX; double fBaseFreqY; int nNumOctaves; gboolean bFractalSum; gboolean bDoStitching; }; struct feTurbulence_StitchInfo { int nWidth; /* How much to subtract to wrap for stitching. */ int nHeight; int nWrapX; /* Minimum value to wrap. */ int nWrapY; }; static long feTurbulence_setup_seed (int lSeed) { if (lSeed <= 0) lSeed = -(lSeed % (feTurbulence_RAND_m - 1)) + 1; if (lSeed > feTurbulence_RAND_m - 1) lSeed = feTurbulence_RAND_m - 1; return lSeed; } static long feTurbulence_random (int lSeed) { long result; result = feTurbulence_RAND_a * (lSeed % feTurbulence_RAND_q) - feTurbulence_RAND_r * (lSeed / feTurbulence_RAND_q); if (result <= 0) result += feTurbulence_RAND_m; return result; } static void feTurbulence_init (RsvgFilterPrimitiveTurbulence * filter) { double s; int i, j, k, lSeed; lSeed = feTurbulence_setup_seed (filter->seed); for (k = 0; k < 4; k++) { for (i = 0; i < feTurbulence_BSize; i++) { filter->uLatticeSelector[i] = i; for (j = 0; j < 2; j++) filter->fGradient[k][i][j] = (double) (((lSeed = feTurbulence_random (lSeed)) % (feTurbulence_BSize + feTurbulence_BSize)) - feTurbulence_BSize) / feTurbulence_BSize; s = (double) (sqrt (filter->fGradient[k][i][0] * filter->fGradient[k][i][0] + filter->fGradient[k][i][1] * filter->fGradient[k][i][1])); filter->fGradient[k][i][0] /= s; filter->fGradient[k][i][1] /= s; } } while (--i) { k = filter->uLatticeSelector[i]; filter->uLatticeSelector[i] = filter->uLatticeSelector[j = (lSeed = feTurbulence_random (lSeed)) % feTurbulence_BSize]; filter->uLatticeSelector[j] = k; } for (i = 0; i < feTurbulence_BSize + 2; i++) { filter->uLatticeSelector[feTurbulence_BSize + i] = filter->uLatticeSelector[i]; for (k = 0; k < 4; k++) for (j = 0; j < 2; j++) filter->fGradient[k][feTurbulence_BSize + i][j] = filter->fGradient[k][i][j]; } } #define feTurbulence_s_curve(t) ( t * t * (3. - 2. * t) ) #define feTurbulence_lerp(t, a, b) ( a + t * (b - a) ) static double feTurbulence_noise2 (RsvgFilterPrimitiveTurbulence * filter, int nColorChannel, double vec[2], struct feTurbulence_StitchInfo *pStitchInfo) { int bx0, bx1, by0, by1, b00, b10, b01, b11; double rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v; register int i, j; t = vec[0] + feTurbulence_PerlinN; bx0 = (int) t; bx1 = bx0 + 1; rx0 = t - (int) t; rx1 = rx0 - 1.0f; t = vec[1] + feTurbulence_PerlinN; by0 = (int) t; by1 = by0 + 1; ry0 = t - (int) t; ry1 = ry0 - 1.0f; /* If stitching, adjust lattice points accordingly. */ if (pStitchInfo != NULL) { if (bx0 >= pStitchInfo->nWrapX) bx0 -= pStitchInfo->nWidth; if (bx1 >= pStitchInfo->nWrapX) bx1 -= pStitchInfo->nWidth; if (by0 >= pStitchInfo->nWrapY) by0 -= pStitchInfo->nHeight; if (by1 >= pStitchInfo->nWrapY) by1 -= pStitchInfo->nHeight; } bx0 &= feTurbulence_BM; bx1 &= feTurbulence_BM; by0 &= feTurbulence_BM; by1 &= feTurbulence_BM; i = filter->uLatticeSelector[bx0]; j = filter->uLatticeSelector[bx1]; b00 = filter->uLatticeSelector[i + by0]; b10 = filter->uLatticeSelector[j + by0]; b01 = filter->uLatticeSelector[i + by1]; b11 = filter->uLatticeSelector[j + by1]; sx = (double) (feTurbulence_s_curve (rx0)); sy = (double) (feTurbulence_s_curve (ry0)); q = filter->fGradient[nColorChannel][b00]; u = rx0 * q[0] + ry0 * q[1]; q = filter->fGradient[nColorChannel][b10]; v = rx1 * q[0] + ry0 * q[1]; a = feTurbulence_lerp (sx, u, v); q = filter->fGradient[nColorChannel][b01]; u = rx0 * q[0] + ry1 * q[1]; q = filter->fGradient[nColorChannel][b11]; v = rx1 * q[0] + ry1 * q[1]; b = feTurbulence_lerp (sx, u, v); return feTurbulence_lerp (sy, a, b); } static double feTurbulence_turbulence (RsvgFilterPrimitiveTurbulence * filter, int nColorChannel, double *point, double fTileX, double fTileY, double fTileWidth, double fTileHeight) { struct feTurbulence_StitchInfo stitch; struct feTurbulence_StitchInfo *pStitchInfo = NULL; /* Not stitching when NULL. */ double fSum = 0.0f, vec[2], ratio = 1.; int nOctave; /* Adjust the base frequencies if necessary for stitching. */ if (filter->bDoStitching) { /* When stitching tiled turbulence, the frequencies must be adjusted so that the tile borders will be continuous. */ if (filter->fBaseFreqX != 0.0) { double fLoFreq = (double) (floor (fTileWidth * filter->fBaseFreqX)) / fTileWidth; double fHiFreq = (double) (ceil (fTileWidth * filter->fBaseFreqX)) / fTileWidth; if (filter->fBaseFreqX / fLoFreq < fHiFreq / filter->fBaseFreqX) filter->fBaseFreqX = fLoFreq; else filter->fBaseFreqX = fHiFreq; } if (filter->fBaseFreqY != 0.0) { double fLoFreq = (double) (floor (fTileHeight * filter->fBaseFreqY)) / fTileHeight; double fHiFreq = (double) (ceil (fTileHeight * filter->fBaseFreqY)) / fTileHeight; if (filter->fBaseFreqY / fLoFreq < fHiFreq / filter->fBaseFreqY) filter->fBaseFreqY = fLoFreq; else filter->fBaseFreqY = fHiFreq; } /* Set up initial stitch values. */ pStitchInfo = &stitch; stitch.nWidth = (int) (fTileWidth * filter->fBaseFreqX + 0.5f); stitch.nWrapX = fTileX * filter->fBaseFreqX + feTurbulence_PerlinN + stitch.nWidth; stitch.nHeight = (int) (fTileHeight * filter->fBaseFreqY + 0.5f); stitch.nWrapY = fTileY * filter->fBaseFreqY + feTurbulence_PerlinN + stitch.nHeight; } vec[0] = point[0] * filter->fBaseFreqX; vec[1] = point[1] * filter->fBaseFreqY; for (nOctave = 0; nOctave < filter->nNumOctaves; nOctave++) { if (filter->bFractalSum) fSum += (double) (feTurbulence_noise2 (filter, nColorChannel, vec, pStitchInfo) / ratio); else fSum += (double) (fabs (feTurbulence_noise2 (filter, nColorChannel, vec, pStitchInfo)) / ratio); vec[0] *= 2; vec[1] *= 2; ratio *= 2; if (pStitchInfo != NULL) { /* Update stitch values. Subtracting PerlinN before the multiplication and adding it afterward simplifies to subtracting it once. */ stitch.nWidth *= 2; stitch.nWrapX = 2 * stitch.nWrapX - feTurbulence_PerlinN; stitch.nHeight *= 2; stitch.nWrapY = 2 * stitch.nWrapY - feTurbulence_PerlinN; } } return fSum; } static void rsvg_filter_primitive_turbulence_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveTurbulence *turbulence = (RsvgFilterPrimitiveTurbulence *) primitive; gint x, y, tileWidth, tileHeight, rowstride, width, height; RsvgIRect boundarys; guchar *output_pixels; cairo_surface_t *output, *in; cairo_matrix_t affine; affine = ctx->paffine; if (cairo_matrix_invert (&affine) != CAIRO_STATUS_SUCCESS) return; in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); tileWidth = (boundarys.x1 - boundarys.x0); tileHeight = (boundarys.y1 - boundarys.y0); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); for (y = 0; y < tileHeight; y++) { for (x = 0; x < tileWidth; x++) { gint i; double point[2]; guchar *pixel; point[0] = affine.xx * (x + boundarys.x0) + affine.xy * (y + boundarys.y0) + affine.x0; point[1] = affine.yx * (x + boundarys.x0) + affine.yy * (y + boundarys.y0) + affine.y0; pixel = output_pixels + 4 * (x + boundarys.x0) + (y + boundarys.y0) * rowstride; for (i = 0; i < 4; i++) { double cr; cr = feTurbulence_turbulence (turbulence, i, point, (double) x, (double) y, (double) tileWidth, (double) tileHeight); if (turbulence->bFractalSum) cr = ((cr * 255.) + 255.) / 2.; else cr = (cr * 255.); cr = CLAMP (cr, 0., 255.); pixel[ctx->channelmap[i]] = (guchar) cr; } for (i = 0; i < 3; i++) pixel[ctx->channelmap[i]] = pixel[ctx->channelmap[i]] * pixel[ctx->channelmap[3]] / 255; } } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_turbulence_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveTurbulence *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "baseFrequency"))) { if (!rsvg_css_parse_number_optional_number (value, &filter->fBaseFreqX, &filter->fBaseFreqY)) { rsvg_node_set_attribute_parse_error (node, "baseFrequency", "expected number-optional-number"); return; } } if ((value = rsvg_property_bag_lookup (atts, "numOctaves"))) filter->nNumOctaves = atoi (value); if ((value = rsvg_property_bag_lookup (atts, "seed"))) filter->seed = atoi (value); if ((value = rsvg_property_bag_lookup (atts, "stitchTiles"))) filter->bDoStitching = (!strcmp (value, "stitch")); if ((value = rsvg_property_bag_lookup (atts, "type"))) filter->bFractalSum = (!strcmp (value, "fractalNoise")); } RsvgNode * rsvg_new_filter_primitive_turbulence (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveTurbulence *filter; filter = g_new0 (RsvgFilterPrimitiveTurbulence, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->fBaseFreqX = 0; filter->fBaseFreqY = 0; filter->nNumOctaves = 1; filter->seed = 0; filter->bDoStitching = 0; filter->bFractalSum = 0; feTurbulence_init (filter); filter->super.render = rsvg_filter_primitive_turbulence_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_TURBULENCE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_turbulence_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveImage RsvgFilterPrimitiveImage; struct _RsvgFilterPrimitiveImage { RsvgFilterPrimitive super; RsvgHandle *ctx; GString *href; }; static cairo_surface_t * rsvg_filter_primitive_image_render_in (RsvgFilterPrimitiveImage *image, RsvgFilterContext * context) { RsvgDrawingCtx *ctx; RsvgNode *drawable; cairo_surface_t *result; ctx = context->ctx; if (!image->href) return NULL; drawable = rsvg_drawing_ctx_acquire_node (ctx, image->href->str); if (!drawable) return NULL; rsvg_current_state (ctx)->affine = context->paffine; result = rsvg_get_surface_of_node (ctx, drawable, context->width, context->height); rsvg_drawing_ctx_release_node (ctx, drawable); return result; } static cairo_surface_t * rsvg_filter_primitive_image_render_ext (RsvgFilterPrimitive *self, RsvgFilterContext * ctx) { RsvgFilterPrimitiveImage *image = (RsvgFilterPrimitiveImage *) self; RsvgIRect boundarys; cairo_surface_t *img, *intermediate; int i; unsigned char *pixels; int channelmap[4]; int length; int width, height; if (!image->href) return NULL; boundarys = rsvg_filter_primitive_get_bounds (self, ctx); width = boundarys.x1 - boundarys.x0; height = boundarys.y1 - boundarys.y0; if (width == 0 || height == 0) return NULL; img = rsvg_cairo_surface_new_from_href (image->ctx, image->href->str, NULL); if (!img) return NULL; intermediate = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height); if (cairo_surface_status (intermediate) != CAIRO_STATUS_SUCCESS || !rsvg_art_affine_image (img, intermediate, &ctx->paffine, (gdouble) width / ctx->paffine.xx, (gdouble) height / ctx->paffine.yy)) { cairo_surface_destroy (intermediate); cairo_surface_destroy (img); return NULL; } cairo_surface_destroy (img); length = cairo_image_surface_get_height (intermediate) * cairo_image_surface_get_stride (intermediate); for (i = 0; i < 4; i++) channelmap[i] = ctx->channelmap[i]; pixels = cairo_image_surface_get_data (intermediate); for (i = 0; i < length; i += 4) { unsigned char alpha; unsigned char pixel[4]; int ch; alpha = pixels[i + 3]; pixel[channelmap[3]] = alpha; if (alpha) for (ch = 0; ch < 3; ch++) pixel[channelmap[ch]] = pixels[i + ch] * alpha / 255; else for (ch = 0; ch < 3; ch++) pixel[channelmap[ch]] = 0; for (ch = 0; ch < 4; ch++) pixels[i + ch] = pixel[ch]; } cairo_surface_mark_dirty (intermediate); return intermediate; } static void rsvg_filter_primitive_image_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveImage *image = (RsvgFilterPrimitiveImage *) primitive; RsvgIRect boundarys; RsvgFilterPrimitiveOutput op; cairo_surface_t *output, *img; if (!image->href) return; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); output = _rsvg_image_surface_new (ctx->width, ctx->height); if (output == NULL) return; img = rsvg_filter_primitive_image_render_in (image, ctx); if (img == NULL) { img = rsvg_filter_primitive_image_render_ext (primitive, ctx); } if (img) { cairo_t *cr; cr = cairo_create (output); cairo_set_source_surface (cr, img, 0, 0); cairo_rectangle (cr, boundarys.x0, boundarys.y0, boundarys.x1 - boundarys.x0, boundarys.y1 - boundarys.y0); cairo_clip (cr); cairo_paint (cr); cairo_destroy (cr); cairo_surface_destroy (img); } op.surface = output; op.bounds = boundarys; rsvg_filter_store_output (primitive->result, op, ctx); cairo_surface_destroy (output); } static void rsvg_filter_primitive_image_free (gpointer impl) { RsvgFilterPrimitiveImage *image = impl; if (image->href) g_string_free (image->href, TRUE); rsvg_filter_primitive_free (impl); } static void rsvg_filter_primitive_image_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveImage *filter = impl; const char *value; filter->ctx = handle; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); if ((value = rsvg_property_bag_lookup (atts, "xlink:href"))) { filter->href = g_string_new (NULL); g_string_assign (filter->href, value); } filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_image (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveImage *filter; filter = g_new0 (RsvgFilterPrimitiveImage, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->super.render = rsvg_filter_primitive_image_render; filter->href = NULL; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_IMAGE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_image_set_atts, rsvg_filter_draw, rsvg_filter_primitive_image_free); } /*************************************************************/ /*************************************************************/ typedef struct _FactorAndMatrix FactorAndMatrix; struct _FactorAndMatrix { gint matrix[9]; gdouble factor; }; typedef struct _vector3 vector3; struct _vector3 { gdouble x; gdouble y; gdouble z; }; static gdouble norm (vector3 A) { return sqrt (A.x * A.x + A.y * A.y + A.z * A.z); } static gdouble dotproduct (vector3 A, vector3 B) { return A.x * B.x + A.y * B.y + A.z * B.z; } static vector3 normalise (vector3 A) { double divisor; divisor = norm (A); A.x /= divisor; A.y /= divisor; A.z /= divisor; return A; } static FactorAndMatrix get_light_normal_matrix_x (gint n) { static const FactorAndMatrix matrix_list[] = { { {0, 0, 0, 0, -2, 2, 0, -1, 1}, 2.0 / 3.0}, { {0, 0, 0, -2, 0, 2, -1, 0, 1}, 1.0 / 3.0}, { {0, 0, 0, -2, 2, 0, -1, 1, 0}, 2.0 / 3.0}, { {0, -1, 1, 0, -2, 2, 0, -1, 1}, 1.0 / 2.0}, { {-1, 0, 1, -2, 0, 2, -1, 0, 1}, 1.0 / 4.0}, { {-1, 1, 0, -2, 2, 0, -1, 1, 0}, 1.0 / 2.0}, { {0, -1, 1, 0, -2, 2, 0, 0, 0}, 2.0 / 3.0}, { {-1, 0, 1, -2, 0, 2, 0, 0, 0}, 1.0 / 3.0}, { {-1, 1, 0, -2, 2, 0, 0, 0, 0}, 2.0 / 3.0} }; return matrix_list[n]; } static FactorAndMatrix get_light_normal_matrix_y (gint n) { static const FactorAndMatrix matrix_list[] = { { {0, 0, 0, 0, -2, -1, 0, 2, 1}, 2.0 / 3.0}, { {0, 0, 0, -1, -2, -1, 1, 2, 1}, 1.0 / 3.0}, { {0, 0, 0, -1, -2, 0, 1, 2, 0}, 2.0 / 3.0}, { {0, -2, -1, 0, 0, 0, 0, 2, 1}, 1.0 / 2.0}, { {-1, -2, -1, 0, 0, 0, 1, 2, 1}, 1.0 / 4.0}, { {-1, -2, 0, 0, 0, 0, 1, 2, 0}, 1.0 / 2.0}, { {0, -2, -1, 0, 2, 1, 0, 0, 0}, 2.0 / 3.0}, { {0, -2, -1, 1, 2, 1, 0, 0, 0}, 1.0 / 3.0}, { {-1, -2, 0, 1, 2, 0, 0, 0, 0}, 2.0 / 3.0} }; return matrix_list[n]; } static vector3 get_surface_normal (guchar * I, RsvgIRect boundarys, gint x, gint y, gdouble dx, gdouble dy, gdouble rawdx, gdouble rawdy, gdouble surfaceScale, gint rowstride, int chan) { gint mrow, mcol; FactorAndMatrix fnmx, fnmy; gint *Kx, *Ky; gdouble factorx, factory; gdouble Nx, Ny; vector3 output; if (x + dx >= boundarys.x1 - 1) mcol = 2; else if (x - dx < boundarys.x0 + 1) mcol = 0; else mcol = 1; if (y + dy >= boundarys.y1 - 1) mrow = 2; else if (y - dy < boundarys.y0 + 1) mrow = 0; else mrow = 1; fnmx = get_light_normal_matrix_x (mrow * 3 + mcol); factorx = fnmx.factor / rawdx; Kx = fnmx.matrix; fnmy = get_light_normal_matrix_y (mrow * 3 + mcol); factory = fnmy.factor / rawdy; Ky = fnmy.matrix; Nx = -surfaceScale * factorx * ((gdouble) (Kx[0] * get_interp_pixel (I, x - dx, y - dy, chan, boundarys, rowstride) + Kx[1] * get_interp_pixel (I, x, y - dy, chan, boundarys, rowstride) + Kx[2] * get_interp_pixel (I, x + dx, y - dy, chan, boundarys, rowstride) + Kx[3] * get_interp_pixel (I, x - dx, y, chan, boundarys, rowstride) + Kx[4] * get_interp_pixel (I, x, y, chan, boundarys, rowstride) + Kx[5] * get_interp_pixel (I, x + dx, y, chan, boundarys, rowstride) + Kx[6] * get_interp_pixel (I, x - dx, y + dy, chan, boundarys, rowstride) + Kx[7] * get_interp_pixel (I, x, y + dy, chan, boundarys, rowstride) + Kx[8] * get_interp_pixel (I, x + dx, y + dy, chan, boundarys, rowstride))) / 255.0; Ny = -surfaceScale * factory * ((gdouble) (Ky[0] * get_interp_pixel (I, x - dx, y - dy, chan, boundarys, rowstride) + Ky[1] * get_interp_pixel (I, x, y - dy, chan, boundarys, rowstride) + Ky[2] * get_interp_pixel (I, x + dx, y - dy, chan, boundarys, rowstride) + Ky[3] * get_interp_pixel (I, x - dx, y, chan, boundarys, rowstride) + Ky[4] * get_interp_pixel (I, x, y, chan, boundarys, rowstride) + Ky[5] * get_interp_pixel (I, x + dx, y, chan, boundarys, rowstride) + Ky[6] * get_interp_pixel (I, x - dx, y + dy, chan, boundarys, rowstride) + Ky[7] * get_interp_pixel (I, x, y + dy, chan, boundarys, rowstride) + Ky[8] * get_interp_pixel (I, x + dx, y + dy, chan, boundarys, rowstride))) / 255.0; output.x = Nx; output.y = Ny; output.z = 1; output = normalise (output); return output; } typedef enum { DISTANTLIGHT, POINTLIGHT, SPOTLIGHT } lightType; typedef struct _RsvgNodeLightSource RsvgNodeLightSource; struct _RsvgNodeLightSource { lightType type; gdouble azimuth; gdouble elevation; RsvgLength x, y, z, pointsAtX, pointsAtY, pointsAtZ; gdouble specularExponent; gdouble limitingconeAngle; }; static vector3 get_light_direction (RsvgNodeLightSource * source, gdouble x1, gdouble y1, gdouble z, cairo_matrix_t *affine, RsvgDrawingCtx * ctx) { vector3 output; switch (source->type) { case DISTANTLIGHT: output.x = cos (source->azimuth) * cos (source->elevation); output.y = sin (source->azimuth) * cos (source->elevation); output.z = sin (source->elevation); break; default: { double x, y; x = affine->xx * x1 + affine->xy * y1 + affine->x0; y = affine->yx * x1 + affine->yy * y1 + affine->y0; output.x = rsvg_length_normalize (&source->x, ctx) - x; output.y = rsvg_length_normalize (&source->y, ctx) - y; output.z = rsvg_length_normalize (&source->z, ctx) - z; output = normalise (output); } break; } return output; } static vector3 get_light_color (RsvgNodeLightSource * source, vector3 color, gdouble x1, gdouble y1, gdouble z, cairo_matrix_t *affine, RsvgDrawingCtx * ctx) { double base, angle, x, y; vector3 s; vector3 L; vector3 output; double sx, sy, sz, spx, spy, spz; if (source->type != SPOTLIGHT) return color; sx = rsvg_length_normalize (&source->x, ctx); sy = rsvg_length_normalize (&source->y, ctx); sz = rsvg_length_normalize (&source->z, ctx); spx = rsvg_length_normalize (&source->pointsAtX, ctx); spy = rsvg_length_normalize (&source->pointsAtY, ctx); spz = rsvg_length_normalize (&source->pointsAtZ, ctx); x = affine->xx * x1 + affine->xy * y1 + affine->x0; y = affine->yx * x1 + affine->yy * y1 + affine->y0; L.x = sx - x; L.y = sy - y; L.z = sz - z; L = normalise (L); s.x = spx - sx; s.y = spy - sy; s.z = spz - sz; s = normalise (s); base = -dotproduct (L, s); angle = acos (base); if (base < 0 || angle > source->limitingconeAngle) { output.x = 0; output.y = 0; output.z = 0; return output; } output.x = color.x * pow (base, source->specularExponent); output.y = color.y * pow (base, source->specularExponent); output.z = color.z * pow (base, source->specularExponent); return output; } static void rsvg_node_light_source_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgNodeLightSource *data = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "azimuth"))) data->azimuth = g_ascii_strtod (value, NULL) / 180.0 * M_PI; if ((value = rsvg_property_bag_lookup (atts, "elevation"))) data->elevation = g_ascii_strtod (value, NULL) / 180.0 * M_PI; if ((value = rsvg_property_bag_lookup (atts, "limitingConeAngle"))) data->limitingconeAngle = g_ascii_strtod (value, NULL) / 180.0 * M_PI; if ((value = rsvg_property_bag_lookup (atts, "x"))) data->x = data->pointsAtX = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); if ((value = rsvg_property_bag_lookup (atts, "y"))) data->y = data->pointsAtX = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); if ((value = rsvg_property_bag_lookup (atts, "z"))) data->z = data->pointsAtX = rsvg_length_parse (value, LENGTH_DIR_BOTH); if ((value = rsvg_property_bag_lookup (atts, "pointsAtX"))) data->pointsAtX = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL); if ((value = rsvg_property_bag_lookup (atts, "pointsAtY"))) data->pointsAtY = rsvg_length_parse (value, LENGTH_DIR_VERTICAL); if ((value = rsvg_property_bag_lookup (atts, "pointsAtZ"))) data->pointsAtZ = rsvg_length_parse (value, LENGTH_DIR_BOTH); if ((value = rsvg_property_bag_lookup (atts, "specularExponent"))) data->specularExponent = g_ascii_strtod (value, NULL); } RsvgNode * rsvg_new_node_light_source (const char *element_name, RsvgNode *parent) { RsvgNodeLightSource *data; data = g_new0 (RsvgNodeLightSource, 1); data->specularExponent = 1; if (strcmp (element_name, "feDistantLight") == 0) data->type = SPOTLIGHT; else if (strcmp (element_name, "feSpotLight") == 0) data->type = DISTANTLIGHT; else if (strcmp (element_name, "fePointLight") == 0) data->type = POINTLIGHT; else g_assert_not_reached (); data->limitingconeAngle = 180; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_LIGHT_SOURCE, parent, rsvg_state_new (), data, rsvg_node_light_source_set_atts, rsvg_filter_draw, g_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveDiffuseLighting RsvgFilterPrimitiveDiffuseLighting; struct _RsvgFilterPrimitiveDiffuseLighting { RsvgFilterPrimitive super; gdouble dx, dy; double diffuseConstant; double surfaceScale; guint32 lightingcolor; }; struct find_light_source_closure { RsvgNode *found_node; }; static gboolean is_light_source (RsvgNode *node, gpointer data) { struct find_light_source_closure *closure = data; if (rsvg_node_get_type (node) == RSVG_NODE_TYPE_LIGHT_SOURCE) { closure->found_node = rsvg_node_ref (node); } return TRUE; } static RsvgNodeLightSource * find_light_source_in_children (RsvgNode *node) { struct find_light_source_closure closure; RsvgNodeLightSource *source; closure.found_node = NULL; rsvg_node_foreach_child (node, is_light_source, &closure); if (closure.found_node == NULL) return NULL; g_assert (rsvg_node_get_type (closure.found_node) == RSVG_NODE_TYPE_LIGHT_SOURCE); source = rsvg_rust_cnode_get_impl (closure.found_node); closure.found_node = rsvg_node_unref (closure.found_node); return source; } static void rsvg_filter_primitive_diffuse_lighting_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveDiffuseLighting *diffuse_lighting = (RsvgFilterPrimitiveDiffuseLighting *) primitive; gint x, y; float dy, dx, rawdy, rawdx; gdouble z; gint rowstride, height, width; gdouble factor, surfaceScale; vector3 lightcolor, L, N; vector3 color; cairo_matrix_t iaffine; RsvgNodeLightSource *source = NULL; RsvgIRect boundarys; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; source = find_light_source_in_children (node); if (source == NULL) return; iaffine = ctx->paffine; if (cairo_matrix_invert (&iaffine) != CAIRO_STATUS_SUCCESS) return; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); color.x = ((guchar *) (&diffuse_lighting->lightingcolor))[2] / 255.0; color.y = ((guchar *) (&diffuse_lighting->lightingcolor))[1] / 255.0; color.z = ((guchar *) (&diffuse_lighting->lightingcolor))[0] / 255.0; surfaceScale = diffuse_lighting->surfaceScale / 255.0; if (diffuse_lighting->dy < 0 || diffuse_lighting->dx < 0) { dx = 1; dy = 1; rawdx = 1; rawdy = 1; } else { dx = diffuse_lighting->dx * ctx->paffine.xx; dy = diffuse_lighting->dy * ctx->paffine.yy; rawdx = diffuse_lighting->dx; rawdy = diffuse_lighting->dy; } for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { z = surfaceScale * (double) in_pixels[y * rowstride + x * 4 + ctx->channelmap[3]]; L = get_light_direction (source, x, y, z, &iaffine, ctx->ctx); N = get_surface_normal (in_pixels, boundarys, x, y, dx, dy, rawdx, rawdy, diffuse_lighting->surfaceScale, rowstride, ctx->channelmap[3]); lightcolor = get_light_color (source, color, x, y, z, &iaffine, ctx->ctx); factor = dotproduct (N, L); output_pixels[y * rowstride + x * 4 + ctx->channelmap[0]] = MAX (0, MIN (255, diffuse_lighting->diffuseConstant * factor * lightcolor.x * 255.0)); output_pixels[y * rowstride + x * 4 + ctx->channelmap[1]] = MAX (0, MIN (255, diffuse_lighting->diffuseConstant * factor * lightcolor.y * 255.0)); output_pixels[y * rowstride + x * 4 + ctx->channelmap[2]] = MAX (0, MIN (255, diffuse_lighting->diffuseConstant * factor * lightcolor.z * 255.0)); output_pixels[y * rowstride + x * 4 + ctx->channelmap[3]] = 255; } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_diffuse_lighting_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveDiffuseLighting *filter = impl; const char *value; RsvgState *state; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "kernelUnitLength"))) rsvg_css_parse_number_optional_number (value, &filter->dx, &filter->dy); if ((value = rsvg_property_bag_lookup (atts, "lighting-color"))) { RsvgCssColorSpec spec; spec = rsvg_css_parse_color (value, ALLOW_INHERIT_YES, ALLOW_CURRENT_COLOR_YES); switch (spec.kind) { case RSVG_CSS_COLOR_SPEC_INHERIT: /* FIXME: we should inherit; see how stop-color is handled in rsvg-styles.c */ break; case RSVG_CSS_COLOR_SPEC_CURRENT_COLOR: state = rsvg_state_new (); rsvg_state_reconstruct (state, node); filter->lightingcolor = state->current_color; break; case RSVG_CSS_COLOR_SPEC_ARGB: filter->lightingcolor = spec.argb; break; case RSVG_CSS_COLOR_PARSE_ERROR: rsvg_node_set_attribute_parse_error (node, "lighting-color", "Invalid color"); break; default: g_assert_not_reached (); } } if ((value = rsvg_property_bag_lookup (atts, "diffuseConstant"))) filter->diffuseConstant = g_ascii_strtod (value, NULL); if ((value = rsvg_property_bag_lookup (atts, "surfaceScale"))) filter->surfaceScale = g_ascii_strtod (value, NULL); } RsvgNode * rsvg_new_filter_primitive_diffuse_lighting (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveDiffuseLighting *filter; filter = g_new0 (RsvgFilterPrimitiveDiffuseLighting, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->surfaceScale = 1; filter->diffuseConstant = 1; filter->dx = 1; filter->dy = 1; filter->lightingcolor = 0xFFFFFFFF; filter->super.render = rsvg_filter_primitive_diffuse_lighting_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_DIFFUSE_LIGHTING, parent, rsvg_state_new (), filter, rsvg_filter_primitive_diffuse_lighting_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveSpecularLighting RsvgFilterPrimitiveSpecularLighting; struct _RsvgFilterPrimitiveSpecularLighting { RsvgFilterPrimitive super; double specularConstant; double specularExponent; double surfaceScale; guint32 lightingcolor; }; static void rsvg_filter_primitive_specular_lighting_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { RsvgFilterPrimitiveSpecularLighting *specular_lighting = (RsvgFilterPrimitiveSpecularLighting *) primitive; gint x, y; gdouble z, surfaceScale; gint rowstride, height, width; gdouble factor, max, base; vector3 lightcolor, color; vector3 L; cairo_matrix_t iaffine; RsvgIRect boundarys; RsvgNodeLightSource *source = NULL; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; source = find_light_source_in_children (node); if (source == NULL) return; iaffine = ctx->paffine; if (cairo_matrix_invert (&iaffine) != CAIRO_STATUS_SUCCESS) return; boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); in = rsvg_filter_get_in (primitive->in, ctx); if (in == NULL) return; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); height = cairo_image_surface_get_height (in); width = cairo_image_surface_get_width (in); rowstride = cairo_image_surface_get_stride (in); output = _rsvg_image_surface_new (width, height); if (output == NULL) { cairo_surface_destroy (in); return; } output_pixels = cairo_image_surface_get_data (output); color.x = ((guchar *) (&specular_lighting->lightingcolor))[2] / 255.0; color.y = ((guchar *) (&specular_lighting->lightingcolor))[1] / 255.0; color.z = ((guchar *) (&specular_lighting->lightingcolor))[0] / 255.0; surfaceScale = specular_lighting->surfaceScale / 255.0; for (y = boundarys.y0; y < boundarys.y1; y++) for (x = boundarys.x0; x < boundarys.x1; x++) { z = in_pixels[y * rowstride + x * 4 + 3] * surfaceScale; L = get_light_direction (source, x, y, z, &iaffine, ctx->ctx); L.z += 1; L = normalise (L); lightcolor = get_light_color (source, color, x, y, z, &iaffine, ctx->ctx); base = dotproduct (get_surface_normal (in_pixels, boundarys, x, y, 1, 1, 1.0 / ctx->paffine.xx, 1.0 / ctx->paffine.yy, specular_lighting->surfaceScale, rowstride, ctx->channelmap[3]), L); factor = specular_lighting->specularConstant * pow (base, specular_lighting->specularExponent) * 255; max = 0; if (max < lightcolor.x) max = lightcolor.x; if (max < lightcolor.y) max = lightcolor.y; if (max < lightcolor.z) max = lightcolor.z; max *= factor; if (max > 255) max = 255; if (max < 0) max = 0; output_pixels[y * rowstride + x * 4 + ctx->channelmap[0]] = lightcolor.x * max; output_pixels[y * rowstride + x * 4 + ctx->channelmap[1]] = lightcolor.y * max; output_pixels[y * rowstride + x * 4 + ctx->channelmap[2]] = lightcolor.z * max; output_pixels[y * rowstride + x * 4 + ctx->channelmap[3]] = max; } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_specular_lighting_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveSpecularLighting *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); if ((value = rsvg_property_bag_lookup (atts, "lighting-color"))) { RsvgCssColorSpec spec; RsvgState *state; spec = rsvg_css_parse_color (value, ALLOW_INHERIT_YES, ALLOW_CURRENT_COLOR_YES); switch (spec.kind) { case RSVG_CSS_COLOR_SPEC_INHERIT: /* FIXME: we should inherit; see how stop-color is handled in rsvg-styles.c */ break; case RSVG_CSS_COLOR_SPEC_CURRENT_COLOR: state = rsvg_state_new (); rsvg_state_reconstruct (state, node); filter->lightingcolor = state->current_color; break; case RSVG_CSS_COLOR_SPEC_ARGB: filter->lightingcolor = spec.argb; break; case RSVG_CSS_COLOR_PARSE_ERROR: rsvg_node_set_attribute_parse_error (node, "lighting-color", "Invalid color"); break; default: g_assert_not_reached (); } } if ((value = rsvg_property_bag_lookup (atts, "specularConstant"))) filter->specularConstant = g_ascii_strtod (value, NULL); if ((value = rsvg_property_bag_lookup (atts, "specularExponent"))) filter->specularExponent = g_ascii_strtod (value, NULL); if ((value = rsvg_property_bag_lookup (atts, "surfaceScale"))) filter->surfaceScale = g_ascii_strtod (value, NULL); } RsvgNode * rsvg_new_filter_primitive_specular_lighting (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveSpecularLighting *filter; filter = g_new0 (RsvgFilterPrimitiveSpecularLighting, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->surfaceScale = 1; filter->specularConstant = 1; filter->specularExponent = 1; filter->lightingcolor = 0xFFFFFFFF; filter->super.render = rsvg_filter_primitive_specular_lighting_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_SPECULAR_LIGHTING, parent, rsvg_state_new (), filter, rsvg_filter_primitive_specular_lighting_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); } /*************************************************************/ /*************************************************************/ typedef struct _RsvgFilterPrimitiveTile RsvgFilterPrimitiveTile; struct _RsvgFilterPrimitiveTile { RsvgFilterPrimitive super; }; static int mod (int a, int b) { while (a < 0) a += b; return a % b; } static void rsvg_filter_primitive_tile_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx) { guchar i; gint x, y, rowstride; RsvgIRect boundarys, oboundarys; RsvgFilterPrimitiveOutput input; guchar *in_pixels; guchar *output_pixels; cairo_surface_t *output, *in; oboundarys = rsvg_filter_primitive_get_bounds (primitive, ctx); input = rsvg_filter_get_result (primitive->in, ctx); in = input.surface; boundarys = input.bounds; cairo_surface_flush (in); in_pixels = cairo_image_surface_get_data (in); output = _rsvg_image_surface_new (ctx->width, ctx->height); if (output == NULL) { cairo_surface_destroy (in); return; } rowstride = cairo_image_surface_get_stride (output); output_pixels = cairo_image_surface_get_data (output); for (y = oboundarys.y0; y < oboundarys.y1; y++) for (x = oboundarys.x0; x < oboundarys.x1; x++) for (i = 0; i < 4; i++) { output_pixels[4 * x + y * rowstride + i] = in_pixels[(mod ((x - boundarys.x0), (boundarys.x1 - boundarys.x0)) + boundarys.x0) * 4 + (mod ((y - boundarys.y0), (boundarys.y1 - boundarys.y0)) + boundarys.y0) * rowstride + i]; } cairo_surface_mark_dirty (output); rsvg_filter_store_result (primitive->result, output, ctx); cairo_surface_destroy (in); cairo_surface_destroy (output); } static void rsvg_filter_primitive_tile_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts) { RsvgFilterPrimitiveTile *filter = impl; const char *value; if ((value = rsvg_property_bag_lookup (atts, "in"))) g_string_assign (filter->super.in, value); if ((value = rsvg_property_bag_lookup (atts, "result"))) g_string_assign (filter->super.result, value); filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts); } RsvgNode * rsvg_new_filter_primitive_tile (const char *element_name, RsvgNode *parent) { RsvgFilterPrimitiveTile *filter; filter = g_new0 (RsvgFilterPrimitiveTile, 1); filter->super.in = g_string_new ("none"); filter->super.result = g_string_new ("none"); filter->super.render = rsvg_filter_primitive_tile_render; return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_TILE, parent, rsvg_state_new (), filter, rsvg_filter_primitive_tile_set_atts, rsvg_filter_draw, rsvg_filter_primitive_free); }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_2580_0
crossvul-cpp_data_good_951_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % L AAA Y Y EEEEE RRRR % % L A A Y Y E R R % % L AAAAA Y EEE RRRR % % L A A Y E R R % % LLLLL A A Y EEEEE R R % % % % MagickCore Image Layering Methods % % % % Software Design % % Cristy % % Anthony Thyssen % % January 2006 % % % % % % Copyright 1999-2019 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://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/artifact.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/composite.h" #include "MagickCore/effect.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/profile.h" #include "MagickCore/resource_.h" #include "MagickCore/resize.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l e a r B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClearBounds() Clear the area specified by the bounds in an image to % transparency. This typically used to handle Background Disposal for the % previous frame in an animation sequence. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % void ClearBounds(Image *image,RectangleInfo *bounds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to had the area cleared in % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static void ClearBounds(Image *image,RectangleInfo *bounds, ExceptionInfo *exception) { ssize_t y; if (bounds->x < 0) return; if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); for (y=0; y < (ssize_t) bounds->height; y++) { register ssize_t x; register Quantum *magick_restrict q; q=GetAuthenticPixels(image,bounds->x,bounds->y+y,bounds->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) bounds->width; x++) { SetPixelAlpha(image,TransparentAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s B o u n d s C l e a r e d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsBoundsCleared() tests whether any pixel in the bounds given, gets cleared % when going from the first image to the second image. This typically used % to check if a proposed disposal method will work successfully to generate % the second frame image from the first disposed form of the previous frame. % % Warning: no bounds checks are performed, except for the null or missed % image, for images that don't change. in all other cases bound must fall % within the image. % % The format is: % % MagickBooleanType IsBoundsCleared(const Image *image1, % const Image *image2,RectangleInfo bounds,ExceptionInfo *exception) % % A description of each parameter follows: % % o image1, image 2: the images to check for cleared pixels % % o bounds: the area to be clear within the imag image % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsBoundsCleared(const Image *image1, const Image *image2,RectangleInfo *bounds,ExceptionInfo *exception) { register const Quantum *p, *q; register ssize_t x; ssize_t y; if (bounds->x < 0) return(MagickFalse); for (y=0; y < (ssize_t) bounds->height; y++) { p=GetVirtualPixels(image1,bounds->x,bounds->y+y,bounds->width,1,exception); q=GetVirtualPixels(image2,bounds->x,bounds->y+y,bounds->width,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) bounds->width; x++) { if ((GetPixelAlpha(image1,p) >= (Quantum) (QuantumRange/2)) && (GetPixelAlpha(image2,q) < (Quantum) (QuantumRange/2))) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) bounds->width) break; } return(y < (ssize_t) bounds->height ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o a l e s c e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CoalesceImages() composites a set of images while respecting any page % offsets and disposal methods. GIF, MIFF, and MNG animation sequences % typically start with an image background and each subsequent image % varies in size and offset. A new image sequence is returned with all % images the same size as the first images virtual canvas and composited % with the next image in the sequence. % % The format of the CoalesceImages method is: % % Image *CoalesceImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CoalesceImages(const Image *image,ExceptionInfo *exception) { Image *coalesce_image, *dispose_image, *previous; register Image *next; RectangleInfo bounds; /* Coalesce the image sequence. */ 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); next=GetFirstImageInList(image); bounds=next->page; if (bounds.width == 0) { bounds.width=next->columns; if (bounds.x > 0) bounds.width+=bounds.x; } if (bounds.height == 0) { bounds.height=next->rows; if (bounds.y > 0) bounds.height+=bounds.y; } bounds.x=0; bounds.y=0; coalesce_image=CloneImage(next,bounds.width,bounds.height,MagickTrue, exception); if (coalesce_image == (Image *) NULL) return((Image *) NULL); coalesce_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(coalesce_image,exception); coalesce_image->alpha_trait=next->alpha_trait; coalesce_image->page=bounds; coalesce_image->dispose=NoneDispose; /* Coalesce rest of the images. */ dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); (void) CompositeImage(coalesce_image,next,CopyCompositeOp,MagickTrue, next->page.x,next->page.y,exception); next=GetNextImageInList(next); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { /* Determine the bounds that was overlaid in the previous image. */ previous=GetPreviousImageInList(next); bounds=previous->page; bounds.width=previous->columns; bounds.height=previous->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) coalesce_image->columns) bounds.width=coalesce_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) coalesce_image->rows) bounds.height=coalesce_image->rows-bounds.y; /* Replace the dispose image with the new coalesced image. */ if (GetPreviousImageInList(next)->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=CloneImage(coalesce_image,0,0,MagickTrue,exception); if (dispose_image == (Image *) NULL) { coalesce_image=DestroyImageList(coalesce_image); return((Image *) NULL); } } /* Clear the overlaid area of the coalesced bounds for background disposal */ if (next->previous->dispose == BackgroundDispose) ClearBounds(dispose_image,&bounds,exception); /* Next image is the dispose image, overlaid with next frame in sequence. */ coalesce_image->next=CloneImage(dispose_image,0,0,MagickTrue,exception); coalesce_image->next->previous=coalesce_image; previous=coalesce_image; coalesce_image=GetNextImageInList(coalesce_image); (void) CompositeImage(coalesce_image,next, next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp, MagickTrue,next->page.x,next->page.y,exception); (void) CloneImageProfiles(coalesce_image,next); (void) CloneImageProperties(coalesce_image,next); (void) CloneImageArtifacts(coalesce_image,next); coalesce_image->page=previous->page; /* If a pixel goes opaque to transparent, use background dispose. */ if (IsBoundsCleared(previous,coalesce_image,&bounds,exception) != MagickFalse) coalesce_image->dispose=BackgroundDispose; else coalesce_image->dispose=NoneDispose; previous->dispose=coalesce_image->dispose; } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(coalesce_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D i s p o s e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DisposeImages() returns the coalesced frames of a GIF animation as it would % appear after the GIF dispose method of that frame has been applied. That is % it returned the appearance of each frame before the next is overlaid. % % The format of the DisposeImages method is: % % Image *DisposeImages(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *DisposeImages(const Image *images,ExceptionInfo *exception) { Image *dispose_image, *dispose_images; RectangleInfo bounds; register Image *image, *next; /* Run the image through the animation sequence */ assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(images); dispose_image=CloneImage(image,image->page.width,image->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return((Image *) NULL); dispose_image->page=image->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(dispose_image,exception); dispose_images=NewImageList(); for (next=image; image != (Image *) NULL; image=GetNextImageInList(image)) { Image *current_image; /* Overlay this frame's image over the previous disposal image. */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } (void) CompositeImage(current_image,next, next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp, MagickTrue,next->page.x,next->page.y,exception); /* Handle Background dispose: image is displayed for the delay period. */ if (next->dispose == BackgroundDispose) { bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds,exception); } /* Select the appropriate previous/disposed image. */ if (next->dispose == PreviousDispose) current_image=DestroyImage(current_image); else { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; current_image=(Image *) NULL; } /* Save the dispose image just calculated for return. */ { Image *dispose; dispose=CloneImage(dispose_image,0,0,MagickTrue,exception); if (dispose == (Image *) NULL) { dispose_images=DestroyImageList(dispose_images); dispose_image=DestroyImage(dispose_image); return((Image *) NULL); } (void) CloneImageProfiles(dispose,next); (void) CloneImageProperties(dispose,next); (void) CloneImageArtifacts(dispose,next); dispose->page.x=0; dispose->page.y=0; dispose->dispose=next->dispose; AppendImageToList(&dispose_images,dispose); } } dispose_image=DestroyImage(dispose_image); return(GetFirstImageInList(dispose_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComparePixels() Compare the two pixels and return true if the pixels % differ according to the given LayerType comparision method. % % This currently only used internally by CompareImagesBounds(). It is % doubtful that this sub-routine will be useful outside this module. % % The format of the ComparePixels method is: % % MagickBooleanType *ComparePixels(const LayerMethod method, % const PixelInfo *p,const PixelInfo *q) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o p, q: the pixels to test for appropriate differences. % */ static MagickBooleanType ComparePixels(const LayerMethod method, const PixelInfo *p,const PixelInfo *q) { double o1, o2; /* Any change in pixel values */ if (method == CompareAnyLayer) return((MagickBooleanType)(IsFuzzyEquivalencePixelInfo(p,q) == MagickFalse)); o1 = (p->alpha_trait != UndefinedPixelTrait) ? p->alpha : OpaqueAlpha; o2 = (q->alpha_trait != UndefinedPixelTrait) ? q->alpha : OpaqueAlpha; /* Pixel goes from opaque to transprency. */ if (method == CompareClearLayer) return((MagickBooleanType) ( (o1 >= ((double) QuantumRange/2.0)) && (o2 < ((double) QuantumRange/2.0)) ) ); /* Overlay would change first pixel by second. */ if (method == CompareOverlayLayer) { if (o2 < ((double) QuantumRange/2.0)) return MagickFalse; return((MagickBooleanType) (IsFuzzyEquivalencePixelInfo(p,q) == MagickFalse)); } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o m p a r e I m a g e B o u n d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImagesBounds() Given two images return the smallest rectangular area % by which the two images differ, accourding to the given 'Compare...' % layer method. % % This currently only used internally in this module, but may eventually % be used by other modules. % % The format of the CompareImagesBounds method is: % % RectangleInfo *CompareImagesBounds(const LayerMethod method, % const Image *image1,const Image *image2,ExceptionInfo *exception) % % A description of each parameter follows: % % o method: What differences to look for. Must be one of CompareAnyLayer, % CompareClearLayer, CompareOverlayLayer. % % o image1, image2: the two images to compare. % % o exception: return any errors or warnings in this structure. % */ static RectangleInfo CompareImagesBounds(const Image *image1, const Image *image2,const LayerMethod method,ExceptionInfo *exception) { RectangleInfo bounds; PixelInfo pixel1, pixel2; register const Quantum *p, *q; register ssize_t x; ssize_t y; /* Set bounding box of the differences between images. */ GetPixelInfo(image1,&pixel1); GetPixelInfo(image2,&pixel2); for (x=0; x < (ssize_t) image1->columns; x++) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (y=0; y < (ssize_t) image1->rows; y++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (y < (ssize_t) image1->rows) break; } if (x >= (ssize_t) image1->columns) { /* Images are identical, return a null image. */ bounds.x=-1; bounds.y=-1; bounds.width=1; bounds.height=1; return(bounds); } bounds.x=x; for (x=(ssize_t) image1->columns-1; x >= 0; x--) { p=GetVirtualPixels(image1,x,0,1,image1->rows,exception); q=GetVirtualPixels(image2,x,0,1,image2->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (y=0; y < (ssize_t) image1->rows; y++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (y < (ssize_t) image1->rows) break; } bounds.width=(size_t) (x-bounds.x+1); for (y=0; y < (ssize_t) image1->rows; y++) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image1->columns; x++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) image1->columns) break; } bounds.y=y; for (y=(ssize_t) image1->rows-1; y >= 0; y--) { p=GetVirtualPixels(image1,0,y,image1->columns,1,exception); q=GetVirtualPixels(image2,0,y,image2->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) image1->columns; x++) { GetPixelInfoPixel(image1,p,&pixel1); GetPixelInfoPixel(image2,q,&pixel2); if (ComparePixels(method,&pixel1,&pixel2)) break; p+=GetPixelChannels(image1); q+=GetPixelChannels(image2); } if (x < (ssize_t) image1->columns) break; } bounds.height=(size_t) (y-bounds.y+1); return(bounds); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p a r e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompareImagesLayers() compares each image with the next in a sequence and % returns the minimum bounding region of all the pixel differences (of the % LayerMethod specified) it discovers. % % Images do NOT have to be the same size, though it is best that all the % images are 'coalesced' (images are all the same size, on a flattened % canvas, so as to represent exactly how an specific frame should look). % % No GIF dispose methods are applied, so GIF animations must be coalesced % before applying this image operator to find differences to them. % % The format of the CompareImagesLayers method is: % % Image *CompareImagesLayers(const Image *images, % const LayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers type to compare images with. Must be one of... % CompareAnyLayer, CompareClearLayer, CompareOverlayLayer. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CompareImagesLayers(const Image *image, const LayerMethod method,ExceptionInfo *exception) { Image *image_a, *image_b, *layers; RectangleInfo *bounds; register const Image *next; register ssize_t i; assert(image != (const 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); assert((method == CompareAnyLayer) || (method == CompareClearLayer) || (method == CompareOverlayLayer)); /* Allocate bounds memory. */ next=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(next),sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Set up first comparision images. */ image_a=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (image_a == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_a->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(image_a,exception); image_a->page=next->page; image_a->page.x=0; image_a->page.y=0; (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); /* Compute the bounding box of changes for the later images */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { image_b=CloneImage(image_a,0,0,MagickTrue,exception); if (image_b == (Image *) NULL) { image_a=DestroyImage(image_a); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); bounds[i]=CompareImagesBounds(image_b,image_a,method,exception); image_b=DestroyImage(image_b); i++; } image_a=DestroyImage(image_a); /* Clone first image in sequence. */ next=GetFirstImageInList(image); layers=CloneImage(next,0,0,MagickTrue,exception); if (layers == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } /* Deconstruct the image sequence. */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { if ((bounds[i].x == -1) && (bounds[i].y == -1) && (bounds[i].width == 1) && (bounds[i].height == 1)) { /* An empty frame is returned from CompareImageBounds(), which means the current frame is identical to the previous frame. */ i++; continue; } image_a=CloneImage(next,0,0,MagickTrue,exception); if (image_a == (Image *) NULL) break; image_b=CropImage(image_a,&bounds[i],exception); image_a=DestroyImage(image_a); if (image_b == (Image *) NULL) break; AppendImageToList(&layers,image_b); i++; } bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); if (next != (Image *) NULL) { layers=DestroyImageList(layers); return((Image *) NULL); } return(GetFirstImageInList(layers)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p t i m i z e L a y e r F r a m e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeLayerFrames() takes a coalesced GIF animation, and compares each % frame against the three different 'disposal' forms of the previous frame. % From this it then attempts to select the smallest cropped image and % disposal method needed to reproduce the resulting image. % % Note that this not easy, and may require the expansion of the bounds % of previous frame, simply clear pixels for the next animation frame to % transparency according to the selected dispose method. % % The format of the OptimizeLayerFrames method is: % % Image *OptimizeLayerFrames(const Image *image, % const LayerMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o method: the layers technique to optimize with. Must be one of... % OptimizeImageLayer, or OptimizePlusLayer. The Plus form allows % the addition of extra 'zero delay' frames to clear pixels from % the previous frame, and the removal of frames that done change, % merging the delay times together. % % o exception: return any errors or warnings in this structure. % */ /* Define a 'fake' dispose method where the frame is duplicated, (for OptimizePlusLayer) with a extra zero time delay frame which does a BackgroundDisposal to clear the pixels that need to be cleared. */ #define DupDispose ((DisposeType)9) /* Another 'fake' dispose method used to removed frames that don't change. */ #define DelDispose ((DisposeType)8) #define DEBUG_OPT_FRAME 0 static Image *OptimizeLayerFrames(const Image *image,const LayerMethod method, ExceptionInfo *exception) { ExceptionInfo *sans_exception; Image *prev_image, *dup_image, *bgnd_image, *optimized_image; RectangleInfo try_bounds, bgnd_bounds, dup_bounds, *bounds; MagickBooleanType add_frames, try_cleared, cleared; DisposeType *disposals; register const Image *curr; register ssize_t i; assert(image != (const 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); assert(method == OptimizeLayer || method == OptimizeImageLayer || method == OptimizePlusLayer); /* Are we allowed to add/remove frames from animation? */ add_frames=method == OptimizePlusLayer ? MagickTrue : MagickFalse; /* Ensure all the images are the same size. */ curr=GetFirstImageInList(image); for (; curr != (Image *) NULL; curr=GetNextImageInList(curr)) { if ((curr->columns != image->columns) || (curr->rows != image->rows)) ThrowImageException(OptionError,"ImagesAreNotTheSameSize"); if ((curr->page.x != 0) || (curr->page.y != 0) || (curr->page.width != image->page.width) || (curr->page.height != image->page.height)) ThrowImageException(OptionError,"ImagePagesAreNotCoalesced"); } /* Allocate memory (times 2 if we allow the use of frame duplications) */ curr=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(curr),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); disposals=(DisposeType *) AcquireQuantumMemory((size_t) GetImageListLength(image),(add_frames != MagickFalse ? 2UL : 1UL)* sizeof(*disposals)); if (disposals == (DisposeType *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Initialise Previous Image as fully transparent */ prev_image=CloneImage(curr,curr->columns,curr->rows,MagickTrue,exception); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } prev_image->page=curr->page; /* ERROR: <-- should not be need, but is! */ prev_image->page.x=0; prev_image->page.y=0; prev_image->dispose=NoneDispose; prev_image->background_color.alpha_trait=BlendPixelTrait; prev_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(prev_image,exception); /* Figure out the area of overlay of the first frame No pixel could be cleared as all pixels are already cleared. */ #if DEBUG_OPT_FRAME i=0; (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif disposals[0]=NoneDispose; bounds[0]=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g\n\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); #endif /* Compute the bounding box of changes for each pair of images. */ i=1; bgnd_image=(Image *) NULL; dup_image=(Image *) NULL; dup_bounds.width=0; dup_bounds.height=0; dup_bounds.x=0; dup_bounds.y=0; curr=GetNextImageInList(curr); for ( ; curr != (const Image *) NULL; curr=GetNextImageInList(curr)) { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"frame %.20g :-\n",(double) i); #endif /* Assume none disposal is the best */ bounds[i]=CompareImagesBounds(curr->previous,curr,CompareAnyLayer,exception); cleared=IsBoundsCleared(curr->previous,curr,&bounds[i],exception); disposals[i-1]=NoneDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "overlay: %.20gx%.20g%+.20g%+.20g%s%s\n", (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y, bounds[i].x < 0?" (unchanged)":"", cleared?" (pixels cleared)":""); #endif if ( bounds[i].x < 0 ) { /* Image frame is exactly the same as the previous frame! If not adding frames leave it to be cropped down to a null image. Otherwise mark previous image for deleted, transfering its crop bounds to the current image. */ if ( add_frames && i>=2 ) { disposals[i-1]=DelDispose; disposals[i]=NoneDispose; bounds[i]=bounds[i-1]; i++; continue; } } else { /* Compare a none disposal against a previous disposal */ try_bounds=CompareImagesBounds(prev_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(prev_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "test_prev: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels were cleared)":""); #endif if ( (!try_cleared && cleared ) || try_bounds.width * try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=try_cleared; bounds[i]=try_bounds; disposals[i-1]=PreviousDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"previous: accepted\n"); } else { (void) FormatLocaleFile(stderr,"previous: rejected\n"); #endif } /* If we are allowed lets try a complex frame duplication. It is useless if the previous image already clears pixels correctly. This method will always clear all the pixels that need to be cleared. */ dup_bounds.width=dup_bounds.height=0; /* no dup, no pixel added */ if ( add_frames ) { dup_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (dup_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); return((Image *) NULL); } dup_bounds=CompareImagesBounds(dup_image,curr,CompareClearLayer,exception); ClearBounds(dup_image,&dup_bounds,exception); try_bounds=CompareImagesBounds(dup_image,curr,CompareAnyLayer,exception); if ( cleared || dup_bounds.width*dup_bounds.height +try_bounds.width*try_bounds.height < bounds[i].width * bounds[i].height ) { cleared=MagickFalse; bounds[i]=try_bounds; disposals[i-1]=DupDispose; /* to be finalised later, if found to be optimial */ } else dup_bounds.width=dup_bounds.height=0; } /* Now compare against a simple background disposal */ bgnd_image=CloneImage(curr->previous,0,0,MagickTrue,exception); if (bgnd_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); prev_image=DestroyImage(prev_image); if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); return((Image *) NULL); } bgnd_bounds=bounds[i-1]; /* interum bounds of the previous image */ ClearBounds(bgnd_image,&bgnd_bounds,exception); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "background: %s\n", try_cleared?"(pixels cleared)":""); #endif if ( try_cleared ) { /* Straight background disposal failed to clear pixels needed! Lets try expanding the disposal area of the previous frame, to include the pixels that are cleared. This guaranteed to work, though may not be the most optimized solution. */ try_bounds=CompareImagesBounds(curr->previous,curr,CompareClearLayer,exception); #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_clear: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_bounds.x<0?" (no expand nessary)":""); #endif if ( bgnd_bounds.x < 0 ) bgnd_bounds = try_bounds; else { #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "expand_bgnd: %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif if ( try_bounds.x < bgnd_bounds.x ) { bgnd_bounds.width+= bgnd_bounds.x-try_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; bgnd_bounds.x = try_bounds.x; } else { try_bounds.width += try_bounds.x - bgnd_bounds.x; if ( bgnd_bounds.width < try_bounds.width ) bgnd_bounds.width = try_bounds.width; } if ( try_bounds.y < bgnd_bounds.y ) { bgnd_bounds.height += bgnd_bounds.y - try_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; bgnd_bounds.y = try_bounds.y; } else { try_bounds.height += try_bounds.y - bgnd_bounds.y; if ( bgnd_bounds.height < try_bounds.height ) bgnd_bounds.height = try_bounds.height; } #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, " to : %.20gx%.20g%+.20g%+.20g\n", (double) bgnd_bounds.width,(double) bgnd_bounds.height, (double) bgnd_bounds.x,(double) bgnd_bounds.y ); #endif } ClearBounds(bgnd_image,&bgnd_bounds,exception); #if DEBUG_OPT_FRAME /* Something strange is happening with a specific animation * CompareAnyLayers (normal method) and CompareClearLayers returns the whole * image, which is not posibly correct! As verified by previous tests. * Something changed beyond the bgnd_bounds clearing. But without being able * to see, or writet he image at this point it is hard to tell what is wrong! * Only CompareOverlay seemed to return something sensible. */ try_bounds=CompareImagesBounds(bgnd_image,curr,CompareClearLayer,exception); (void) FormatLocaleFile(stderr, "expand_ctst: %.20gx%.20g%+.20g%+.20g\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y ); try_bounds=CompareImagesBounds(bgnd_image,curr,CompareAnyLayer,exception); try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_any : %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif try_bounds=CompareImagesBounds(bgnd_image,curr,CompareOverlayLayer,exception); #if DEBUG_OPT_FRAME try_cleared=IsBoundsCleared(bgnd_image,curr,&try_bounds,exception); (void) FormatLocaleFile(stderr, "expand_test: %.20gx%.20g%+.20g%+.20g%s\n", (double) try_bounds.width,(double) try_bounds.height, (double) try_bounds.x,(double) try_bounds.y, try_cleared?" (pixels cleared)":""); #endif } /* Test if this background dispose is smaller than any of the other methods we tryed before this (including duplicated frame) */ if ( cleared || bgnd_bounds.width*bgnd_bounds.height +try_bounds.width*try_bounds.height < bounds[i-1].width*bounds[i-1].height +dup_bounds.width*dup_bounds.height +bounds[i].width*bounds[i].height ) { cleared=MagickFalse; bounds[i-1]=bgnd_bounds; bounds[i]=try_bounds; if ( disposals[i-1] == DupDispose ) dup_image=DestroyImage(dup_image); disposals[i-1]=BackgroundDispose; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr,"expand_bgnd: accepted\n"); } else { (void) FormatLocaleFile(stderr,"expand_bgnd: reject\n"); #endif } } /* Finalise choice of dispose, set new prev_image, and junk any extra images as appropriate, */ if ( disposals[i-1] == DupDispose ) { if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); prev_image=DestroyImage(prev_image); prev_image=dup_image, dup_image=(Image *) NULL; bounds[i+1]=bounds[i]; bounds[i]=dup_bounds; disposals[i-1]=DupDispose; disposals[i]=BackgroundDispose; i++; } else { if ( dup_image != (Image *) NULL) dup_image=DestroyImage(dup_image); if ( disposals[i-1] != PreviousDispose ) prev_image=DestroyImage(prev_image); if ( disposals[i-1] == BackgroundDispose ) prev_image=bgnd_image, bgnd_image=(Image *) NULL; if (bgnd_image != (Image *) NULL) bgnd_image=DestroyImage(bgnd_image); if ( disposals[i-1] == NoneDispose ) { prev_image=ReferenceImage(curr->previous); if (prev_image == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); return((Image *) NULL); } } } assert(prev_image != (Image *) NULL); disposals[i]=disposals[i-1]; #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "final %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i-1, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i-1]), (double) bounds[i-1].width,(double) bounds[i-1].height, (double) bounds[i-1].x,(double) bounds[i-1].y ); #endif #if DEBUG_OPT_FRAME (void) FormatLocaleFile(stderr, "interum %.20g : %s %.20gx%.20g%+.20g%+.20g\n", (double) i, CommandOptionToMnemonic(MagickDisposeOptions,disposals[i]), (double) bounds[i].width,(double) bounds[i].height, (double) bounds[i].x,(double) bounds[i].y ); (void) FormatLocaleFile(stderr,"\n"); #endif i++; } prev_image=DestroyImage(prev_image); /* Optimize all images in sequence. */ sans_exception=AcquireExceptionInfo(); i=0; curr=GetFirstImageInList(image); optimized_image=NewImageList(); while ( curr != (const Image *) NULL ) { prev_image=CloneImage(curr,0,0,MagickTrue,exception); if (prev_image == (Image *) NULL) break; if (prev_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(prev_image,OpaqueAlphaChannel,exception); if ( disposals[i] == DelDispose ) { size_t time = 0; while ( disposals[i] == DelDispose ) { time += curr->delay*1000/curr->ticks_per_second; curr=GetNextImageInList(curr); i++; } time += curr->delay*1000/curr->ticks_per_second; prev_image->ticks_per_second = 100L; prev_image->delay = time*prev_image->ticks_per_second/1000; } bgnd_image=CropImage(prev_image,&bounds[i],sans_exception); prev_image=DestroyImage(prev_image); if (bgnd_image == (Image *) NULL) break; bgnd_image->dispose=disposals[i]; if ( disposals[i] == DupDispose ) { bgnd_image->delay=0; bgnd_image->dispose=NoneDispose; } else curr=GetNextImageInList(curr); AppendImageToList(&optimized_image,bgnd_image); i++; } sans_exception=DestroyExceptionInfo(sans_exception); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); disposals=(DisposeType *) RelinquishMagickMemory(disposals); if (curr != (Image *) NULL) { optimized_image=DestroyImageList(optimized_image); return((Image *) NULL); } return(GetFirstImageInList(optimized_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageLayers() compares each image the GIF disposed forms of the % previous image in the sequence. From this it attempts to select the % smallest cropped image to replace each frame, while preserving the results % of the GIF animation. % % The format of the OptimizeImageLayers method is: % % Image *OptimizeImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizeImageLayers(const Image *image, ExceptionInfo *exception) { return(OptimizeLayerFrames(image,OptimizeImageLayer,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e P l u s I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImagePlusLayers() is exactly as OptimizeImageLayers(), but may % also add or even remove extra frames in the animation, if it improves % the total number of pixels in the resulting GIF animation. % % The format of the OptimizePlusImageLayers method is: % % Image *OptimizePlusImageLayers(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *OptimizePlusImageLayers(const Image *image, ExceptionInfo *exception) { return OptimizeLayerFrames(image,OptimizePlusLayer,exception); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O p t i m i z e I m a g e T r a n s p a r e n c y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimizeImageTransparency() takes a frame optimized GIF animation, and % compares the overlayed pixels against the disposal image resulting from all % the previous frames in the animation. Any pixel that does not change the % disposal image (and thus does not effect the outcome of an overlay) is made % transparent. % % WARNING: This modifies the current images directly, rather than generate % a new image sequence. % % The format of the OptimizeImageTransperency method is: % % void OptimizeImageTransperency(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image sequence % % o exception: return any errors or warnings in this structure. % */ MagickExport void OptimizeImageTransparency(const Image *image, ExceptionInfo *exception) { Image *dispose_image; register Image *next; /* Run the image through the animation sequence */ 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); next=GetFirstImageInList(image); dispose_image=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (dispose_image == (Image *) NULL) return; dispose_image->page=next->page; dispose_image->page.x=0; dispose_image->page.y=0; dispose_image->dispose=NoneDispose; dispose_image->background_color.alpha_trait=BlendPixelTrait; dispose_image->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(dispose_image,exception); while ( next != (Image *) NULL ) { Image *current_image; /* Overlay this frame's image over the previous disposal image */ current_image=CloneImage(dispose_image,0,0,MagickTrue,exception); if (current_image == (Image *) NULL) { dispose_image=DestroyImage(dispose_image); return; } (void) CompositeImage(current_image,next,next->alpha_trait != UndefinedPixelTrait ? OverCompositeOp : CopyCompositeOp,MagickTrue,next->page.x,next->page.y, exception); /* At this point the image would be displayed, for the delay period ** Work out the disposal of the previous image */ if (next->dispose == BackgroundDispose) { RectangleInfo bounds=next->page; bounds.width=next->columns; bounds.height=next->rows; if (bounds.x < 0) { bounds.width+=bounds.x; bounds.x=0; } if ((ssize_t) (bounds.x+bounds.width) > (ssize_t) current_image->columns) bounds.width=current_image->columns-bounds.x; if (bounds.y < 0) { bounds.height+=bounds.y; bounds.y=0; } if ((ssize_t) (bounds.y+bounds.height) > (ssize_t) current_image->rows) bounds.height=current_image->rows-bounds.y; ClearBounds(current_image,&bounds,exception); } if (next->dispose != PreviousDispose) { dispose_image=DestroyImage(dispose_image); dispose_image=current_image; } else current_image=DestroyImage(current_image); /* Optimize Transparency of the next frame (if present) */ next=GetNextImageInList(next); if (next != (Image *) NULL) { (void) CompositeImage(next,dispose_image,ChangeMaskCompositeOp, MagickTrue,-(next->page.x),-(next->page.y),exception); } } dispose_image=DestroyImage(dispose_image); return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e D u p l i c a t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveDuplicateLayers() removes any image that is exactly the same as the % next image in the given image list. Image size and virtual canvas offset % must also match, though not the virtual canvas size itself. % % No check is made with regards to image disposal setting, though it is the % dispose setting of later image that is kept. Also any time delays are also % added together. As such coalesced image animations should still produce the % same result, though with duplicte frames merged into a single frame. % % The format of the RemoveDuplicateLayers method is: % % void RemoveDuplicateLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveDuplicateLayers(Image **images,ExceptionInfo *exception) { RectangleInfo bounds; register Image *image, *next; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", (*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=GetFirstImageInList(*images); for ( ; (next=GetNextImageInList(image)) != (Image *) NULL; image=next) { if ((image->columns != next->columns) || (image->rows != next->rows) || (image->page.x != next->page.x) || (image->page.y != next->page.y)) continue; bounds=CompareImagesBounds(image,next,CompareAnyLayer,exception); if (bounds.x < 0) { /* Two images are the same, merge time delays and delete one. */ size_t time; time=1000*image->delay*PerceptibleReciprocal(image->ticks_per_second); time+=1000*next->delay*PerceptibleReciprocal(next->ticks_per_second); next->ticks_per_second=100L; next->delay=time*image->ticks_per_second/1000; next->iterations=image->iterations; *images=image; (void) DeleteImageFromList(images); } } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e Z e r o D e l a y L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveZeroDelayLayers() removes any image that as a zero delay time. Such % images generally represent intermediate or partial updates in GIF % animations used for file optimization. They are not ment to be displayed % to users of the animation. Viewable images in an animation should have a % time delay of 3 or more centi-seconds (hundredths of a second). % % However if all the frames have a zero time delay, then either the animation % is as yet incomplete, or it is not a GIF animation. This a non-sensible % situation, so no image will be removed and a 'Zero Time Animation' warning % (exception) given. % % No warning will be given if no image was removed because all images had an % appropriate non-zero time delay set. % % Due to the special requirements of GIF disposal handling, GIF animations % should be coalesced first, before calling this function, though that is not % a requirement. % % The format of the RemoveZeroDelayLayers method is: % % void RemoveZeroDelayLayers(Image **image,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image list % % o exception: return any errors or warnings in this structure. % */ MagickExport void RemoveZeroDelayLayers(Image **images, ExceptionInfo *exception) { Image *i; assert((*images) != (const Image *) NULL); assert((*images)->signature == MagickCoreSignature); if ((*images)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*images)->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); i=GetFirstImageInList(*images); for ( ; i != (Image *) NULL; i=GetNextImageInList(i)) if ( i->delay != 0L ) break; if ( i == (Image *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "ZeroTimeAnimation","`%s'",GetFirstImageInList(*images)->filename); return; } i=GetFirstImageInList(*images); while ( i != (Image *) NULL ) { if ( i->delay == 0L ) { (void) DeleteImageFromList(&i); *images=i; } else i=GetNextImageInList(i); } *images=GetFirstImageInList(*images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeLayers() compose the source image sequence over the destination % image sequence, starting with the current image in both lists. % % Each layer from the two image lists are composted together until the end of % one of the image lists is reached. The offset of each composition is also % adjusted to match the virtual canvas offsets of each layer. As such the % given offset is relative to the virtual canvas, and not the actual image. % % Composition uses given x and y offsets, as the 'origin' location of the % source images virtual canvas (not the real image) allowing you to compose a % list of 'layer images' into the destiantioni images. This makes it well % sutiable for directly composing 'Clears Frame Animations' or 'Coaleased % Animations' onto a static or other 'Coaleased Animation' destination image % list. GIF disposal handling is not looked at. % % Special case:- If one of the image sequences is the last image (just a % single image remaining), that image is repeatally composed with all the % images in the other image list. Either the source or destination lists may % be the single image, for this situation. % % In the case of a single destination image (or last image given), that image % will ve cloned to match the number of images remaining in the source image % list. % % This is equivelent to the "-layer Composite" Shell API operator. % % % The format of the CompositeLayers method is: % % void CompositeLayers(Image *destination, const CompositeOperator % compose, Image *source, const ssize_t x_offset, const ssize_t y_offset, % ExceptionInfo *exception); % % A description of each parameter follows: % % o destination: the destination images and results % % o source: source image(s) for the layer composition % % o compose, x_offset, y_offset: arguments passed on to CompositeImages() % % o exception: return any errors or warnings in this structure. % */ static inline void CompositeCanvas(Image *destination, const CompositeOperator compose,Image *source,ssize_t x_offset, ssize_t y_offset,ExceptionInfo *exception) { const char *value; x_offset+=source->page.x-destination->page.x; y_offset+=source->page.y-destination->page.y; value=GetImageArtifact(source,"compose:outside-overlay"); (void) CompositeImage(destination,source,compose, (value != (const char *) NULL) && (IsStringTrue(value) != MagickFalse) ? MagickFalse : MagickTrue,x_offset,y_offset,exception); } MagickExport void CompositeLayers(Image *destination, const CompositeOperator compose, Image *source,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { assert(destination != (Image *) NULL); assert(destination->signature == MagickCoreSignature); assert(source != (Image *) NULL); assert(source->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (source->debug != MagickFalse || destination->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s - %s", source->filename,destination->filename); /* Overlay single source image over destation image/list */ if ( source->next == (Image *) NULL ) while ( destination != (Image *) NULL ) { CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); destination=GetNextImageInList(destination); } /* Overlay source image list over single destination. Multiple clones of destination image are created to match source list. Original Destination image becomes first image of generated list. As such the image list pointer does not require any change in caller. Some animation attributes however also needs coping in this case. */ else if ( destination->next == (Image *) NULL ) { Image *dest = CloneImage(destination,0,0,MagickTrue,exception); CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); /* copy source image attributes ? */ if ( source->next != (Image *) NULL ) { destination->delay = source->delay; destination->iterations = source->iterations; } source=GetNextImageInList(source); while ( source != (Image *) NULL ) { AppendImageToList(&destination, CloneImage(dest,0,0,MagickTrue,exception)); destination=GetLastImageInList(destination); CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); destination->delay = source->delay; destination->iterations = source->iterations; source=GetNextImageInList(source); } dest=DestroyImage(dest); } /* Overlay a source image list over a destination image list until either list runs out of images. (Does not repeat) */ else while ( source != (Image *) NULL && destination != (Image *) NULL ) { CompositeCanvas(destination, compose, source, x_offset, y_offset, exception); source=GetNextImageInList(source); destination=GetNextImageInList(destination); } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e r g e I m a g e L a y e r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MergeImageLayers() composes all the image layers from the current given % image onward to produce a single image of the merged layers. % % The inital canvas's size depends on the given LayerMethod, and is % initialized using the first images background color. The images % are then compositied onto that image in sequence using the given % composition that has been assigned to each individual image. % % The format of the MergeImageLayers is: % % Image *MergeImageLayers(Image *image,const LayerMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image list to be composited together % % o method: the method of selecting the size of the initial canvas. % % MergeLayer: Merge all layers onto a canvas just large enough % to hold all the actual images. The virtual canvas of the % first image is preserved but otherwise ignored. % % FlattenLayer: Use the virtual canvas size of first image. % Images which fall outside this canvas is clipped. % This can be used to 'fill out' a given virtual canvas. % % MosaicLayer: Start with the virtual canvas of the first image, % enlarging left and right edges to contain all images. % Images with negative offsets will be clipped. % % TrimBoundsLayer: Determine the overall bounds of all the image % layers just as in "MergeLayer", then adjust the the canvas % and offsets to be relative to those bounds, without overlaying % the images. % % WARNING: a new image is not returned, the original image % sequence page data is modified instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MergeImageLayers(Image *image,const LayerMethod method, ExceptionInfo *exception) { #define MergeLayersTag "Merge/Layers" Image *canvas; MagickBooleanType proceed; RectangleInfo page; register const Image *next; size_t number_images, height, width; ssize_t scene; 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); /* Determine canvas image size, and its virtual canvas size and offset */ page=image->page; width=image->columns; height=image->rows; switch (method) { case TrimBoundsLayer: case MergeLayer: default: { next=GetNextImageInList(image); for ( ; next != (Image *) NULL; next=GetNextImageInList(next)) { if (page.x > next->page.x) { width+=page.x-next->page.x; page.x=next->page.x; } if (page.y > next->page.y) { height+=page.y-next->page.y; page.y=next->page.y; } if ((ssize_t) width < (next->page.x+(ssize_t) next->columns-page.x)) width=(size_t) next->page.x+(ssize_t) next->columns-page.x; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows-page.y)) height=(size_t) next->page.y+(ssize_t) next->rows-page.y; } break; } case FlattenLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; page.x=0; page.y=0; break; } case MosaicLayer: { if (page.width > 0) width=page.width; if (page.height > 0) height=page.height; for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) { if (method == MosaicLayer) { page.x=next->page.x; page.y=next->page.y; if ((ssize_t) width < (next->page.x+(ssize_t) next->columns)) width=(size_t) next->page.x+next->columns; if ((ssize_t) height < (next->page.y+(ssize_t) next->rows)) height=(size_t) next->page.y+next->rows; } } page.width=width; page.height=height; page.x=0; page.y=0; } break; } /* Set virtual canvas size if not defined. */ if (page.width == 0) page.width=page.x < 0 ? width : width+page.x; if (page.height == 0) page.height=page.y < 0 ? height : height+page.y; /* Handle "TrimBoundsLayer" method separately to normal 'layer merge'. */ if (method == TrimBoundsLayer) { number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { image->page.x-=page.x; image->page.y-=page.y; image->page.width=width; image->page.height=height; proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return((Image *) NULL); } /* Create canvas size of width and height, and background color. */ canvas=CloneImage(image,width,height,MagickTrue,exception); if (canvas == (Image *) NULL) return((Image *) NULL); (void) SetImageBackgroundColor(canvas,exception); canvas->page=page; canvas->dispose=UndefinedDispose; /* Compose images onto canvas, with progress monitor */ number_images=GetImageListLength(image); for (scene=0; scene < (ssize_t) number_images; scene++) { (void) CompositeImage(canvas,image,image->compose,MagickTrue,image->page.x- canvas->page.x,image->page.y-canvas->page.y,exception); proceed=SetImageProgress(image,MergeLayersTag,(MagickOffsetType) scene, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); if (image == (Image *) NULL) break; } return(canvas); }
./CrossVul/dataset_final_sorted/CWE-369/c/good_951_0
crossvul-cpp_data_good_5310_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT U U M M % % Q Q U U A A NN N T U U MM MM % % Q Q U U AAAAA N N N T U U M M M % % Q QQ U U A A N NN T U U M M % % QQQQ UUU A A N N T UUU M M % % % % MagicCore Methods to Acquire / Destroy Quantum Pixels % % % % Software Design % % Cristy % % October 1998 % % % % % % Copyright 1999-2016 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/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/color-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/delegate.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/statistic.h" #include "magick/stream.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/utility.h" /* Define declarations. */ #define QuantumSignature 0xab /* Forward declarations. */ static void DestroyQuantumPixels(QuantumInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumInfo() allocates the QuantumInfo structure. % % The format of the AcquireQuantumInfo method is: % % QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ MagickExport QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info, Image *image) { MagickBooleanType status; QuantumInfo *quantum_info; quantum_info=(QuantumInfo *) AcquireMagickMemory(sizeof(*quantum_info)); if (quantum_info == (QuantumInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); quantum_info->signature=MagickSignature; GetQuantumInfo(image_info,quantum_info); if (image == (const Image *) NULL) return(quantum_info); status=SetQuantumDepth(image,quantum_info,image->depth); quantum_info->endian=image->endian; if (status == MagickFalse) quantum_info=DestroyQuantumInfo(quantum_info); return(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumPixels() allocates the pixel staging area. % % The format of the AcquireQuantumPixels method is: % % MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info, % const size_t extent) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o extent: the quantum info. % */ static MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info, const size_t extent) { register ssize_t i; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); quantum_info->pixels=(unsigned char **) AcquireQuantumMemory( quantum_info->number_threads,sizeof(*quantum_info->pixels)); if (quantum_info->pixels == (unsigned char **) NULL) return(MagickFalse); quantum_info->extent=extent; (void) ResetMagickMemory(quantum_info->pixels,0,quantum_info->number_threads* sizeof(*quantum_info->pixels)); for (i=0; i < (ssize_t) quantum_info->number_threads; i++) { quantum_info->pixels[i]=(unsigned char *) AcquireQuantumMemory(extent+1, sizeof(**quantum_info->pixels)); if (quantum_info->pixels[i] == (unsigned char *) NULL) { while (--i >= 0) quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory( quantum_info->pixels[i]); return(MagickFalse); } (void) ResetMagickMemory(quantum_info->pixels[i],0,(extent+1)* sizeof(**quantum_info->pixels)); quantum_info->pixels[i][extent]=QuantumSignature; } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantumInfo() deallocates memory associated with the QuantumInfo % structure. % % The format of the DestroyQuantumInfo method is: % % QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); if (quantum_info->semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&quantum_info->semaphore); quantum_info->signature=(~MagickSignature); quantum_info=(QuantumInfo *) RelinquishMagickMemory(quantum_info); return(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantumPixels() destroys the quantum pixels. % % The format of the DestroyQuantumPixels() method is: % % void DestroyQuantumPixels(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ static void DestroyQuantumPixels(QuantumInfo *quantum_info) { register ssize_t i; ssize_t extent; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); assert(quantum_info->pixels != (unsigned char **) NULL); extent=(ssize_t) quantum_info->extent; for (i=0; i < (ssize_t) quantum_info->number_threads; i++) if (quantum_info->pixels[i] != (unsigned char *) NULL) { /* Did we overrun our quantum buffer? */ assert(quantum_info->pixels[i][extent] == QuantumSignature); quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory( quantum_info->pixels[i]); } quantum_info->pixels=(unsigned char **) RelinquishMagickMemory( quantum_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumExtent() returns the quantum pixel buffer extent. % % The format of the GetQuantumExtent method is: % % size_t GetQuantumExtent(Image *image,const QuantumInfo *quantum_info, % const QuantumType quantum_type) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o quantum_type: Declare which pixel components to transfer (red, green, % blue, opacity, RGB, or RGBA). % */ MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t packet_size; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); packet_size=1; switch (quantum_type) { case GrayAlphaQuantum: packet_size=2; break; case IndexAlphaQuantum: packet_size=2; break; case RGBQuantum: packet_size=3; break; case BGRQuantum: packet_size=3; break; case RGBAQuantum: packet_size=4; break; case RGBOQuantum: packet_size=4; break; case BGRAQuantum: packet_size=4; break; case CMYKQuantum: packet_size=4; break; case CMYKAQuantum: packet_size=5; break; default: break; } if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*image->columns*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*image->columns*quantum_info->depth+7)/8)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m E n d i a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumEndian() returns the quantum endian of the image. % % The endian of the GetQuantumEndian method is: % % EndianType GetQuantumEndian(const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport EndianType GetQuantumEndian(const QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); return(quantum_info->endian); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumFormat() returns the quantum format of the image. % % The format of the GetQuantumFormat method is: % % QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); return(quantum_info->format); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumInfo() initializes the QuantumInfo structure to default values. % % The format of the GetQuantumInfo method is: % % GetQuantumInfo(const ImageInfo *image_info,QuantumInfo *quantum_info) % % A description of each parameter follows: % % o image_info: the image info. % % o quantum_info: the quantum info. % */ MagickExport void GetQuantumInfo(const ImageInfo *image_info, QuantumInfo *quantum_info) { const char *option; assert(quantum_info != (QuantumInfo *) NULL); (void) ResetMagickMemory(quantum_info,0,sizeof(*quantum_info)); quantum_info->quantum=8; quantum_info->maximum=1.0; quantum_info->scale=QuantumRange; quantum_info->pack=MagickTrue; quantum_info->semaphore=AllocateSemaphoreInfo(); quantum_info->signature=MagickSignature; if (image_info == (const ImageInfo *) NULL) return; option=GetImageOption(image_info,"quantum:format"); if (option != (char *) NULL) quantum_info->format=(QuantumFormatType) ParseCommandOption( MagickQuantumFormatOptions,MagickFalse,option); option=GetImageOption(image_info,"quantum:minimum"); if (option != (char *) NULL) quantum_info->minimum=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"quantum:maximum"); if (option != (char *) NULL) quantum_info->maximum=StringToDouble(option,(char **) NULL); if ((quantum_info->minimum == 0.0) && (quantum_info->maximum == 0.0)) quantum_info->scale=0.0; else if (quantum_info->minimum == quantum_info->maximum) { quantum_info->scale=(MagickRealType) QuantumRange/quantum_info->minimum; quantum_info->minimum=0.0; } else quantum_info->scale=(MagickRealType) QuantumRange/(quantum_info->maximum- quantum_info->minimum); option=GetImageOption(image_info,"quantum:scale"); if (option != (char *) NULL) quantum_info->scale=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"quantum:polarity"); if (option != (char *) NULL) quantum_info->min_is_white=LocaleCompare(option,"min-is-white") == 0 ? MagickTrue : MagickFalse; quantum_info->endian=image_info->endian; ResetQuantumState(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumPixels() returns the quantum pixels. % % The format of the GetQuantumPixels method is: % % unsigned char *QuantumPixels GetQuantumPixels( % const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o image: the image. % */ MagickExport unsigned char *GetQuantumPixels(const QuantumInfo *quantum_info) { const int id = GetOpenMPThreadId(); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); return(quantum_info->pixels[id]); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumType() returns the quantum type of the image. % % The format of the GetQuantumType method is: % % QuantumType GetQuantumType(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % */ MagickExport QuantumType GetQuantumType(Image *image,ExceptionInfo *exception) { QuantumType quantum_type; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); (void) exception; quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; if (image->matte != MagickFalse) quantum_type=CMYKAQuantum; } if (IsGrayColorspace(image->colorspace) != MagickFalse) { quantum_type=GrayQuantum; if (image->matte != MagickFalse) quantum_type=GrayAlphaQuantum; } if (image->storage_class == PseudoClass) { quantum_type=IndexQuantum; if (image->matte != MagickFalse) quantum_type=IndexAlphaQuantum; } return(quantum_type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t Q u a n t u m S t a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetQuantumState() resets the quantum state. % % The format of the ResetQuantumState method is: % % void ResetQuantumState(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickPrivate void ResetQuantumState(QuantumInfo *quantum_info) { static const unsigned int mask[32] = { 0x00000000U, 0x00000001U, 0x00000003U, 0x00000007U, 0x0000000fU, 0x0000001fU, 0x0000003fU, 0x0000007fU, 0x000000ffU, 0x000001ffU, 0x000003ffU, 0x000007ffU, 0x00000fffU, 0x00001fffU, 0x00003fffU, 0x00007fffU, 0x0000ffffU, 0x0001ffffU, 0x0003ffffU, 0x0007ffffU, 0x000fffffU, 0x001fffffU, 0x003fffffU, 0x007fffffU, 0x00ffffffU, 0x01ffffffU, 0x03ffffffU, 0x07ffffffU, 0x0fffffffU, 0x1fffffffU, 0x3fffffffU, 0x7fffffffU }; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->state.inverse_scale=1.0; if (fabs(quantum_info->scale) >= MagickEpsilon) quantum_info->state.inverse_scale/=quantum_info->scale; quantum_info->state.pixel=0U; quantum_info->state.bits=0U; quantum_info->state.mask=mask; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumAlphaType() sets the quantum format. % % The format of the SetQuantumAlphaType method is: % % void SetQuantumAlphaType(QuantumInfo *quantum_info, % const QuantumAlphaType type) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o type: the alpha type (e.g. associate). % */ MagickExport void SetQuantumAlphaType(QuantumInfo *quantum_info, const QuantumAlphaType type) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->alpha_type=type; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumDepth() sets the quantum depth. % % The format of the SetQuantumDepth method is: % % MagickBooleanType SetQuantumDepth(const Image *image, % QuantumInfo *quantum_info,const size_t depth) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o depth: the quantum depth. % */ MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=image->columns*quantum; if ((image->columns != 0) && (quantum != (extent/image->columns))) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m E n d i a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumEndian() sets the quantum endian. % % The endian of the SetQuantumEndian method is: % % MagickBooleanType SetQuantumEndian(const Image *image, % QuantumInfo *quantum_info,const EndianType endian) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o endian: the quantum endian. % */ MagickExport MagickBooleanType SetQuantumEndian(const Image *image, QuantumInfo *quantum_info,const EndianType endian) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->endian=endian; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumFormat() sets the quantum format. % % The format of the SetQuantumFormat method is: % % MagickBooleanType SetQuantumFormat(const Image *image, % QuantumInfo *quantum_info,const QuantumFormatType format) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o format: the quantum format. % */ MagickExport MagickBooleanType SetQuantumFormat(const Image *image, QuantumInfo *quantum_info,const QuantumFormatType format) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->format=format; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m I m a g e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumImageType() sets the image type based on the quantum type. % % The format of the SetQuantumImageType method is: % % void ImageType SetQuantumImageType(Image *image, % const QuantumType quantum_type) % % A description of each parameter follows: % % o image: the image. % % o quantum_type: Declare which pixel components to transfer (red, green, % blue, opacity, RGB, or RGBA). % */ MagickExport void SetQuantumImageType(Image *image, const QuantumType quantum_type) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); switch (quantum_type) { case IndexQuantum: case IndexAlphaQuantum: { image->type=PaletteType; break; } case GrayQuantum: case GrayAlphaQuantum: { image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; break; } case CyanQuantum: case MagentaQuantum: case YellowQuantum: case BlackQuantum: case CMYKQuantum: case CMYKAQuantum: { image->type=ColorSeparationType; break; } default: { image->type=TrueColorType; break; } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m P a c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumPack() sets the quantum pack flag. % % The format of the SetQuantumPack method is: % % void SetQuantumPack(QuantumInfo *quantum_info, % const MagickBooleanType pack) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o pack: the pack flag. % */ MagickExport void SetQuantumPack(QuantumInfo *quantum_info, const MagickBooleanType pack) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->pack=pack; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m P a d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumPad() sets the quantum pad. % % The format of the SetQuantumPad method is: % % MagickBooleanType SetQuantumPad(const Image *image, % QuantumInfo *quantum_info,const size_t pad) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o pad: the quantum pad. % */ MagickExport MagickBooleanType SetQuantumPad(const Image *image, QuantumInfo *quantum_info,const size_t pad) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->pad=pad; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m M i n I s W h i t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumMinIsWhite() sets the quantum min-is-white flag. % % The format of the SetQuantumMinIsWhite method is: % % void SetQuantumMinIsWhite(QuantumInfo *quantum_info, % const MagickBooleanType min_is_white) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o min_is_white: the min-is-white flag. % */ MagickExport void SetQuantumMinIsWhite(QuantumInfo *quantum_info, const MagickBooleanType min_is_white) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->min_is_white=min_is_white; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m Q u a n t u m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumQuantum() sets the quantum quantum. % % The format of the SetQuantumQuantum method is: % % void SetQuantumQuantum(QuantumInfo *quantum_info, % const size_t quantum) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o quantum: the quantum quantum. % */ MagickExport void SetQuantumQuantum(QuantumInfo *quantum_info, const size_t quantum) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->quantum=quantum; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m S c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumScale() sets the quantum scale. % % The format of the SetQuantumScale method is: % % void SetQuantumScale(QuantumInfo *quantum_info,const double scale) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o scale: the quantum scale. % */ MagickExport void SetQuantumScale(QuantumInfo *quantum_info,const double scale) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->scale=scale; }
./CrossVul/dataset_final_sorted/CWE-369/c/good_5310_0
crossvul-cpp_data_good_2303_3
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library Win32-specific Routines. Adapted from tif_unix.c 4/5/95 by * Scott Wagner (wagner@itek.com), Itek Graphix, Rochester, NY USA */ #include "tiffiop.h" #include <windows.h> static tmsize_t _tiffReadProc(thandle_t fd, void* buf, tmsize_t size) { /* tmsize_t is 64bit on 64bit systems, but the WinAPI ReadFile takes * 32bit sizes, so we loop through the data in suitable 32bit sized * chunks */ uint8* ma; uint64 mb; DWORD n; DWORD o; tmsize_t p; ma=(uint8*)buf; mb=size; p=0; while (mb>0) { n=0x80000000UL; if ((uint64)n>mb) n=(DWORD)mb; if (!ReadFile(fd,(LPVOID)ma,n,&o,NULL)) return(0); ma+=o; mb-=o; p+=o; if (o!=n) break; } return(p); } static tmsize_t _tiffWriteProc(thandle_t fd, void* buf, tmsize_t size) { /* tmsize_t is 64bit on 64bit systems, but the WinAPI WriteFile takes * 32bit sizes, so we loop through the data in suitable 32bit sized * chunks */ uint8* ma; uint64 mb; DWORD n; DWORD o; tmsize_t p; ma=(uint8*)buf; mb=size; p=0; while (mb>0) { n=0x80000000UL; if ((uint64)n>mb) n=(DWORD)mb; if (!WriteFile(fd,(LPVOID)ma,n,&o,NULL)) return(0); ma+=o; mb-=o; p+=o; if (o!=n) break; } return(p); } static uint64 _tiffSeekProc(thandle_t fd, uint64 off, int whence) { LARGE_INTEGER offli; DWORD dwMoveMethod; offli.QuadPart = off; switch(whence) { case SEEK_SET: dwMoveMethod = FILE_BEGIN; break; case SEEK_CUR: dwMoveMethod = FILE_CURRENT; break; case SEEK_END: dwMoveMethod = FILE_END; break; default: dwMoveMethod = FILE_BEGIN; break; } offli.LowPart=SetFilePointer(fd,offli.LowPart,&offli.HighPart,dwMoveMethod); if ((offli.LowPart==INVALID_SET_FILE_POINTER)&&(GetLastError()!=NO_ERROR)) offli.QuadPart=0; return(offli.QuadPart); } static int _tiffCloseProc(thandle_t fd) { return (CloseHandle(fd) ? 0 : -1); } static uint64 _tiffSizeProc(thandle_t fd) { ULARGE_INTEGER m; m.LowPart=GetFileSize(fd,&m.HighPart); return(m.QuadPart); } static int _tiffDummyMapProc(thandle_t fd, void** pbase, toff_t* psize) { (void) fd; (void) pbase; (void) psize; return (0); } /* * From "Hermann Josef Hill" <lhill@rhein-zeitung.de>: * * Windows uses both a handle and a pointer for file mapping, * but according to the SDK documentation and Richter's book * "Advanced Windows Programming" it is safe to free the handle * after obtaining the file mapping pointer * * This removes a nasty OS dependency and cures a problem * with Visual C++ 5.0 */ static int _tiffMapProc(thandle_t fd, void** pbase, toff_t* psize) { uint64 size; tmsize_t sizem; HANDLE hMapFile; size = _tiffSizeProc(fd); sizem = (tmsize_t)size; if ((uint64)sizem!=size) return (0); /* By passing in 0 for the maximum file size, it specifies that we create a file mapping object for the full file size. */ hMapFile = CreateFileMapping(fd, NULL, PAGE_READONLY, 0, 0, NULL); if (hMapFile == NULL) return (0); *pbase = MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0); CloseHandle(hMapFile); if (*pbase == NULL) return (0); *psize = size; return(1); } static void _tiffDummyUnmapProc(thandle_t fd, void* base, toff_t size) { (void) fd; (void) base; (void) size; } static void _tiffUnmapProc(thandle_t fd, void* base, toff_t size) { (void) fd; (void) size; UnmapViewOfFile(base); } /* * Open a TIFF file descriptor for read/writing. * Note that TIFFFdOpen and TIFFOpen recognise the character 'u' in the mode * string, which forces the file to be opened unmapped. */ TIFF* TIFFFdOpen(int ifd, const char* name, const char* mode) { TIFF* tif; int fSuppressMap; int m; fSuppressMap=0; for (m=0; mode[m]!=0; m++) { if (mode[m]=='u') { fSuppressMap=1; break; } } tif = TIFFClientOpen(name, mode, (thandle_t)ifd, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, fSuppressMap ? _tiffDummyMapProc : _tiffMapProc, fSuppressMap ? _tiffDummyUnmapProc : _tiffUnmapProc); if (tif) tif->tif_fd = ifd; return (tif); } #ifndef _WIN32_WCE /* * Open a TIFF file for read/writing. */ TIFF* TIFFOpen(const char* name, const char* mode) { static const char module[] = "TIFFOpen"; thandle_t fd; int m; DWORD dwMode; TIFF* tif; m = _TIFFgetMode(mode, module); switch(m) { case O_RDONLY: dwMode = OPEN_EXISTING; break; case O_RDWR: dwMode = OPEN_ALWAYS; break; case O_RDWR|O_CREAT: dwMode = OPEN_ALWAYS; break; case O_RDWR|O_TRUNC: dwMode = CREATE_ALWAYS; break; case O_RDWR|O_CREAT|O_TRUNC: dwMode = CREATE_ALWAYS; break; default: return ((TIFF*)0); } fd = (thandle_t)CreateFileA(name, (m == O_RDONLY)?GENERIC_READ:(GENERIC_READ | GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, dwMode, (m == O_RDONLY)?FILE_ATTRIBUTE_READONLY:FILE_ATTRIBUTE_NORMAL, NULL); if (fd == INVALID_HANDLE_VALUE) { TIFFErrorExt(0, module, "%s: Cannot open", name); return ((TIFF *)0); } tif = TIFFFdOpen((int)fd, name, mode); if(!tif) CloseHandle(fd); return tif; } /* * Open a TIFF file with a Unicode filename, for read/writing. */ TIFF* TIFFOpenW(const wchar_t* name, const char* mode) { static const char module[] = "TIFFOpenW"; thandle_t fd; int m; DWORD dwMode; int mbsize; char *mbname; TIFF *tif; m = _TIFFgetMode(mode, module); switch(m) { case O_RDONLY: dwMode = OPEN_EXISTING; break; case O_RDWR: dwMode = OPEN_ALWAYS; break; case O_RDWR|O_CREAT: dwMode = OPEN_ALWAYS; break; case O_RDWR|O_TRUNC: dwMode = CREATE_ALWAYS; break; case O_RDWR|O_CREAT|O_TRUNC: dwMode = CREATE_ALWAYS; break; default: return ((TIFF*)0); } fd = (thandle_t)CreateFileW(name, (m == O_RDONLY)?GENERIC_READ:(GENERIC_READ|GENERIC_WRITE), FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, dwMode, (m == O_RDONLY)?FILE_ATTRIBUTE_READONLY:FILE_ATTRIBUTE_NORMAL, NULL); if (fd == INVALID_HANDLE_VALUE) { TIFFErrorExt(0, module, "%S: Cannot open", name); return ((TIFF *)0); } mbname = NULL; mbsize = WideCharToMultiByte(CP_ACP, 0, name, -1, NULL, 0, NULL, NULL); if (mbsize > 0) { mbname = (char *)_TIFFmalloc(mbsize); if (!mbname) { TIFFErrorExt(0, module, "Can't allocate space for filename conversion buffer"); return ((TIFF*)0); } WideCharToMultiByte(CP_ACP, 0, name, -1, mbname, mbsize, NULL, NULL); } tif = TIFFFdOpen((int)fd, (mbname != NULL) ? mbname : "<unknown>", mode); if(!tif) CloseHandle(fd); _TIFFfree(mbname); return tif; } #endif /* ndef _WIN32_WCE */ void* _TIFFmalloc(tmsize_t s) { if (s == 0) return ((void *) NULL); return (malloc((size_t) s)); } void _TIFFfree(void* p) { free(p); } void* _TIFFrealloc(void* p, tmsize_t s) { return (realloc(p, (size_t) s)); } void _TIFFmemset(void* p, int v, tmsize_t c) { memset(p, v, (size_t) c); } void _TIFFmemcpy(void* d, const void* s, tmsize_t c) { memcpy(d, s, (size_t) c); } int _TIFFmemcmp(const void* p1, const void* p2, tmsize_t c) { return (memcmp(p1, p2, (size_t) c)); } #ifndef _WIN32_WCE #if (_MSC_VER < 1500) # define vsnprintf _vsnprintf #endif static void Win32WarningHandler(const char* module, const char* fmt, va_list ap) { #ifndef TIF_PLATFORM_CONSOLE LPTSTR szTitle; LPTSTR szTmp; LPCTSTR szTitleText = "%s Warning"; LPCTSTR szDefaultModule = "LIBTIFF"; LPCTSTR szTmpModule = (module == NULL) ? szDefaultModule : module; SIZE_T nBufSize = (strlen(szTmpModule) + strlen(szTitleText) + strlen(fmt) + 256)*sizeof(char); if ((szTitle = (LPTSTR)LocalAlloc(LMEM_FIXED, nBufSize)) == NULL) return; sprintf(szTitle, szTitleText, szTmpModule); szTmp = szTitle + (strlen(szTitle)+2)*sizeof(char); vsnprintf(szTmp, nBufSize-(strlen(szTitle)+2)*sizeof(char), fmt, ap); MessageBoxA(GetFocus(), szTmp, szTitle, MB_OK | MB_ICONINFORMATION); LocalFree(szTitle); return; #else if (module != NULL) fprintf(stderr, "%s: ", module); fprintf(stderr, "Warning, "); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); #endif } TIFFErrorHandler _TIFFwarningHandler = Win32WarningHandler; static void Win32ErrorHandler(const char* module, const char* fmt, va_list ap) { #ifndef TIF_PLATFORM_CONSOLE LPTSTR szTitle; LPTSTR szTmp; LPCTSTR szTitleText = "%s Error"; LPCTSTR szDefaultModule = "LIBTIFF"; LPCTSTR szTmpModule = (module == NULL) ? szDefaultModule : module; SIZE_T nBufSize = (strlen(szTmpModule) + strlen(szTitleText) + strlen(fmt) + 256)*sizeof(char); if ((szTitle = (LPTSTR)LocalAlloc(LMEM_FIXED, nBufSize)) == NULL) return; sprintf(szTitle, szTitleText, szTmpModule); szTmp = szTitle + (strlen(szTitle)+2)*sizeof(char); vsnprintf(szTmp, nBufSize-(strlen(szTitle)+2)*sizeof(char), fmt, ap); MessageBoxA(GetFocus(), szTmp, szTitle, MB_OK | MB_ICONEXCLAMATION); LocalFree(szTitle); return; #else if (module != NULL) fprintf(stderr, "%s: ", module); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); #endif } TIFFErrorHandler _TIFFerrorHandler = Win32ErrorHandler; #endif /* ndef _WIN32_WCE */ /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-369/c/good_2303_3
crossvul-cpp_data_bad_1008_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF EEEEE AAA TTTTT U U RRRR EEEEE % % F E A A T U U R R E % % FFF EEE AAAAA T U U RRRR EEE % % F E A A T U U R R E % % F EEEEE A A T UUU R R EEEEE % % % % % % MagickCore Image Feature Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 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://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/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/feature.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/image-private.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/morphology-private.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/random_.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/timer.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a n n y E d g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CannyEdgeImage() uses a multi-stage algorithm to detect a wide range of % edges in images. % % The format of the CannyEdgeImage method is: % % Image *CannyEdgeImage(const Image *image,const double radius, % const double sigma,const double lower_percent, % const double upper_percent,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the gaussian smoothing filter. % % o sigma: the sigma of the gaussian smoothing filter. % % o lower_percent: percentage of edge pixels in the lower threshold. % % o upper_percent: percentage of edge pixels in the upper threshold. % % o exception: return any errors or warnings in this structure. % */ typedef struct _CannyInfo { double magnitude, intensity; int orientation; ssize_t x, y; } CannyInfo; static inline MagickBooleanType IsAuthenticPixel(const Image *image, const ssize_t x,const ssize_t y) { if ((x < 0) || (x >= (ssize_t) image->columns)) return(MagickFalse); if ((y < 0) || (y >= (ssize_t) image->rows)) return(MagickFalse); return(MagickTrue); } static MagickBooleanType TraceEdges(Image *edge_image,CacheView *edge_view, MatrixInfo *canny_cache,const ssize_t x,const ssize_t y, const double lower_threshold,ExceptionInfo *exception) { CannyInfo edge, pixel; MagickBooleanType status; register Quantum *q; register ssize_t i; q=GetCacheViewAuthenticPixels(edge_view,x,y,1,1,exception); if (q == (Quantum *) NULL) return(MagickFalse); *q=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); if (GetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); edge.x=x; edge.y=y; if (SetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); for (i=1; i != 0; ) { ssize_t v; i--; status=GetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); for (v=(-1); v <= 1; v++) { ssize_t u; for (u=(-1); u <= 1; u++) { if ((u == 0) && (v == 0)) continue; if (IsAuthenticPixel(edge_image,edge.x+u,edge.y+v) == MagickFalse) continue; /* Not an edge if gradient value is below the lower threshold. */ q=GetCacheViewAuthenticPixels(edge_view,edge.x+u,edge.y+v,1,1, exception); if (q == (Quantum *) NULL) return(MagickFalse); status=GetMatrixElement(canny_cache,edge.x+u,edge.y+v,&pixel); if (status == MagickFalse) return(MagickFalse); if ((GetPixelIntensity(edge_image,q) == 0.0) && (pixel.intensity >= lower_threshold)) { *q=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); edge.x+=u; edge.y+=v; status=SetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); i++; } } } } return(MagickTrue); } MagickExport Image *CannyEdgeImage(const Image *image,const double radius, const double sigma,const double lower_percent,const double upper_percent, ExceptionInfo *exception) { #define CannyEdgeImageTag "CannyEdge/Image" CacheView *edge_view; CannyInfo element; char geometry[MagickPathExtent]; double lower_threshold, max, min, upper_threshold; Image *edge_image; KernelInfo *kernel_info; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *canny_cache; ssize_t y; assert(image != (const 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); /* Filter out noise. */ (void) FormatLocaleString(geometry,MagickPathExtent, "blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma); kernel_info=AcquireKernelInfo(geometry,exception); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); edge_image=MorphologyImage(image,ConvolveMorphology,1,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); if (edge_image == (Image *) NULL) return((Image *) NULL); if (TransformImageColorspace(edge_image,GRAYColorspace,exception) == MagickFalse) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } (void) SetImageAlphaChannel(edge_image,OffAlphaChannel,exception); /* Find the intensity gradient of the image. */ canny_cache=AcquireMatrixInfo(edge_image->columns,edge_image->rows, sizeof(CannyInfo),exception); if (canny_cache == (MatrixInfo *) NULL) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } status=MagickTrue; edge_view=AcquireVirtualCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns+1,2, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; double dx, dy; register const Quantum *magick_restrict kernel_pixels; ssize_t v; static double Gx[2][2] = { { -1.0, +1.0 }, { -1.0, +1.0 } }, Gy[2][2] = { { +1.0, +1.0 }, { -1.0, -1.0 } }; (void) memset(&pixel,0,sizeof(pixel)); dx=0.0; dy=0.0; kernel_pixels=p; for (v=0; v < 2; v++) { ssize_t u; for (u=0; u < 2; u++) { double intensity; intensity=GetPixelIntensity(edge_image,kernel_pixels+u); dx+=0.5*Gx[v][u]*intensity; dy+=0.5*Gy[v][u]*intensity; } kernel_pixels+=edge_image->columns+1; } pixel.magnitude=hypot(dx,dy); pixel.orientation=0; if (fabs(dx) > MagickEpsilon) { double slope; slope=dy/dx; if (slope < 0.0) { if (slope < -2.41421356237) pixel.orientation=0; else if (slope < -0.414213562373) pixel.orientation=1; else pixel.orientation=2; } else { if (slope > 2.41421356237) pixel.orientation=0; else if (slope > 0.414213562373) pixel.orientation=3; else pixel.orientation=2; } } if (SetMatrixElement(canny_cache,x,y,&pixel) == MagickFalse) continue; p+=GetPixelChannels(edge_image); } } edge_view=DestroyCacheView(edge_view); /* Non-maxima suppression, remove pixels that are not considered to be part of an edge. */ progress=0; (void) GetMatrixElement(canny_cache,0,0,&element); max=element.intensity; min=element.intensity; edge_view=AcquireAuthenticCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(edge_view,0,y,edge_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo alpha_pixel, beta_pixel, pixel; (void) GetMatrixElement(canny_cache,x,y,&pixel); switch (pixel.orientation) { case 0: default: { /* 0 degrees, north and south. */ (void) GetMatrixElement(canny_cache,x,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x,y+1,&beta_pixel); break; } case 1: { /* 45 degrees, northwest and southeast. */ (void) GetMatrixElement(canny_cache,x-1,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y+1,&beta_pixel); break; } case 2: { /* 90 degrees, east and west. */ (void) GetMatrixElement(canny_cache,x-1,y,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y,&beta_pixel); break; } case 3: { /* 135 degrees, northeast and southwest. */ (void) GetMatrixElement(canny_cache,x+1,y-1,&beta_pixel); (void) GetMatrixElement(canny_cache,x-1,y+1,&alpha_pixel); break; } } pixel.intensity=pixel.magnitude; if ((pixel.magnitude < alpha_pixel.magnitude) || (pixel.magnitude < beta_pixel.magnitude)) pixel.intensity=0; (void) SetMatrixElement(canny_cache,x,y,&pixel); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CannyEdgeImage) #endif { if (pixel.intensity < min) min=pixel.intensity; if (pixel.intensity > max) max=pixel.intensity; } *q=0; q+=GetPixelChannels(edge_image); } if (SyncCacheViewAuthenticPixels(edge_view,exception) == MagickFalse) status=MagickFalse; } edge_view=DestroyCacheView(edge_view); /* Estimate hysteresis threshold. */ lower_threshold=lower_percent*(max-min)+min; upper_threshold=upper_percent*(max-min)+min; /* Hysteresis threshold. */ edge_view=AcquireAuthenticCacheView(edge_image,exception); for (y=0; y < (ssize_t) edge_image->rows; y++) { register ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; register const Quantum *magick_restrict p; /* Edge if pixel gradient higher than upper threshold. */ p=GetCacheViewVirtualPixels(edge_view,x,y,1,1,exception); if (p == (const Quantum *) NULL) continue; status=GetMatrixElement(canny_cache,x,y,&pixel); if (status == MagickFalse) continue; if ((GetPixelIntensity(edge_image,p) == 0.0) && (pixel.intensity >= upper_threshold)) status=TraceEdges(edge_image,edge_view,canny_cache,x,y,lower_threshold, exception); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CannyEdgeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } edge_view=DestroyCacheView(edge_view); /* Free resources. */ canny_cache=DestroyMatrixInfo(canny_cache); return(edge_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e F e a t u r e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageFeatures() returns features for each channel in the image in % each of four directions (horizontal, vertical, left and right diagonals) % for the specified distance. The features include the angular second % moment, contrast, correlation, sum of squares: variance, inverse difference % moment, sum average, sum varience, sum entropy, entropy, difference variance,% difference entropy, information measures of correlation 1, information % measures of correlation 2, and maximum correlation coefficient. You can % access the red channel contrast, for example, like this: % % channel_features=GetImageFeatures(image,1,exception); % contrast=channel_features[RedPixelChannel].contrast[0]; % % Use MagickRelinquishMemory() to free the features buffer. % % The format of the GetImageFeatures method is: % % ChannelFeatures *GetImageFeatures(const Image *image, % const size_t distance,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o distance: the distance. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelFeatures *GetImageFeatures(const Image *image, const size_t distance,ExceptionInfo *exception) { typedef struct _ChannelStatistics { PixelInfo direction[4]; /* horizontal, vertical, left and right diagonals */ } ChannelStatistics; CacheView *image_view; ChannelFeatures *channel_features; ChannelStatistics **cooccurrence, correlation, *density_x, *density_xy, *density_y, entropy_x, entropy_xy, entropy_xy1, entropy_xy2, entropy_y, mean, **Q, *sum, sum_squares, variance; PixelPacket gray, *grays; MagickBooleanType status; register ssize_t i, r; size_t length; unsigned int number_grays; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns < (distance+1)) || (image->rows < (distance+1))) return((ChannelFeatures *) NULL); length=MaxPixelChannels+1UL; channel_features=(ChannelFeatures *) AcquireQuantumMemory(length, sizeof(*channel_features)); if (channel_features == (ChannelFeatures *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(channel_features,0,length* sizeof(*channel_features)); /* Form grays. */ grays=(PixelPacket *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*grays)); if (grays == (PixelPacket *) NULL) { channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } for (i=0; i <= (ssize_t) MaxMap; i++) { grays[i].red=(~0U); grays[i].green=(~0U); grays[i].blue=(~0U); grays[i].alpha=(~0U); grays[i].black=(~0U); } status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (r=0; r < (ssize_t) image->rows; r++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,r,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { grays[ScaleQuantumToMap(GetPixelRed(image,p))].red= ScaleQuantumToMap(GetPixelRed(image,p)); grays[ScaleQuantumToMap(GetPixelGreen(image,p))].green= ScaleQuantumToMap(GetPixelGreen(image,p)); grays[ScaleQuantumToMap(GetPixelBlue(image,p))].blue= ScaleQuantumToMap(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) grays[ScaleQuantumToMap(GetPixelBlack(image,p))].black= ScaleQuantumToMap(GetPixelBlack(image,p)); if (image->alpha_trait != UndefinedPixelTrait) grays[ScaleQuantumToMap(GetPixelAlpha(image,p))].alpha= ScaleQuantumToMap(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); return(channel_features); } (void) memset(&gray,0,sizeof(gray)); for (i=0; i <= (ssize_t) MaxMap; i++) { if (grays[i].red != ~0U) grays[gray.red++].red=grays[i].red; if (grays[i].green != ~0U) grays[gray.green++].green=grays[i].green; if (grays[i].blue != ~0U) grays[gray.blue++].blue=grays[i].blue; if (image->colorspace == CMYKColorspace) if (grays[i].black != ~0U) grays[gray.black++].black=grays[i].black; if (image->alpha_trait != UndefinedPixelTrait) if (grays[i].alpha != ~0U) grays[gray.alpha++].alpha=grays[i].alpha; } /* Allocate spatial dependence matrix. */ number_grays=gray.red; if (gray.green > number_grays) number_grays=gray.green; if (gray.blue > number_grays) number_grays=gray.blue; if (image->colorspace == CMYKColorspace) if (gray.black > number_grays) number_grays=gray.black; if (image->alpha_trait != UndefinedPixelTrait) if (gray.alpha > number_grays) number_grays=gray.alpha; cooccurrence=(ChannelStatistics **) AcquireQuantumMemory(number_grays, sizeof(*cooccurrence)); density_x=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_x)); density_xy=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_xy)); density_y=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_y)); Q=(ChannelStatistics **) AcquireQuantumMemory(number_grays,sizeof(*Q)); sum=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(*sum)); if ((cooccurrence == (ChannelStatistics **) NULL) || (density_x == (ChannelStatistics *) NULL) || (density_xy == (ChannelStatistics *) NULL) || (density_y == (ChannelStatistics *) NULL) || (Q == (ChannelStatistics **) NULL) || (sum == (ChannelStatistics *) NULL)) { if (Q != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); } if (sum != (ChannelStatistics *) NULL) sum=(ChannelStatistics *) RelinquishMagickMemory(sum); if (density_y != (ChannelStatistics *) NULL) density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); if (density_xy != (ChannelStatistics *) NULL) density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); if (density_x != (ChannelStatistics *) NULL) density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); if (cooccurrence != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory( cooccurrence); } grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } (void) memset(&correlation,0,sizeof(correlation)); (void) memset(density_x,0,2*(number_grays+1)*sizeof(*density_x)); (void) memset(density_xy,0,2*(number_grays+1)*sizeof(*density_xy)); (void) memset(density_y,0,2*(number_grays+1)*sizeof(*density_y)); (void) memset(&mean,0,sizeof(mean)); (void) memset(sum,0,number_grays*sizeof(*sum)); (void) memset(&sum_squares,0,sizeof(sum_squares)); (void) memset(density_xy,0,2*number_grays*sizeof(*density_xy)); (void) memset(&entropy_x,0,sizeof(entropy_x)); (void) memset(&entropy_xy,0,sizeof(entropy_xy)); (void) memset(&entropy_xy1,0,sizeof(entropy_xy1)); (void) memset(&entropy_xy2,0,sizeof(entropy_xy2)); (void) memset(&entropy_y,0,sizeof(entropy_y)); (void) memset(&variance,0,sizeof(variance)); for (i=0; i < (ssize_t) number_grays; i++) { cooccurrence[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays, sizeof(**cooccurrence)); Q[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(**Q)); if ((cooccurrence[i] == (ChannelStatistics *) NULL) || (Q[i] == (ChannelStatistics *) NULL)) break; (void) memset(cooccurrence[i],0,number_grays* sizeof(**cooccurrence)); (void) memset(Q[i],0,number_grays*sizeof(**Q)); } if (i < (ssize_t) number_grays) { for (i--; i >= 0; i--) { if (Q[i] != (ChannelStatistics *) NULL) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); if (cooccurrence[i] != (ChannelStatistics *) NULL) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); } Q=(ChannelStatistics **) RelinquishMagickMemory(Q); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); sum=(ChannelStatistics *) RelinquishMagickMemory(sum); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Initialize spatial dependence matrix. */ status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); for (r=0; r < (ssize_t) image->rows; r++) { register const Quantum *magick_restrict p; register ssize_t x; ssize_t offset, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-(ssize_t) distance,r,image->columns+ 2*distance,distance+2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } p+=distance*GetPixelChannels(image);; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < 4; i++) { switch (i) { case 0: default: { /* Horizontal adjacency. */ offset=(ssize_t) distance; break; } case 1: { /* Vertical adjacency. */ offset=(ssize_t) (image->columns+2*distance); break; } case 2: { /* Right diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)-distance); break; } case 3: { /* Left diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)+distance); break; } } u=0; v=0; while (grays[u].red != ScaleQuantumToMap(GetPixelRed(image,p))) u++; while (grays[v].red != ScaleQuantumToMap(GetPixelRed(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].red++; cooccurrence[v][u].direction[i].red++; u=0; v=0; while (grays[u].green != ScaleQuantumToMap(GetPixelGreen(image,p))) u++; while (grays[v].green != ScaleQuantumToMap(GetPixelGreen(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].green++; cooccurrence[v][u].direction[i].green++; u=0; v=0; while (grays[u].blue != ScaleQuantumToMap(GetPixelBlue(image,p))) u++; while (grays[v].blue != ScaleQuantumToMap(GetPixelBlue(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].blue++; cooccurrence[v][u].direction[i].blue++; if (image->colorspace == CMYKColorspace) { u=0; v=0; while (grays[u].black != ScaleQuantumToMap(GetPixelBlack(image,p))) u++; while (grays[v].black != ScaleQuantumToMap(GetPixelBlack(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].black++; cooccurrence[v][u].direction[i].black++; } if (image->alpha_trait != UndefinedPixelTrait) { u=0; v=0; while (grays[u].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p))) u++; while (grays[v].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].alpha++; cooccurrence[v][u].direction[i].alpha++; } } p+=GetPixelChannels(image); } } grays=(PixelPacket *) RelinquishMagickMemory(grays); image_view=DestroyCacheView(image_view); if (status == MagickFalse) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Normalize spatial dependence matrix. */ for (i=0; i < 4; i++) { double normalize; register ssize_t y; switch (i) { case 0: default: { /* Horizontal adjacency. */ normalize=2.0*image->rows*(image->columns-distance); break; } case 1: { /* Vertical adjacency. */ normalize=2.0*(image->rows-distance)*image->columns; break; } case 2: { /* Right diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } case 3: { /* Left diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } } normalize=PerceptibleReciprocal(normalize); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { cooccurrence[x][y].direction[i].red*=normalize; cooccurrence[x][y].direction[i].green*=normalize; cooccurrence[x][y].direction[i].blue*=normalize; if (image->colorspace == CMYKColorspace) cooccurrence[x][y].direction[i].black*=normalize; if (image->alpha_trait != UndefinedPixelTrait) cooccurrence[x][y].direction[i].alpha*=normalize; } } } /* Compute texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Angular second moment: measure of homogeneity of the image. */ channel_features[RedPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].red* cooccurrence[x][y].direction[i].red; channel_features[GreenPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].green* cooccurrence[x][y].direction[i].green; channel_features[BluePixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].blue* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].black* cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].alpha* cooccurrence[x][y].direction[i].alpha; /* Correlation: measure of linear-dependencies in the image. */ sum[y].direction[i].red+=cooccurrence[x][y].direction[i].red; sum[y].direction[i].green+=cooccurrence[x][y].direction[i].green; sum[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) sum[y].direction[i].black+=cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) sum[y].direction[i].alpha+=cooccurrence[x][y].direction[i].alpha; correlation.direction[i].red+=x*y*cooccurrence[x][y].direction[i].red; correlation.direction[i].green+=x*y* cooccurrence[x][y].direction[i].green; correlation.direction[i].blue+=x*y* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) correlation.direction[i].black+=x*y* cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) correlation.direction[i].alpha+=x*y* cooccurrence[x][y].direction[i].alpha; /* Inverse Difference Moment. */ channel_features[RedPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].red/((y-x)*(y-x)+1); channel_features[GreenPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].green/((y-x)*(y-x)+1); channel_features[BluePixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].blue/((y-x)*(y-x)+1); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].black/((y-x)*(y-x)+1); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].alpha/((y-x)*(y-x)+1); /* Sum average. */ density_xy[y+x+2].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[y+x+2].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[y+x+2].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[y+x+2].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_xy[y+x+2].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; /* Entropy. */ channel_features[RedPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); channel_features[GreenPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); channel_features[BluePixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].black* MagickLog10(cooccurrence[x][y].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].alpha* MagickLog10(cooccurrence[x][y].direction[i].alpha); /* Information Measures of Correlation. */ density_x[x].direction[i].red+=cooccurrence[x][y].direction[i].red; density_x[x].direction[i].green+=cooccurrence[x][y].direction[i].green; density_x[x].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->alpha_trait != UndefinedPixelTrait) density_x[x].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; if (image->colorspace == CMYKColorspace) density_x[x].direction[i].black+= cooccurrence[x][y].direction[i].black; density_y[y].direction[i].red+=cooccurrence[x][y].direction[i].red; density_y[y].direction[i].green+=cooccurrence[x][y].direction[i].green; density_y[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_y[y].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_y[y].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; } mean.direction[i].red+=y*sum[y].direction[i].red; sum_squares.direction[i].red+=y*y*sum[y].direction[i].red; mean.direction[i].green+=y*sum[y].direction[i].green; sum_squares.direction[i].green+=y*y*sum[y].direction[i].green; mean.direction[i].blue+=y*sum[y].direction[i].blue; sum_squares.direction[i].blue+=y*y*sum[y].direction[i].blue; if (image->colorspace == CMYKColorspace) { mean.direction[i].black+=y*sum[y].direction[i].black; sum_squares.direction[i].black+=y*y*sum[y].direction[i].black; } if (image->alpha_trait != UndefinedPixelTrait) { mean.direction[i].alpha+=y*sum[y].direction[i].alpha; sum_squares.direction[i].alpha+=y*y*sum[y].direction[i].alpha; } } /* Correlation: measure of linear-dependencies in the image. */ channel_features[RedPixelChannel].correlation[i]= (correlation.direction[i].red-mean.direction[i].red* mean.direction[i].red)/(sqrt(sum_squares.direction[i].red- (mean.direction[i].red*mean.direction[i].red))*sqrt( sum_squares.direction[i].red-(mean.direction[i].red* mean.direction[i].red))); channel_features[GreenPixelChannel].correlation[i]= (correlation.direction[i].green-mean.direction[i].green* mean.direction[i].green)/(sqrt(sum_squares.direction[i].green- (mean.direction[i].green*mean.direction[i].green))*sqrt( sum_squares.direction[i].green-(mean.direction[i].green* mean.direction[i].green))); channel_features[BluePixelChannel].correlation[i]= (correlation.direction[i].blue-mean.direction[i].blue* mean.direction[i].blue)/(sqrt(sum_squares.direction[i].blue- (mean.direction[i].blue*mean.direction[i].blue))*sqrt( sum_squares.direction[i].blue-(mean.direction[i].blue* mean.direction[i].blue))); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].correlation[i]= (correlation.direction[i].black-mean.direction[i].black* mean.direction[i].black)/(sqrt(sum_squares.direction[i].black- (mean.direction[i].black*mean.direction[i].black))*sqrt( sum_squares.direction[i].black-(mean.direction[i].black* mean.direction[i].black))); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].correlation[i]= (correlation.direction[i].alpha-mean.direction[i].alpha* mean.direction[i].alpha)/(sqrt(sum_squares.direction[i].alpha- (mean.direction[i].alpha*mean.direction[i].alpha))*sqrt( sum_squares.direction[i].alpha-(mean.direction[i].alpha* mean.direction[i].alpha))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=2; x < (ssize_t) (2*number_grays); x++) { /* Sum average. */ channel_features[RedPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].red; channel_features[GreenPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].green; channel_features[BluePixelChannel].sum_average[i]+= x*density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].alpha; /* Sum entropy. */ channel_features[RedPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BluePixelChannel].sum_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].black* MagickLog10(density_xy[x].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].alpha* MagickLog10(density_xy[x].direction[i].alpha); /* Sum variance. */ channel_features[RedPixelChannel].sum_variance[i]+= (x-channel_features[RedPixelChannel].sum_entropy[i])* (x-channel_features[RedPixelChannel].sum_entropy[i])* density_xy[x].direction[i].red; channel_features[GreenPixelChannel].sum_variance[i]+= (x-channel_features[GreenPixelChannel].sum_entropy[i])* (x-channel_features[GreenPixelChannel].sum_entropy[i])* density_xy[x].direction[i].green; channel_features[BluePixelChannel].sum_variance[i]+= (x-channel_features[BluePixelChannel].sum_entropy[i])* (x-channel_features[BluePixelChannel].sum_entropy[i])* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_variance[i]+= (x-channel_features[BlackPixelChannel].sum_entropy[i])* (x-channel_features[BlackPixelChannel].sum_entropy[i])* density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_variance[i]+= (x-channel_features[AlphaPixelChannel].sum_entropy[i])* (x-channel_features[AlphaPixelChannel].sum_entropy[i])* density_xy[x].direction[i].alpha; } } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Sum of Squares: Variance */ variance.direction[i].red+=(y-mean.direction[i].red+1)* (y-mean.direction[i].red+1)*cooccurrence[x][y].direction[i].red; variance.direction[i].green+=(y-mean.direction[i].green+1)* (y-mean.direction[i].green+1)*cooccurrence[x][y].direction[i].green; variance.direction[i].blue+=(y-mean.direction[i].blue+1)* (y-mean.direction[i].blue+1)*cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].black+=(y-mean.direction[i].black+1)* (y-mean.direction[i].black+1)*cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) variance.direction[i].alpha+=(y-mean.direction[i].alpha+1)* (y-mean.direction[i].alpha+1)* cooccurrence[x][y].direction[i].alpha; /* Sum average / Difference Variance. */ density_xy[MagickAbsoluteValue(y-x)].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[MagickAbsoluteValue(y-x)].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[MagickAbsoluteValue(y-x)].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[MagickAbsoluteValue(y-x)].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_xy[MagickAbsoluteValue(y-x)].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; /* Information Measures of Correlation. */ entropy_xy.direction[i].red-=cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); entropy_xy.direction[i].green-=cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); entropy_xy.direction[i].blue-=cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) entropy_xy.direction[i].black-=cooccurrence[x][y].direction[i].black* MagickLog10(cooccurrence[x][y].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy.direction[i].alpha-= cooccurrence[x][y].direction[i].alpha*MagickLog10( cooccurrence[x][y].direction[i].alpha); entropy_xy1.direction[i].red-=(cooccurrence[x][y].direction[i].red* MagickLog10(density_x[x].direction[i].red*density_y[y].direction[i].red)); entropy_xy1.direction[i].green-=(cooccurrence[x][y].direction[i].green* MagickLog10(density_x[x].direction[i].green* density_y[y].direction[i].green)); entropy_xy1.direction[i].blue-=(cooccurrence[x][y].direction[i].blue* MagickLog10(density_x[x].direction[i].blue*density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy1.direction[i].black-=( cooccurrence[x][y].direction[i].black*MagickLog10( density_x[x].direction[i].black*density_y[y].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy1.direction[i].alpha-=( cooccurrence[x][y].direction[i].alpha*MagickLog10( density_x[x].direction[i].alpha*density_y[y].direction[i].alpha)); entropy_xy2.direction[i].red-=(density_x[x].direction[i].red* density_y[y].direction[i].red*MagickLog10(density_x[x].direction[i].red* density_y[y].direction[i].red)); entropy_xy2.direction[i].green-=(density_x[x].direction[i].green* density_y[y].direction[i].green*MagickLog10(density_x[x].direction[i].green* density_y[y].direction[i].green)); entropy_xy2.direction[i].blue-=(density_x[x].direction[i].blue* density_y[y].direction[i].blue*MagickLog10(density_x[x].direction[i].blue* density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy2.direction[i].black-=(density_x[x].direction[i].black* density_y[y].direction[i].black*MagickLog10( density_x[x].direction[i].black*density_y[y].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy2.direction[i].alpha-=(density_x[x].direction[i].alpha* density_y[y].direction[i].alpha*MagickLog10( density_x[x].direction[i].alpha*density_y[y].direction[i].alpha)); } } channel_features[RedPixelChannel].variance_sum_of_squares[i]= variance.direction[i].red; channel_features[GreenPixelChannel].variance_sum_of_squares[i]= variance.direction[i].green; channel_features[BluePixelChannel].variance_sum_of_squares[i]= variance.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].variance_sum_of_squares[i]= variance.direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].variance_sum_of_squares[i]= variance.direction[i].alpha; } /* Compute more texture features. */ (void) memset(&variance,0,sizeof(variance)); (void) memset(&sum_squares,0,sizeof(sum_squares)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Difference variance. */ variance.direction[i].red+=density_xy[x].direction[i].red; variance.direction[i].green+=density_xy[x].direction[i].green; variance.direction[i].blue+=density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].black+=density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) variance.direction[i].alpha+=density_xy[x].direction[i].alpha; sum_squares.direction[i].red+=density_xy[x].direction[i].red* density_xy[x].direction[i].red; sum_squares.direction[i].green+=density_xy[x].direction[i].green* density_xy[x].direction[i].green; sum_squares.direction[i].blue+=density_xy[x].direction[i].blue* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) sum_squares.direction[i].black+=density_xy[x].direction[i].black* density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) sum_squares.direction[i].alpha+=density_xy[x].direction[i].alpha* density_xy[x].direction[i].alpha; /* Difference entropy. */ channel_features[RedPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BluePixelChannel].difference_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].black* MagickLog10(density_xy[x].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].alpha* MagickLog10(density_xy[x].direction[i].alpha); /* Information Measures of Correlation. */ entropy_x.direction[i].red-=(density_x[x].direction[i].red* MagickLog10(density_x[x].direction[i].red)); entropy_x.direction[i].green-=(density_x[x].direction[i].green* MagickLog10(density_x[x].direction[i].green)); entropy_x.direction[i].blue-=(density_x[x].direction[i].blue* MagickLog10(density_x[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_x.direction[i].black-=(density_x[x].direction[i].black* MagickLog10(density_x[x].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_x.direction[i].alpha-=(density_x[x].direction[i].alpha* MagickLog10(density_x[x].direction[i].alpha)); entropy_y.direction[i].red-=(density_y[x].direction[i].red* MagickLog10(density_y[x].direction[i].red)); entropy_y.direction[i].green-=(density_y[x].direction[i].green* MagickLog10(density_y[x].direction[i].green)); entropy_y.direction[i].blue-=(density_y[x].direction[i].blue* MagickLog10(density_y[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_y.direction[i].black-=(density_y[x].direction[i].black* MagickLog10(density_y[x].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_y.direction[i].alpha-=(density_y[x].direction[i].alpha* MagickLog10(density_y[x].direction[i].alpha)); } /* Difference variance. */ channel_features[RedPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].red)- (variance.direction[i].red*variance.direction[i].red))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[GreenPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].green)- (variance.direction[i].green*variance.direction[i].green))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[BluePixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].blue)- (variance.direction[i].blue*variance.direction[i].blue))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].black)- (variance.direction[i].black*variance.direction[i].black))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].alpha)- (variance.direction[i].alpha*variance.direction[i].alpha))/ ((double) number_grays*number_grays*number_grays*number_grays); /* Information Measures of Correlation. */ channel_features[RedPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].red-entropy_xy1.direction[i].red)/ (entropy_x.direction[i].red > entropy_y.direction[i].red ? entropy_x.direction[i].red : entropy_y.direction[i].red); channel_features[GreenPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].green-entropy_xy1.direction[i].green)/ (entropy_x.direction[i].green > entropy_y.direction[i].green ? entropy_x.direction[i].green : entropy_y.direction[i].green); channel_features[BluePixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].blue-entropy_xy1.direction[i].blue)/ (entropy_x.direction[i].blue > entropy_y.direction[i].blue ? entropy_x.direction[i].blue : entropy_y.direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].black-entropy_xy1.direction[i].black)/ (entropy_x.direction[i].black > entropy_y.direction[i].black ? entropy_x.direction[i].black : entropy_y.direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].alpha-entropy_xy1.direction[i].alpha)/ (entropy_x.direction[i].alpha > entropy_y.direction[i].alpha ? entropy_x.direction[i].alpha : entropy_y.direction[i].alpha); channel_features[RedPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].red- entropy_xy.direction[i].red))))); channel_features[GreenPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].green- entropy_xy.direction[i].green))))); channel_features[BluePixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].blue- entropy_xy.direction[i].blue))))); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].black- entropy_xy.direction[i].black))))); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].alpha- entropy_xy.direction[i].alpha))))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { ssize_t z; for (z=0; z < (ssize_t) number_grays; z++) { register ssize_t y; ChannelStatistics pixel; (void) memset(&pixel,0,sizeof(pixel)); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Contrast: amount of local variations present in an image. */ if (((y-x) == z) || ((x-y) == z)) { pixel.direction[i].red+=cooccurrence[x][y].direction[i].red; pixel.direction[i].green+=cooccurrence[x][y].direction[i].green; pixel.direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) pixel.direction[i].black+=cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) pixel.direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; } /* Maximum Correlation Coefficient. */ Q[z][y].direction[i].red+=cooccurrence[z][x].direction[i].red* cooccurrence[y][x].direction[i].red/density_x[z].direction[i].red/ density_y[x].direction[i].red; Q[z][y].direction[i].green+=cooccurrence[z][x].direction[i].green* cooccurrence[y][x].direction[i].green/ density_x[z].direction[i].green/density_y[x].direction[i].red; Q[z][y].direction[i].blue+=cooccurrence[z][x].direction[i].blue* cooccurrence[y][x].direction[i].blue/density_x[z].direction[i].blue/ density_y[x].direction[i].blue; if (image->colorspace == CMYKColorspace) Q[z][y].direction[i].black+=cooccurrence[z][x].direction[i].black* cooccurrence[y][x].direction[i].black/ density_x[z].direction[i].black/density_y[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) Q[z][y].direction[i].alpha+= cooccurrence[z][x].direction[i].alpha* cooccurrence[y][x].direction[i].alpha/ density_x[z].direction[i].alpha/ density_y[x].direction[i].alpha; } } channel_features[RedPixelChannel].contrast[i]+=z*z* pixel.direction[i].red; channel_features[GreenPixelChannel].contrast[i]+=z*z* pixel.direction[i].green; channel_features[BluePixelChannel].contrast[i]+=z*z* pixel.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].contrast[i]+=z*z* pixel.direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].contrast[i]+=z*z* pixel.direction[i].alpha; } /* Maximum Correlation Coefficient. Future: return second largest eigenvalue of Q. */ channel_features[RedPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[GreenPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[BluePixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); } /* Relinquish resources. */ sum=(ChannelStatistics *) RelinquishMagickMemory(sum); for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); return(channel_features); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H o u g h L i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Use HoughLineImage() in conjunction with any binary edge extracted image (we % recommand Canny) to identify lines in the image. The algorithm accumulates % counts for every white pixel for every possible orientation (for angles from % 0 to 179 in 1 degree increments) and distance from the center of the image to % the corner (in 1 px increments) and stores the counts in an accumulator % matrix of angle vs distance. The size of the accumulator is 180x(diagonal/2). % Next it searches this space for peaks in counts and converts the locations % of the peaks to slope and intercept in the normal x,y input image space. Use % the slope/intercepts to find the endpoints clipped to the bounds of the % image. The lines are then drawn. The counts are a measure of the length of % the lines. % % The format of the HoughLineImage method is: % % Image *HoughLineImage(const Image *image,const size_t width, % const size_t height,const size_t threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find line pairs as local maxima in this neighborhood. % % o threshold: the line count threshold. % % o exception: return any errors or warnings in this structure. % */ 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)); } static Image *RenderHoughLines(const ImageInfo *image_info,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define BoundingBox "viewbox" DrawInfo *draw_info; Image *image; MagickBooleanType status; /* Open image. */ image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->columns=columns; image->rows=rows; draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->affine.sx=image->resolution.x == 0.0 ? 1.0 : image->resolution.x/ DefaultResolution; draw_info->affine.sy=image->resolution.y == 0.0 ? 1.0 : image->resolution.y/ DefaultResolution; image->columns=(size_t) (draw_info->affine.sx*image->columns); image->rows=(size_t) (draw_info->affine.sy*image->rows); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Render drawing. */ if (GetBlobStreamData(image) == (unsigned char *) NULL) draw_info->primitive=FileToString(image->filename,~0UL,exception); else { draw_info->primitive=(char *) AcquireMagickMemory((size_t) GetBlobSize(image)+1); if (draw_info->primitive != (char *) NULL) { (void) memcpy(draw_info->primitive,GetBlobStreamData(image), (size_t) GetBlobSize(image)); draw_info->primitive[GetBlobSize(image)]='\0'; } } (void) DrawImage(image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } MagickExport Image *HoughLineImage(const Image *image,const size_t width, const size_t height,const size_t threshold,ExceptionInfo *exception) { #define HoughLineImageTag "HoughLine/Image" CacheView *image_view; char message[MagickPathExtent], path[MagickPathExtent]; const char *artifact; double hough_height; Image *lines_image = NULL; ImageInfo *image_info; int file; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *accumulator; PointInfo center; register ssize_t y; size_t accumulator_height, accumulator_width, line_count; /* Create the accumulator. */ assert(image != (const 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); accumulator_width=180; hough_height=((sqrt(2.0)*(double) (image->rows > image->columns ? image->rows : image->columns))/2.0); accumulator_height=(size_t) (2.0*hough_height); accumulator=AcquireMatrixInfo(accumulator_width,accumulator_height, sizeof(double),exception); if (accumulator == (MatrixInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); if (NullMatrix(accumulator) == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Populate the accumulator. */ status=MagickTrue; progress=0; center.x=(double) image->columns/2.0; center.y=(double) image->rows/2.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelIntensity(image,p) > (QuantumRange/2.0)) { register ssize_t i; for (i=0; i < 180; i++) { double count, radius; radius=(((double) x-center.x)*cos(DegreesToRadians((double) i)))+ (((double) y-center.y)*sin(DegreesToRadians((double) i))); (void) GetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); count++; (void) SetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); } } p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CannyEdgeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } /* Generate line segments from accumulator. */ file=AcquireUniqueFileResource(path); if (file == -1) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } (void) FormatLocaleString(message,MagickPathExtent, "# Hough line transform: %.20gx%.20g%+.20g\n",(double) width, (double) height,(double) threshold); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; (void) FormatLocaleString(message,MagickPathExtent, "viewbox 0 0 %.20g %.20g\n",(double) image->columns,(double) image->rows); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; (void) FormatLocaleString(message,MagickPathExtent, "# x1,y1 x2,y2 # count angle distance\n"); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; line_count=image->columns > image->rows ? image->columns/4 : image->rows/4; if (threshold != 0) line_count=threshold; for (y=0; y < (ssize_t) accumulator_height; y++) { register ssize_t x; for (x=0; x < (ssize_t) accumulator_width; x++) { double count; (void) GetMatrixElement(accumulator,x,y,&count); if (count >= (double) line_count) { double maxima; SegmentInfo line; ssize_t v; /* Is point a local maxima? */ maxima=count; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((u != 0) || (v !=0)) { (void) GetMatrixElement(accumulator,x+u,y+v,&count); if (count > maxima) { maxima=count; break; } } } if (u < (ssize_t) (width/2)) break; } (void) GetMatrixElement(accumulator,x,y,&count); if (maxima > count) continue; if ((x >= 45) && (x <= 135)) { /* y = (r-x cos(t))/sin(t) */ line.x1=0.0; line.y1=((double) (y-(accumulator_height/2.0))-((line.x1- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); line.x2=(double) image->columns; line.y2=((double) (y-(accumulator_height/2.0))-((line.x2- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); } else { /* x = (r-y cos(t))/sin(t) */ line.y1=0.0; line.x1=((double) (y-(accumulator_height/2.0))-((line.y1- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); line.y2=(double) image->rows; line.x2=((double) (y-(accumulator_height/2.0))-((line.y2- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); } (void) FormatLocaleString(message,MagickPathExtent, "line %g,%g %g,%g # %g %g %g\n",line.x1,line.y1,line.x2,line.y2, maxima,(double) x,(double) y); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; } } } (void) close(file); /* Render lines to image canvas. */ image_info=AcquireImageInfo(); image_info->background_color=image->background_color; (void) FormatLocaleString(image_info->filename,MagickPathExtent,"%s",path); artifact=GetImageArtifact(image,"background"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"background",artifact); artifact=GetImageArtifact(image,"fill"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"fill",artifact); artifact=GetImageArtifact(image,"stroke"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"stroke",artifact); artifact=GetImageArtifact(image,"strokewidth"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"strokewidth",artifact); lines_image=RenderHoughLines(image_info,image->columns,image->rows,exception); artifact=GetImageArtifact(image,"hough-lines:accumulator"); if ((lines_image != (Image *) NULL) && (IsStringTrue(artifact) != MagickFalse)) { Image *accumulator_image; accumulator_image=MatrixToImage(accumulator,exception); if (accumulator_image != (Image *) NULL) AppendImageToList(&lines_image,accumulator_image); } /* Free resources. */ accumulator=DestroyMatrixInfo(accumulator); image_info=DestroyImageInfo(image_info); (void) RelinquishUniqueFileResource(path); return(GetFirstImageInList(lines_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e a n S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MeanShiftImage() delineate arbitrarily shaped clusters in the image. For % each pixel, it visits all the pixels in the neighborhood specified by % the window centered at the pixel and excludes those that are outside the % radius=(window-1)/2 surrounding the pixel. From those pixels, it finds those % that are within the specified color distance from the current mean, and % computes a new x,y centroid from those coordinates and a new mean. This new % x,y centroid is used as the center for a new window. This process iterates % until it converges and the final mean is replaces the (original window % center) pixel value. It repeats this process for the next pixel, etc., % until it processes all pixels in the image. Results are typically better with % colorspaces other than sRGB. We recommend YIQ, YUV or YCbCr. % % The format of the MeanShiftImage method is: % % Image *MeanShiftImage(const Image *image,const size_t width, % const size_t height,const double color_distance, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find pixels in this neighborhood. % % o color_distance: the color distance. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MeanShiftImage(const Image *image,const size_t width, const size_t height,const double color_distance,ExceptionInfo *exception) { #define MaxMeanShiftIterations 100 #define MeanShiftImageTag "MeanShift/Image" CacheView *image_view, *mean_view, *pixel_view; Image *mean_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (const 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); mean_image=CloneImage(image,0,0,MagickTrue,exception); if (mean_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse) { mean_image=DestroyImage(mean_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); pixel_view=AcquireVirtualCacheView(image,exception); mean_view=AcquireAuthenticCacheView(mean_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,progress) \ magick_number_threads(mean_image,mean_image,mean_image->rows,1) #endif for (y=0; y < (ssize_t) mean_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) mean_image->columns; x++) { PixelInfo mean_pixel, previous_pixel; PointInfo mean_location, previous_location; register ssize_t i; GetPixelInfo(image,&mean_pixel); GetPixelInfoPixel(image,p,&mean_pixel); mean_location.x=(double) x; mean_location.y=(double) y; for (i=0; i < MaxMeanShiftIterations; i++) { double distance, gamma; PixelInfo sum_pixel; PointInfo sum_location; ssize_t count, v; sum_location.x=0.0; sum_location.y=0.0; GetPixelInfo(image,&sum_pixel); previous_location=mean_location; previous_pixel=mean_pixel; count=0; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) { PixelInfo pixel; status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t) MagickRound(mean_location.x+u),(ssize_t) MagickRound( mean_location.y+v),&pixel,exception); distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); if (distance <= (color_distance*color_distance)) { sum_location.x+=mean_location.x+u; sum_location.y+=mean_location.y+v; sum_pixel.red+=pixel.red; sum_pixel.green+=pixel.green; sum_pixel.blue+=pixel.blue; sum_pixel.alpha+=pixel.alpha; count++; } } } } gamma=1.0/count; mean_location.x=gamma*sum_location.x; mean_location.y=gamma*sum_location.y; mean_pixel.red=gamma*sum_pixel.red; mean_pixel.green=gamma*sum_pixel.green; mean_pixel.blue=gamma*sum_pixel.blue; mean_pixel.alpha=gamma*sum_pixel.alpha; distance=(mean_location.x-previous_location.x)* (mean_location.x-previous_location.x)+ (mean_location.y-previous_location.y)* (mean_location.y-previous_location.y)+ 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); if (distance <= 3.0) break; } SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q); SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q); SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q); SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q); p+=GetPixelChannels(image); q+=GetPixelChannels(mean_image); } if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } mean_view=DestroyCacheView(mean_view); pixel_view=DestroyCacheView(pixel_view); image_view=DestroyCacheView(image_view); return(mean_image); }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_1008_0
crossvul-cpp_data_good_4778_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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-2016 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/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/draw.h" #include "magick/enhance.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/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/memory-private.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/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/splay-tree.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread_.h" #include "magick/token.h" #include "magick/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; #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 *), WritePTIFImage(const ImageInfo *,Image *), WriteTIFFImage(const ImageInfo *,Image *); #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[MaxTextExtent]; 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 == 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); } /* 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); 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,(size_t) (image->x_resolution+0.5)); 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); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); 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,"GROUP4",MaxTextExtent); } (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 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; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(q)+0.5; if (a > 1.0) a-=1.0; b=QuantumScale*GetPixelb(q)+0.5; if (b > 1.0) b-=1.0; SetPixela(q,QuantumRange*a); SetPixelb(q,QuantumRange*b); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType ReadProfile(Image *image,const char *name, const unsigned char *datum,ssize_t length) { 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); 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[MaxTextExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MaxTextExtent,format,error); #else (void) vsprintf(message,format,error); #endif (void) ConcatenateMagickString(message,".",MaxTextExtent); 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,MagickBooleanType ping) { uint32 length; unsigned char *profile; length=0; if (ping == MagickFalse) { #if defined(TIFFTAG_ICCPROFILE) if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"icc",profile,(ssize_t) length); #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); #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); } #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); #endif if ((TIFFGetField(tiff,34118,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length); } if ((TIFFGetField(tiff,37724,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length); } static void TIFFGetProperties(TIFF *tiff,Image *image) { char message[MaxTextExtent], *text; uint32 count, length, type; unsigned long *tietz; if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) (void) SetImageProperty(image,"tiff:artist",text); if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) (void) SetImageProperty(image,"tiff:copyright",text); if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) (void) SetImageProperty(image,"tiff:timestamp",text); if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) (void) SetImageProperty(image,"tiff:document",text); if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) (void) SetImageProperty(image,"tiff:hostcomputer",text); if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) (void) SetImageProperty(image,"comment",text); if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) (void) SetImageProperty(image,"tiff:make",text); if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) (void) SetImageProperty(image,"tiff:model",text); if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message); } if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) (void) SetImageProperty(image,"label",text); if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) (void) SetImageProperty(image,"tiff:software",text); if (TIFFGetField(tiff,33423,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message); } if (TIFFGetField(tiff,36867,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE"); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE"); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK"); break; } default: break; } if (TIFFGetField(tiff,37706,&length,&tietz) == 1) { (void) FormatLocaleString(message,MaxTextExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message); } } static void TIFFGetEXIFProperties(TIFF *tiff,Image *image) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MaxTextExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans; /* 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; } sans=NULL; 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,&sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MaxTextExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, &sans,&sans); if (tiff_status == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%.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,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value); } 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,size_t bits_per_sample, tsample_t sample,ssize_t row,tdata_t scanline) { int32 status; (void) bits_per_sample; 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[MaxTextExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MaxTextExtent,format,warning); #else (void) vsprintf(message,format,warning); #endif (void) ConcatenateMagickString(message,".",MaxTextExtent); 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 */ if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value)) 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 void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; const StringInfo *layer_info; Image *layers; 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; layer_info=GetImageProfile(image,"tiff:37724"); if (layer_info == (const StringInfo *) NULL) return; for (i=0; i < (ssize_t) layer_info->length-8; i++) { if (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0) continue; i+=4; if ((LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0)) break; } i+=4; if (i >= (ssize_t) (layer_info->length-8)) return; layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception); (void) DeleteImageProfile(layers,"tiff:37724"); AttachBlob(layers->blob,layer_info->datum,layer_info->length); SeekBlob(layers,(MagickOffsetType) i,SEEK_SET); info.version=1; info.columns=layers->columns; info.rows=layers->rows; /* Setting the mode to a value that won't change the colorspace */ info.mode=10; if (IsGrayImage(image,&image->exception) != MagickFalse) info.channels=(image->matte != MagickFalse ? 2UL : 1UL); else if (image->storage_class == PseudoClass) info.channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->colorspace != CMYKColorspace) info.channels=(image->matte != MagickFalse ? 4UL : 3UL); else info.channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) ReadPSDLayers(layers,image_info,&info,MagickFalse,exception); InheritException(exception,&layers->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); } } } #if defined(__cplusplus) || defined(c_plusplus) } #endif static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType 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 *pixels; /* Open image. */ 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) 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); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 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) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK"); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); 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")); } 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"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image,image_info->ping); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=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->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-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[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING, &horizontal,&vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (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; } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(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) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(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"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } 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) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; 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->matte == MagickFalse) image->depth=GetImageDepth(image,exception); } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { quantum_info=DestroyQuantumInfo(quantum_info); break; } goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) 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; pixels=GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,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->matte != MagickFalse) { 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->matte != MagickFalse) { 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) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,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 PixelPacket *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) 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,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: { pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; 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 PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p)))); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p)))); p++; q++; } 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)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } tile_pixels=(uint32 *) AcquireQuantumMemory(columns, rows*sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *magick_restrict q; 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 == (PixelPacket *) 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+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); q++; p++; } p+=columns-columns_remaining; q-=(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) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(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 PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } 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; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: 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; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* 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,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image = DestroyImageList(image); return((Image *)NULL); } } 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)); /* This also sets field_bit to 0 (FIELD_IGNORE) */ ResetMagickMemory(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[MaxTextExtent]; 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,MaxTextExtent,"%d",TIFF_VERSION); #endif #if defined(MAGICKCORE_TIFF_DELEGATE) { const char *p; register ssize_t i; p=TIFFGetVersion(); for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++) version[i]=(*p++); version[i]='\0'; } #endif entry=SetMagickInfo("GROUP4"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadGROUP4Image; entry->encoder=(EncodeImageHandler *) WriteGROUP4Image; #endif entry->raw=MagickTrue; entry->endian_support=MagickTrue; entry->adjoin=MagickFalse; entry->format_type=ImplicitFormatType; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Raw CCITT Group4"); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PTIF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WritePTIFImage; #endif entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Pyramid encoded TIFF"); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->stealth=MagickTrue; entry->description=ConstantString(TIFFDescription); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIFF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->magick=(IsImageFormatHandler *) IsTIFF; entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString(TIFFDescription); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIFF64"); #if defined(TIFF_VERSION_BIG) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->adjoin=MagickFalse; entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Tagged Image File Format (64-bit)"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("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 (DeleteMagickThreadKey(tiff_exception) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) (void) TIFFSetTagExtender(tag_extender); #endif (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); instantiate_key=MagickFalse; } UnlockSemaphoreInfo(tiff_semaphore); DestroySemaphoreInfo(&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) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image) { char filename[MaxTextExtent]; 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 == 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); huffman_image=CloneImage(image,0,0,MagickTrue,&image->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(&image->exception,FileOpenError, "UnableToCreateTemporaryFile",filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageDepth(image,1); (void) SetImageType(image,BilevelType); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { InheritException(&image->exception,&huffman_image->exception); 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(&image->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) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ 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. */ exception=(&image->exception); 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"); AppendImageToList(&images,clone_image); columns=next->columns; rows=next->rows; resolution.x=next->x_resolution; resolution.y=next->y_resolution; while ((columns > 64) && (rows > 64)) { columns/=2; rows/=2; resolution.x/=2.0; resolution.y/=2.0; pyramid_image=ResizeImage(next,columns,rows,image->filter,image->blur, exception); if (pyramid_image == (Image *) NULL) break; pyramid_image->x_resolution=resolution.x; pyramid_image->y_resolution=resolution.y; (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE"); AppendImageToList(&images,pyramid_image); } } /* Write pyramid-encoded TIFF image. */ write_info=CloneImageInfo(image_info); write_info->adjoin=MagickTrue; status=WriteTIFFImage(write_info,GetFirstImageInList(images)); 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) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ 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 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; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(q)-0.5; if (a < 0.0) a+=1.0; b=QuantumScale*GetPixelb(q)-0.5; if (b < 0.0) b+=1.0; SetPixela(q,QuantumRange*a); SetPixelb(q,QuantumRange*b); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } 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) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) return(MagickTrue); 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; 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) CopyMagickMemory(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 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 ImageInfo *image_info, Image *image) { 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"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value); value=GetImageProperty(image,"comment"); 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 ((image_info->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) { #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); 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) { #if !defined(TIFFDefaultStripSize) #define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff)) #endif const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric; uint32 rows_per_strip; unsigned char *pixels; /* Open TIFF 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) SetMagickThreadValue(tiff_exception,&image->exception); endian_type=UndefinedEndian; 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;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #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; do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type); 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); (void) SetImageDepth(image,1); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); 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,&image->exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) 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(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; } #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(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; 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,&image->exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,&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->matte == MagickFalse)) SetImageMonochrome(image,&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->matte != MagickFalse) { 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); rows_per_strip=1; if (TIFFScanlineSize(tiff) != 0) rows_per_strip=TIFFDefaultStripSize(tiff,0); option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; rows_per_strip+=(16-(rows_per_strip % 16)); 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); sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor"); 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; if (image->colorspace == YCbCrColorspace) (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: { rows_per_strip=(uint32) image->rows; (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_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. */ rows_per_strip=(uint32) image->rows; (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: { rows_per_strip=(uint32) image->rows; 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))) (void) TIFFSetField(tiff,TIFFTAG_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))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); break; } default: break; } if (rows_per_strip < 1) rows_per_strip=1; if ((image->rows/rows_per_strip) >= (1UL << 15)) rows_per_strip=(uint32) (image->rows >> 15); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); if ((image->x_resolution != 0.0) && (image->y_resolution != 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->x_resolution); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"TIFF: negative image positions unsupported","%s", image->filename); if ((image->page.x > 0) && (image->x_resolution > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->x_resolution); } if ((image->page.y > 0) && (image->y_resolution > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->y_resolution); } } 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); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, GetImageListLength(image)); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) GetImageListLength(image); if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=GetQuantumPixels(quantum_info); tiff_info.scanline=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->matte != MagickFalse) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->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 PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,pixels,&image->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 PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GreenQuantum,pixels,&image->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 PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlueQuantum,pixels,&image->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->matte != MagickFalse) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->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->matte != MagickFalse) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->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)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize TIFF colormap. */ (void) ResetMagickMemory(red,0,65536*sizeof(*red)); (void) ResetMagickMemory(green,0,65536*sizeof(*green)); (void) ResetMagickMemory(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->matte != MagickFalse) { 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 PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->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,&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++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-369/c/good_4778_1
crossvul-cpp_data_good_2303_2
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library VMS-specific Routines. */ #include <stdlib.h> #include <unixio.h> #include "tiffiop.h" #if !HAVE_IEEEFP #include <math.h> #endif #ifdef VAXC #define NOSHARE noshare #else #define NOSHARE #endif COMPILATION SHOULD FAIL This file is not yet updated to reflect changes in LibTiff 4.0. If you have the opportunity to update and test this file, please contact LibTiff folks for all assistance you may require and contribute the results #ifdef __alpha /* Dummy entry point for backwards compatibility */ void TIFFModeCCITTFax3(void){} #endif static tsize_t _tiffReadProc(thandle_t fd, tdata_t buf, tsize_t size) { return (read((int) fd, buf, size)); } static tsize_t _tiffWriteProc(thandle_t fd, tdata_t buf, tsize_t size) { return (write((int) fd, buf, size)); } static toff_t _tiffSeekProc(thandle_t fd, toff_t off, int whence) { return ((toff_t) lseek((int) fd, (off_t) off, whence)); } static int _tiffCloseProc(thandle_t fd) { return (close((int) fd)); } #include <sys/stat.h> static toff_t _tiffSizeProc(thandle_t fd) { struct stat sb; return (toff_t) (fstat((int) fd, &sb) < 0 ? 0 : sb.st_size); } #ifdef HAVE_MMAP #include <starlet.h> #include <fab.h> #include <secdef.h> /* * Table for storing information on current open sections. * (Should really be a linked list) */ #define MAX_MAPPED 100 static int no_mapped = 0; static struct { char *base; char *top; unsigned short channel; } map_table[MAX_MAPPED]; /* * This routine maps a file into a private section. Note that this * method of accessing a file is by far the fastest under VMS. * The routine may fail (i.e. return 0) for several reasons, for * example: * - There is no more room for storing the info on sections. * - The process is out of open file quota, channels, ... * - fd does not describe an opened file. * - The file is already opened for write access by this process * or another process * - There is no free "hole" in virtual memory that fits the * size of the file */ static int _tiffMapProc(thandle_t fd, tdata_t* pbase, toff_t* psize) { char name[256]; struct FAB fab; unsigned short channel; char *inadr[2], *retadr[2]; unsigned long status; long size; if (no_mapped >= MAX_MAPPED) return(0); /* * We cannot use a file descriptor, we * must open the file once more. */ if (getname((int)fd, name, 1) == NULL) return(0); /* prepare the FAB for a user file open */ fab = cc$rms_fab; fab.fab$l_fop |= FAB$V_UFO; fab.fab$b_fac = FAB$M_GET; fab.fab$b_shr = FAB$M_SHRGET; fab.fab$l_fna = name; fab.fab$b_fns = strlen(name); status = sys$open(&fab); /* open file & get channel number */ if ((status&1) == 0) return(0); channel = (unsigned short)fab.fab$l_stv; inadr[0] = inadr[1] = (char *)0; /* just an address in P0 space */ /* * Map the blocks of the file up to * the EOF block into virtual memory. */ size = _tiffSizeProc(fd); status = sys$crmpsc(inadr, retadr, 0, SEC$M_EXPREG, 0,0,0, channel, TIFFhowmany(size,512), 0,0,0); ddd if ((status&1) == 0){ sys$dassgn(channel); return(0); } *pbase = (tdata_t) retadr[0]; /* starting virtual address */ /* * Use the size of the file up to the * EOF mark for UNIX compatibility. */ *psize = (toff_t) size; /* Record the section in the table */ map_table[no_mapped].base = retadr[0]; map_table[no_mapped].top = retadr[1]; map_table[no_mapped].channel = channel; no_mapped++; return(1); } /* * This routine unmaps a section from the virtual address space of * the process, but only if the base was the one returned from a * call to TIFFMapFileContents. */ static void _tiffUnmapProc(thandle_t fd, tdata_t base, toff_t size) { char *inadr[2]; int i, j; /* Find the section in the table */ for (i = 0;i < no_mapped; i++) { if (map_table[i].base == (char *) base) { /* Unmap the section */ inadr[0] = (char *) base; inadr[1] = map_table[i].top; sys$deltva(inadr, 0, 0); sys$dassgn(map_table[i].channel); /* Remove this section from the list */ for (j = i+1; j < no_mapped; j++) map_table[j-1] = map_table[j]; no_mapped--; return; } } } #else /* !HAVE_MMAP */ static int _tiffMapProc(thandle_t fd, tdata_t* pbase, toff_t* psize) { return (0); } static void _tiffUnmapProc(thandle_t fd, tdata_t base, toff_t size) { } #endif /* !HAVE_MMAP */ /* * Open a TIFF file descriptor for read/writing. */ TIFF* TIFFFdOpen(int fd, const char* name, const char* mode) { TIFF* tif; tif = TIFFClientOpen(name, mode, ddd (thandle_t) fd, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); if (tif) tif->tif_fd = fd; return (tif); } /* * Open a TIFF file for read/writing. */ TIFF* TIFFOpen(const char* name, const char* mode) { static const char module[] = "TIFFOpen"; int m, fd; m = _TIFFgetMode(mode, module); if (m == -1) return ((TIFF*)0); if (m&O_TRUNC){ /* * There is a bug in open in VAXC. If you use * open w/ m=O_RDWR|O_CREAT|O_TRUNC the * wrong thing happens. On the other hand * creat does the right thing. */ fd = creat((char *) /* bug in stdio.h */ name, 0666, "alq = 128", "deq = 64", "mbc = 32", "fop = tef"); } else if (m&O_RDWR) { fd = open(name, m, 0666, "deq = 64", "mbc = 32", "fop = tef", "ctx = stm"); } else fd = open(name, m, 0666, "mbc = 32", "ctx = stm"); if (fd < 0) { TIFFErrorExt(0, module, "%s: Cannot open", name); return ((TIFF*)0); } return (TIFFFdOpen(fd, name, mode)); } tdata_t _TIFFmalloc(tsize_t s) { if (s == 0) return ((void *) NULL); return (malloc((size_t) s)); } void _TIFFfree(tdata_t p) { free(p); } tdata_t _TIFFrealloc(tdata_t p, tsize_t s) { return (realloc(p, (size_t) s)); } void _TIFFmemset(tdata_t p, int v, tsize_t c) { memset(p, v, (size_t) c); } void _TIFFmemcpy(tdata_t d, const tdata_t s, tsize_t c) { memcpy(d, s, (size_t) c); } int _TIFFmemcmp(const tdata_t p1, const tdata_t p2, tsize_t c) { return (memcmp(p1, p2, (size_t) c)); } /* * On the VAX, we need to make those global, writable pointers * non-shareable, otherwise they would be made shareable by default. * On the AXP, this brain damage has been corrected. * * I (Karsten Spang, krs@kampsax.dk) have dug around in the GCC * manual and the GAS code and have come up with the following * construct, but I don't have GCC on my VAX, so it is untested. * Please tell me if it does not work. */ static void vmsWarningHandler(const char* module, const char* fmt, va_list ap) { if (module != NULL) fprintf(stderr, "%s: ", module); fprintf(stderr, "Warning, "); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); } NOSHARE TIFFErrorHandler _TIFFwarningHandler = vmsWarningHandler #if defined(VAX) && defined(__GNUC__) asm("_$$PsectAttributes_NOSHR$$_TIFFwarningHandler") #endif ; static void vmsErrorHandler(const char* module, const char* fmt, va_list ap) { if (module != NULL) fprintf(stderr, "%s: ", module); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); } NOSHARE TIFFErrorHandler _TIFFerrorHandler = vmsErrorHandler #if defined(VAX) && defined(__GNUC__) asm("_$$PsectAttributes_NOSHR$$_TIFFerrorHandler") #endif ; #if !HAVE_IEEEFP /* IEEE floting point handling */ typedef struct ieeedouble { unsigned long mant2; /* fix NDR: full 8-byte swap */ unsigned long mant : 20, exp : 11, sign : 1; } ieeedouble; typedef struct ieeefloat { unsigned long mant : 23, exp : 8, sign : 1; } ieeefloat; /* * NB: These are D_FLOAT's, not G_FLOAT's. A G_FLOAT is * simply a reverse-IEEE float/double. */ typedef struct { unsigned long mant1 : 7, exp : 8, sign : 1, mant2 : 16, mant3 : 16, mant4 : 16; } nativedouble; typedef struct { unsigned long mant1 : 7, exp : 8, sign : 1, mant2 : 16; } nativefloat; typedef union { ieeedouble ieee; nativedouble native; char b[8]; uint32 l[2]; double d; } double_t; typedef union { ieeefloat ieee; nativefloat native; char b[4]; uint32 l; float f; } float_t; #if defined(VAXC) || defined(DECC) #pragma inline(ieeetod,dtoieee) #endif /* * Convert an IEEE double precision number to native double precision. * The source is contained in two longwords, the second holding the sign, * exponent and the higher order bits of the mantissa, and the first * holding the rest of the mantissa as follows: * (Note: It is assumed that the number has been eight-byte swapped to * LSB first.) * * First longword: * 32 least significant bits of mantissa * Second longword: * 0-19: 20 most significant bits of mantissa * 20-30: exponent * 31: sign * The exponent is stored as excess 1023. * The most significant bit of the mantissa is implied 1, and not stored. * If the exponent and mantissa are zero, the number is zero. * If the exponent is 0 (i.e. -1023) and the mantissa is non-zero, it is an * unnormalized number with the most significant bit NOT implied. * If the exponent is 2047, the number is invalid, in case the mantissa is zero, * this means overflow (+/- depending of the sign bit), otherwise * it simply means invalid number. * * If the number is too large for the machine or was specified as overflow, * +/-HUGE_VAL is returned. */ INLINE static void ieeetod(double *dp) { double_t source; long sign,exp,mant; double dmant; source.ieee = ((double_t*)dp)->ieee; sign = source.ieee.sign; exp = source.ieee.exp; mant = source.ieee.mant; if (exp == 2047) { if (mant) /* Not a Number (NAN) */ *dp = HUGE_VAL; else /* +/- infinity */ *dp = (sign ? -HUGE_VAL : HUGE_VAL); return; } if (!exp) { if (!(mant || source.ieee.mant2)) { /* zero */ *dp=0; return; } else { /* Unnormalized number */ /* NB: not -1023, the 1 bit is not implied */ exp= -1022; } } else { mant |= 1<<20; exp -= 1023; } dmant = (((double) mant) + ((double) source.ieee.mant2) / (((double) (1<<16)) * ((double) (1<<16)))) / (double) (1<<20); dmant = ldexp(dmant, exp); if (sign) dmant= -dmant; *dp = dmant; } INLINE static void dtoieee(double *dp) { double_t num; double x; int exp; num.d = *dp; if (!num.d) { /* Zero is just binary all zeros */ num.l[0] = num.l[1] = 0; return; } if (num.d < 0) { /* Sign is encoded separately */ num.d = -num.d; num.ieee.sign = 1; } else { num.ieee.sign = 0; } /* Now separate the absolute value into mantissa and exponent */ x = frexp(num.d, &exp); /* * Handle cases where the value is outside the * range for IEEE floating point numbers. * (Overflow cannot happen on a VAX, but underflow * can happen for G float.) */ if (exp < -1022) { /* Unnormalized number */ x = ldexp(x, -1023-exp); exp = 0; } else if (exp > 1023) { /* +/- infinity */ x = 0; exp = 2047; } else { /* Get rid of most significant bit */ x *= 2; x -= 1; exp += 1022; /* fix NDR: 1.0 -> x=0.5, exp=1 -> ieee.exp = 1023 */ } num.ieee.exp = exp; x *= (double) (1<<20); num.ieee.mant = (long) x; x -= (double) num.ieee.mant; num.ieee.mant2 = (long) (x*((double) (1<<16)*(double) (1<<16))); if (!(num.ieee.mant || num.ieee.exp || num.ieee.mant2)) { /* Avoid negative zero */ num.ieee.sign = 0; } ((double_t*)dp)->ieee = num.ieee; } /* * Beware, these do not handle over/under-flow * during conversion from ieee to native format. */ #define NATIVE2IEEEFLOAT(fp) { \ float_t t; \ if (t.ieee.exp = (fp)->native.exp) \ t.ieee.exp += -129 + 127; \ t.ieee.sign = (fp)->native.sign; \ t.ieee.mant = ((fp)->native.mant1<<16)|(fp)->native.mant2; \ *(fp) = t; \ } #define IEEEFLOAT2NATIVE(fp) { \ float_t t; int v = (fp)->ieee.exp; \ if (v) v += -127 + 129; /* alter bias of exponent */\ t.native.exp = v; /* implicit truncation of exponent */\ t.native.sign = (fp)->ieee.sign; \ v = (fp)->ieee.mant; \ t.native.mant1 = v >> 16; \ t.native.mant2 = v;\ *(fp) = t; \ } #define IEEEDOUBLE2NATIVE(dp) ieeetod(dp) #define NATIVE2IEEEDOUBLE(dp) dtoieee(dp) /* * These unions are used during floating point * conversions. The above macros define the * conversion operations. */ void TIFFCvtIEEEFloatToNative(TIFF* tif, u_int n, float* f) { float_t* fp = (float_t*) f; while (n-- > 0) { IEEEFLOAT2NATIVE(fp); fp++; } } void TIFFCvtNativeToIEEEFloat(TIFF* tif, u_int n, float* f) { float_t* fp = (float_t*) f; while (n-- > 0) { NATIVE2IEEEFLOAT(fp); fp++; } } void TIFFCvtIEEEDoubleToNative(TIFF* tif, u_int n, double* f) { double_t* fp = (double_t*) f; while (n-- > 0) { IEEEDOUBLE2NATIVE(fp); fp++; } } void TIFFCvtNativeToIEEEDouble(TIFF* tif, u_int n, double* f) { double_t* fp = (double_t*) f; while (n-- > 0) { NATIVE2IEEEDOUBLE(fp); fp++; } } #endif /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-369/c/good_2303_2
crossvul-cpp_data_bad_5310_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT U U M M % % Q Q U U A A NN N T U U MM MM % % Q Q U U AAAAA N N N T U U M M M % % Q QQ U U A A N NN T U U M M % % QQQQ UUU A A N N T UUU M M % % % % MagicCore Methods to Acquire / Destroy Quantum Pixels % % % % Software Design % % Cristy % % October 1998 % % % % % % Copyright 1999-2016 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/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/color-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/delegate.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/statistic.h" #include "magick/stream.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/utility.h" /* Define declarations. */ #define QuantumSignature 0xab /* Forward declarations. */ static void DestroyQuantumPixels(QuantumInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumInfo() allocates the QuantumInfo structure. % % The format of the AcquireQuantumInfo method is: % % QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ MagickExport QuantumInfo *AcquireQuantumInfo(const ImageInfo *image_info, Image *image) { MagickBooleanType status; QuantumInfo *quantum_info; quantum_info=(QuantumInfo *) AcquireMagickMemory(sizeof(*quantum_info)); if (quantum_info == (QuantumInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); quantum_info->signature=MagickSignature; GetQuantumInfo(image_info,quantum_info); if (image == (const Image *) NULL) return(quantum_info); status=SetQuantumDepth(image,quantum_info,image->depth); quantum_info->endian=image->endian; if (status == MagickFalse) quantum_info=DestroyQuantumInfo(quantum_info); return(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumPixels() allocates the pixel staging area. % % The format of the AcquireQuantumPixels method is: % % MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info, % const size_t extent) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o extent: the quantum info. % */ static MagickBooleanType AcquireQuantumPixels(QuantumInfo *quantum_info, const size_t extent) { register ssize_t i; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); quantum_info->pixels=(unsigned char **) AcquireQuantumMemory( quantum_info->number_threads,sizeof(*quantum_info->pixels)); if (quantum_info->pixels == (unsigned char **) NULL) return(MagickFalse); quantum_info->extent=extent; (void) ResetMagickMemory(quantum_info->pixels,0,quantum_info->number_threads* sizeof(*quantum_info->pixels)); for (i=0; i < (ssize_t) quantum_info->number_threads; i++) { quantum_info->pixels[i]=(unsigned char *) AcquireQuantumMemory(extent+1, sizeof(**quantum_info->pixels)); if (quantum_info->pixels[i] == (unsigned char *) NULL) { while (--i >= 0) quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory( quantum_info->pixels[i]); return(MagickFalse); } (void) ResetMagickMemory(quantum_info->pixels[i],0,(extent+1)* sizeof(**quantum_info->pixels)); quantum_info->pixels[i][extent]=QuantumSignature; } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantumInfo() deallocates memory associated with the QuantumInfo % structure. % % The format of the DestroyQuantumInfo method is: % % QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport QuantumInfo *DestroyQuantumInfo(QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); if (quantum_info->semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&quantum_info->semaphore); quantum_info->signature=(~MagickSignature); quantum_info=(QuantumInfo *) RelinquishMagickMemory(quantum_info); return(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantumPixels() destroys the quantum pixels. % % The format of the DestroyQuantumPixels() method is: % % void DestroyQuantumPixels(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ static void DestroyQuantumPixels(QuantumInfo *quantum_info) { register ssize_t i; ssize_t extent; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); assert(quantum_info->pixels != (unsigned char **) NULL); extent=(ssize_t) quantum_info->extent; for (i=0; i < (ssize_t) quantum_info->number_threads; i++) if (quantum_info->pixels[i] != (unsigned char *) NULL) { /* Did we overrun our quantum buffer? */ assert(quantum_info->pixels[i][extent] == QuantumSignature); quantum_info->pixels[i]=(unsigned char *) RelinquishMagickMemory( quantum_info->pixels[i]); } quantum_info->pixels=(unsigned char **) RelinquishMagickMemory( quantum_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumExtent() returns the quantum pixel buffer extent. % % The format of the GetQuantumExtent method is: % % size_t GetQuantumExtent(Image *image,const QuantumInfo *quantum_info, % const QuantumType quantum_type) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o quantum_type: Declare which pixel components to transfer (red, green, % blue, opacity, RGB, or RGBA). % */ MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t packet_size; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); packet_size=1; switch (quantum_type) { case GrayAlphaQuantum: packet_size=2; break; case IndexAlphaQuantum: packet_size=2; break; case RGBQuantum: packet_size=3; break; case BGRQuantum: packet_size=3; break; case RGBAQuantum: packet_size=4; break; case RGBOQuantum: packet_size=4; break; case BGRAQuantum: packet_size=4; break; case CMYKQuantum: packet_size=4; break; case CMYKAQuantum: packet_size=5; break; default: break; } if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*image->columns*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*image->columns*quantum_info->depth+7)/8)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m E n d i a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumEndian() returns the quantum endian of the image. % % The endian of the GetQuantumEndian method is: % % EndianType GetQuantumEndian(const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport EndianType GetQuantumEndian(const QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); return(quantum_info->endian); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumFormat() returns the quantum format of the image. % % The format of the GetQuantumFormat method is: % % QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickExport QuantumFormatType GetQuantumFormat(const QuantumInfo *quantum_info) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); return(quantum_info->format); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumInfo() initializes the QuantumInfo structure to default values. % % The format of the GetQuantumInfo method is: % % GetQuantumInfo(const ImageInfo *image_info,QuantumInfo *quantum_info) % % A description of each parameter follows: % % o image_info: the image info. % % o quantum_info: the quantum info. % */ MagickExport void GetQuantumInfo(const ImageInfo *image_info, QuantumInfo *quantum_info) { const char *option; assert(quantum_info != (QuantumInfo *) NULL); (void) ResetMagickMemory(quantum_info,0,sizeof(*quantum_info)); quantum_info->quantum=8; quantum_info->maximum=1.0; quantum_info->scale=QuantumRange; quantum_info->pack=MagickTrue; quantum_info->semaphore=AllocateSemaphoreInfo(); quantum_info->signature=MagickSignature; if (image_info == (const ImageInfo *) NULL) return; option=GetImageOption(image_info,"quantum:format"); if (option != (char *) NULL) quantum_info->format=(QuantumFormatType) ParseCommandOption( MagickQuantumFormatOptions,MagickFalse,option); option=GetImageOption(image_info,"quantum:minimum"); if (option != (char *) NULL) quantum_info->minimum=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"quantum:maximum"); if (option != (char *) NULL) quantum_info->maximum=StringToDouble(option,(char **) NULL); if ((quantum_info->minimum == 0.0) && (quantum_info->maximum == 0.0)) quantum_info->scale=0.0; else if (quantum_info->minimum == quantum_info->maximum) { quantum_info->scale=(MagickRealType) QuantumRange/quantum_info->minimum; quantum_info->minimum=0.0; } else quantum_info->scale=(MagickRealType) QuantumRange/(quantum_info->maximum- quantum_info->minimum); option=GetImageOption(image_info,"quantum:scale"); if (option != (char *) NULL) quantum_info->scale=StringToDouble(option,(char **) NULL); option=GetImageOption(image_info,"quantum:polarity"); if (option != (char *) NULL) quantum_info->min_is_white=LocaleCompare(option,"min-is-white") == 0 ? MagickTrue : MagickFalse; quantum_info->endian=image_info->endian; ResetQuantumState(quantum_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumPixels() returns the quantum pixels. % % The format of the GetQuantumPixels method is: % % unsigned char *QuantumPixels GetQuantumPixels( % const QuantumInfo *quantum_info) % % A description of each parameter follows: % % o image: the image. % */ MagickExport unsigned char *GetQuantumPixels(const QuantumInfo *quantum_info) { const int id = GetOpenMPThreadId(); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); return(quantum_info->pixels[id]); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t u m T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantumType() returns the quantum type of the image. % % The format of the GetQuantumType method is: % % QuantumType GetQuantumType(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % */ MagickExport QuantumType GetQuantumType(Image *image,ExceptionInfo *exception) { QuantumType quantum_type; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); (void) exception; quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; if (image->matte != MagickFalse) quantum_type=CMYKAQuantum; } if (IsGrayColorspace(image->colorspace) != MagickFalse) { quantum_type=GrayQuantum; if (image->matte != MagickFalse) quantum_type=GrayAlphaQuantum; } if (image->storage_class == PseudoClass) { quantum_type=IndexQuantum; if (image->matte != MagickFalse) quantum_type=IndexAlphaQuantum; } return(quantum_type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t Q u a n t u m S t a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetQuantumState() resets the quantum state. % % The format of the ResetQuantumState method is: % % void ResetQuantumState(QuantumInfo *quantum_info) % % A description of each parameter follows: % % o quantum_info: the quantum info. % */ MagickPrivate void ResetQuantumState(QuantumInfo *quantum_info) { static const unsigned int mask[32] = { 0x00000000U, 0x00000001U, 0x00000003U, 0x00000007U, 0x0000000fU, 0x0000001fU, 0x0000003fU, 0x0000007fU, 0x000000ffU, 0x000001ffU, 0x000003ffU, 0x000007ffU, 0x00000fffU, 0x00001fffU, 0x00003fffU, 0x00007fffU, 0x0000ffffU, 0x0001ffffU, 0x0003ffffU, 0x0007ffffU, 0x000fffffU, 0x001fffffU, 0x003fffffU, 0x007fffffU, 0x00ffffffU, 0x01ffffffU, 0x03ffffffU, 0x07ffffffU, 0x0fffffffU, 0x1fffffffU, 0x3fffffffU, 0x7fffffffU }; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->state.inverse_scale=1.0; if (fabs(quantum_info->scale) >= MagickEpsilon) quantum_info->state.inverse_scale/=quantum_info->scale; quantum_info->state.pixel=0U; quantum_info->state.bits=0U; quantum_info->state.mask=mask; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumAlphaType() sets the quantum format. % % The format of the SetQuantumAlphaType method is: % % void SetQuantumAlphaType(QuantumInfo *quantum_info, % const QuantumAlphaType type) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o type: the alpha type (e.g. associate). % */ MagickExport void SetQuantumAlphaType(QuantumInfo *quantum_info, const QuantumAlphaType type) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->alpha_type=type; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumDepth() sets the quantum depth. % % The format of the SetQuantumDepth method is: % % MagickBooleanType SetQuantumDepth(const Image *image, % QuantumInfo *quantum_info,const size_t depth) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o depth: the quantum depth. % */ MagickExport MagickBooleanType SetQuantumDepth(const Image *image, QuantumInfo *quantum_info,const size_t depth) { size_t extent, quantum; /* Allocate the quantum pixel buffer. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->depth=depth; if (quantum_info->format == FloatingPointQuantumFormat) { if (quantum_info->depth > 32) quantum_info->depth=64; else if (quantum_info->depth > 16) quantum_info->depth=32; else quantum_info->depth=16; } if (quantum_info->pixels != (unsigned char **) NULL) DestroyQuantumPixels(quantum_info); quantum=(quantum_info->pad+6)*(quantum_info->depth+7)/8; extent=image->columns*quantum; if (quantum != (extent/image->columns)) return(MagickFalse); return(AcquireQuantumPixels(quantum_info,extent)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m E n d i a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumEndian() sets the quantum endian. % % The endian of the SetQuantumEndian method is: % % MagickBooleanType SetQuantumEndian(const Image *image, % QuantumInfo *quantum_info,const EndianType endian) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o endian: the quantum endian. % */ MagickExport MagickBooleanType SetQuantumEndian(const Image *image, QuantumInfo *quantum_info,const EndianType endian) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->endian=endian; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m F o r m a t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumFormat() sets the quantum format. % % The format of the SetQuantumFormat method is: % % MagickBooleanType SetQuantumFormat(const Image *image, % QuantumInfo *quantum_info,const QuantumFormatType format) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o format: the quantum format. % */ MagickExport MagickBooleanType SetQuantumFormat(const Image *image, QuantumInfo *quantum_info,const QuantumFormatType format) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->format=format; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m I m a g e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumImageType() sets the image type based on the quantum type. % % The format of the SetQuantumImageType method is: % % void ImageType SetQuantumImageType(Image *image, % const QuantumType quantum_type) % % A description of each parameter follows: % % o image: the image. % % o quantum_type: Declare which pixel components to transfer (red, green, % blue, opacity, RGB, or RGBA). % */ MagickExport void SetQuantumImageType(Image *image, const QuantumType quantum_type) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); switch (quantum_type) { case IndexQuantum: case IndexAlphaQuantum: { image->type=PaletteType; break; } case GrayQuantum: case GrayAlphaQuantum: { image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; break; } case CyanQuantum: case MagentaQuantum: case YellowQuantum: case BlackQuantum: case CMYKQuantum: case CMYKAQuantum: { image->type=ColorSeparationType; break; } default: { image->type=TrueColorType; break; } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m P a c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumPack() sets the quantum pack flag. % % The format of the SetQuantumPack method is: % % void SetQuantumPack(QuantumInfo *quantum_info, % const MagickBooleanType pack) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o pack: the pack flag. % */ MagickExport void SetQuantumPack(QuantumInfo *quantum_info, const MagickBooleanType pack) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->pack=pack; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m P a d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumPad() sets the quantum pad. % % The format of the SetQuantumPad method is: % % MagickBooleanType SetQuantumPad(const Image *image, % QuantumInfo *quantum_info,const size_t pad) % % A description of each parameter follows: % % o image: the image. % % o quantum_info: the quantum info. % % o pad: the quantum pad. % */ MagickExport MagickBooleanType SetQuantumPad(const Image *image, QuantumInfo *quantum_info,const size_t pad) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->pad=pad; return(SetQuantumDepth(image,quantum_info,quantum_info->depth)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m M i n I s W h i t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumMinIsWhite() sets the quantum min-is-white flag. % % The format of the SetQuantumMinIsWhite method is: % % void SetQuantumMinIsWhite(QuantumInfo *quantum_info, % const MagickBooleanType min_is_white) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o min_is_white: the min-is-white flag. % */ MagickExport void SetQuantumMinIsWhite(QuantumInfo *quantum_info, const MagickBooleanType min_is_white) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->min_is_white=min_is_white; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m Q u a n t u m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumQuantum() sets the quantum quantum. % % The format of the SetQuantumQuantum method is: % % void SetQuantumQuantum(QuantumInfo *quantum_info, % const size_t quantum) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o quantum: the quantum quantum. % */ MagickExport void SetQuantumQuantum(QuantumInfo *quantum_info, const size_t quantum) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->quantum=quantum; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t Q u a n t u m S c a l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetQuantumScale() sets the quantum scale. % % The format of the SetQuantumScale method is: % % void SetQuantumScale(QuantumInfo *quantum_info,const double scale) % % A description of each parameter follows: % % o quantum_info: the quantum info. % % o scale: the quantum scale. % */ MagickExport void SetQuantumScale(QuantumInfo *quantum_info,const double scale) { assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickSignature); quantum_info->scale=scale; }
./CrossVul/dataset_final_sorted/CWE-369/c/bad_5310_0
crossvul-cpp_data_good_967_0
// SPDX-License-Identifier: GPL-2.0-only /* * linux/drivers/block/floppy.c * * Copyright (C) 1991, 1992 Linus Torvalds * Copyright (C) 1993, 1994 Alain Knaff * Copyright (C) 1998 Alan Cox */ /* * 02.12.91 - Changed to static variables to indicate need for reset * and recalibrate. This makes some things easier (output_byte reset * checking etc), and means less interrupt jumping in case of errors, * so the code is hopefully easier to understand. */ /* * This file is certainly a mess. I've tried my best to get it working, * but I don't like programming floppies, and I have only one anyway. * Urgel. I should check for more errors, and do more graceful error * recovery. Seems there are problems with several drives. I've tried to * correct them. No promises. */ /* * As with hd.c, all routines within this file can (and will) be called * by interrupts, so extreme caution is needed. A hardware interrupt * handler may not sleep, or a kernel panic will happen. Thus I cannot * call "floppy-on" directly, but have to set a special timer interrupt * etc. */ /* * 28.02.92 - made track-buffering routines, based on the routines written * by entropy@wintermute.wpi.edu (Lawrence Foard). Linus. */ /* * Automatic floppy-detection and formatting written by Werner Almesberger * (almesber@nessie.cs.id.ethz.ch), who also corrected some problems with * the floppy-change signal detection. */ /* * 1992/7/22 -- Hennus Bergman: Added better error reporting, fixed * FDC data overrun bug, added some preliminary stuff for vertical * recording support. * * 1992/9/17: Added DMA allocation & DMA functions. -- hhb. * * TODO: Errors are still not counted properly. */ /* 1992/9/20 * Modifications for ``Sector Shifting'' by Rob Hooft (hooft@chem.ruu.nl) * modeled after the freeware MS-DOS program fdformat/88 V1.8 by * Christoph H. Hochst\"atter. * I have fixed the shift values to the ones I always use. Maybe a new * ioctl() should be created to be able to modify them. * There is a bug in the driver that makes it impossible to format a * floppy as the first thing after bootup. */ /* * 1993/4/29 -- Linus -- cleaned up the timer handling in the kernel, and * this helped the floppy driver as well. Much cleaner, and still seems to * work. */ /* 1994/6/24 --bbroad-- added the floppy table entries and made * minor modifications to allow 2.88 floppies to be run. */ /* 1994/7/13 -- Paul Vojta -- modified the probing code to allow three or more * disk types. */ /* * 1994/8/8 -- Alain Knaff -- Switched to fdpatch driver: Support for bigger * format bug fixes, but unfortunately some new bugs too... */ /* 1994/9/17 -- Koen Holtman -- added logging of physical floppy write * errors to allow safe writing by specialized programs. */ /* 1995/4/24 -- Dan Fandrich -- added support for Commodore 1581 3.5" disks * by defining bit 1 of the "stretch" parameter to mean put sectors on the * opposite side of the disk, leaving the sector IDs alone (i.e. Commodore's * drives are "upside-down"). */ /* * 1995/8/26 -- Andreas Busse -- added Mips support. */ /* * 1995/10/18 -- Ralf Baechle -- Portability cleanup; move machine dependent * features to asm/floppy.h. */ /* * 1998/1/21 -- Richard Gooch <rgooch@atnf.csiro.au> -- devfs support */ /* * 1998/05/07 -- Russell King -- More portability cleanups; moved definition of * interrupt and dma channel to asm/floppy.h. Cleaned up some formatting & * use of '0' for NULL. */ /* * 1998/06/07 -- Alan Cox -- Merged the 2.0.34 fixes for resource allocation * failures. */ /* * 1998/09/20 -- David Weinehall -- Added slow-down code for buggy PS/2-drives. */ /* * 1999/08/13 -- Paul Slootman -- floppy stopped working on Alpha after 24 * days, 6 hours, 32 minutes and 32 seconds (i.e. MAXINT jiffies; ints were * being used to store jiffies, which are unsigned longs). */ /* * 2000/08/28 -- Arnaldo Carvalho de Melo <acme@conectiva.com.br> * - get rid of check_region * - s/suser/capable/ */ /* * 2001/08/26 -- Paul Gortmaker - fix insmod oops on machines with no * floppy controller (lingering task on list after module is gone... boom.) */ /* * 2002/02/07 -- Anton Altaparmakov - Fix io ports reservation to correct range * (0x3f2-0x3f5, 0x3f7). This fix is a bit of a hack but the proper fix * requires many non-obvious changes in arch dependent code. */ /* 2003/07/28 -- Daniele Bellucci <bellucda@tiscali.it>. * Better audit of register_blkdev. */ #undef FLOPPY_SILENT_DCL_CLEAR #define REALLY_SLOW_IO #define DEBUGT 2 #define DPRINT(format, args...) \ pr_info("floppy%d: " format, current_drive, ##args) #define DCL_DEBUG /* debug disk change line */ #ifdef DCL_DEBUG #define debug_dcl(test, fmt, args...) \ do { if ((test) & FD_DEBUG) DPRINT(fmt, ##args); } while (0) #else #define debug_dcl(test, fmt, args...) \ do { if (0) DPRINT(fmt, ##args); } while (0) #endif /* do print messages for unexpected interrupts */ static int print_unex = 1; #include <linux/module.h> #include <linux/sched.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/timer.h> #include <linux/workqueue.h> #define FDPATCHES #include <linux/fdreg.h> #include <linux/fd.h> #include <linux/hdreg.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/bio.h> #include <linux/string.h> #include <linux/jiffies.h> #include <linux/fcntl.h> #include <linux/delay.h> #include <linux/mc146818rtc.h> /* CMOS defines */ #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/mod_devicetable.h> #include <linux/mutex.h> #include <linux/io.h> #include <linux/uaccess.h> #include <linux/async.h> #include <linux/compat.h> /* * PS/2 floppies have much slower step rates than regular floppies. * It's been recommended that take about 1/4 of the default speed * in some more extreme cases. */ static DEFINE_MUTEX(floppy_mutex); static int slow_floppy; #include <asm/dma.h> #include <asm/irq.h> static int FLOPPY_IRQ = 6; static int FLOPPY_DMA = 2; static int can_use_virtual_dma = 2; /* ======= * can use virtual DMA: * 0 = use of virtual DMA disallowed by config * 1 = use of virtual DMA prescribed by config * 2 = no virtual DMA preference configured. By default try hard DMA, * but fall back on virtual DMA when not enough memory available */ static int use_virtual_dma; /* ======= * use virtual DMA * 0 using hard DMA * 1 using virtual DMA * This variable is set to virtual when a DMA mem problem arises, and * reset back in floppy_grab_irq_and_dma. * It is not safe to reset it in other circumstances, because the floppy * driver may have several buffers in use at once, and we do currently not * record each buffers capabilities */ static DEFINE_SPINLOCK(floppy_lock); static unsigned short virtual_dma_port = 0x3f0; irqreturn_t floppy_interrupt(int irq, void *dev_id); static int set_dor(int fdc, char mask, char data); #define K_64 0x10000 /* 64KB */ /* the following is the mask of allowed drives. By default units 2 and * 3 of both floppy controllers are disabled, because switching on the * motor of these drives causes system hangs on some PCI computers. drive * 0 is the low bit (0x1), and drive 7 is the high bit (0x80). Bits are on if * a drive is allowed. * * NOTE: This must come before we include the arch floppy header because * some ports reference this variable from there. -DaveM */ static int allowed_drive_mask = 0x33; #include <asm/floppy.h> static int irqdma_allocated; #include <linux/blk-mq.h> #include <linux/blkpg.h> #include <linux/cdrom.h> /* for the compatibility eject ioctl */ #include <linux/completion.h> static LIST_HEAD(floppy_reqs); static struct request *current_req; static int set_next_request(void); #ifndef fd_get_dma_residue #define fd_get_dma_residue() get_dma_residue(FLOPPY_DMA) #endif /* Dma Memory related stuff */ #ifndef fd_dma_mem_free #define fd_dma_mem_free(addr, size) free_pages(addr, get_order(size)) #endif #ifndef fd_dma_mem_alloc #define fd_dma_mem_alloc(size) __get_dma_pages(GFP_KERNEL, get_order(size)) #endif #ifndef fd_cacheflush #define fd_cacheflush(addr, size) /* nothing... */ #endif static inline void fallback_on_nodma_alloc(char **addr, size_t l) { #ifdef FLOPPY_CAN_FALLBACK_ON_NODMA if (*addr) return; /* we have the memory */ if (can_use_virtual_dma != 2) return; /* no fallback allowed */ pr_info("DMA memory shortage. Temporarily falling back on virtual DMA\n"); *addr = (char *)nodma_mem_alloc(l); #else return; #endif } /* End dma memory related stuff */ static unsigned long fake_change; static bool initialized; #define ITYPE(x) (((x) >> 2) & 0x1f) #define TOMINOR(x) ((x & 3) | ((x & 4) << 5)) #define UNIT(x) ((x) & 0x03) /* drive on fdc */ #define FDC(x) (((x) & 0x04) >> 2) /* fdc of drive */ /* reverse mapping from unit and fdc to drive */ #define REVDRIVE(fdc, unit) ((unit) + ((fdc) << 2)) #define DP (&drive_params[current_drive]) #define DRS (&drive_state[current_drive]) #define DRWE (&write_errors[current_drive]) #define FDCS (&fdc_state[fdc]) #define UDP (&drive_params[drive]) #define UDRS (&drive_state[drive]) #define UDRWE (&write_errors[drive]) #define UFDCS (&fdc_state[FDC(drive)]) #define PH_HEAD(floppy, head) (((((floppy)->stretch & 2) >> 1) ^ head) << 2) #define STRETCH(floppy) ((floppy)->stretch & FD_STRETCH) /* read/write */ #define COMMAND (raw_cmd->cmd[0]) #define DR_SELECT (raw_cmd->cmd[1]) #define TRACK (raw_cmd->cmd[2]) #define HEAD (raw_cmd->cmd[3]) #define SECTOR (raw_cmd->cmd[4]) #define SIZECODE (raw_cmd->cmd[5]) #define SECT_PER_TRACK (raw_cmd->cmd[6]) #define GAP (raw_cmd->cmd[7]) #define SIZECODE2 (raw_cmd->cmd[8]) #define NR_RW 9 /* format */ #define F_SIZECODE (raw_cmd->cmd[2]) #define F_SECT_PER_TRACK (raw_cmd->cmd[3]) #define F_GAP (raw_cmd->cmd[4]) #define F_FILL (raw_cmd->cmd[5]) #define NR_F 6 /* * Maximum disk size (in kilobytes). * This default is used whenever the current disk size is unknown. * [Now it is rather a minimum] */ #define MAX_DISK_SIZE 4 /* 3984 */ /* * globals used by 'result()' */ #define MAX_REPLIES 16 static unsigned char reply_buffer[MAX_REPLIES]; static int inr; /* size of reply buffer, when called from interrupt */ #define ST0 (reply_buffer[0]) #define ST1 (reply_buffer[1]) #define ST2 (reply_buffer[2]) #define ST3 (reply_buffer[0]) /* result of GETSTATUS */ #define R_TRACK (reply_buffer[3]) #define R_HEAD (reply_buffer[4]) #define R_SECTOR (reply_buffer[5]) #define R_SIZECODE (reply_buffer[6]) #define SEL_DLY (2 * HZ / 100) /* * this struct defines the different floppy drive types. */ static struct { struct floppy_drive_params params; const char *name; /* name printed while booting */ } default_drive_params[] = { /* NOTE: the time values in jiffies should be in msec! CMOS drive type | Maximum data rate supported by drive type | | Head load time, msec | | | Head unload time, msec (not used) | | | | Step rate interval, usec | | | | | Time needed for spinup time (jiffies) | | | | | | Timeout for spinning down (jiffies) | | | | | | | Spindown offset (where disk stops) | | | | | | | | Select delay | | | | | | | | | RPS | | | | | | | | | | Max number of tracks | | | | | | | | | | | Interrupt timeout | | | | | | | | | | | | Max nonintlv. sectors | | | | | | | | | | | | | -Max Errors- flags */ {{0, 500, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 80, 3*HZ, 20, {3,1,2,0,2}, 0, 0, { 7, 4, 8, 2, 1, 5, 3,10}, 3*HZ/2, 0 }, "unknown" }, {{1, 300, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 40, 3*HZ, 17, {3,1,2,0,2}, 0, 0, { 1, 0, 0, 0, 0, 0, 0, 0}, 3*HZ/2, 1 }, "360K PC" }, /*5 1/4 360 KB PC*/ {{2, 500, 16, 16, 6000, 4*HZ/10, 3*HZ, 14, SEL_DLY, 6, 83, 3*HZ, 17, {3,1,2,0,2}, 0, 0, { 2, 5, 6,23,10,20,12, 0}, 3*HZ/2, 2 }, "1.2M" }, /*5 1/4 HD AT*/ {{3, 250, 16, 16, 3000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0, 0, { 4,22,21,30, 3, 0, 0, 0}, 3*HZ/2, 4 }, "720k" }, /*3 1/2 DD*/ {{4, 500, 16, 16, 4000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0, 0, { 7, 4,25,22,31,21,29,11}, 3*HZ/2, 7 }, "1.44M" }, /*3 1/2 HD*/ {{5, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0, 0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M AMI BIOS" }, /*3 1/2 ED*/ {{6, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0, 0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M" } /*3 1/2 ED*/ /* | --autodetected formats--- | | | * read_track | | Name printed when booting * | Native format * Frequency of disk change checks */ }; static struct floppy_drive_params drive_params[N_DRIVE]; static struct floppy_drive_struct drive_state[N_DRIVE]; static struct floppy_write_errors write_errors[N_DRIVE]; static struct timer_list motor_off_timer[N_DRIVE]; static struct gendisk *disks[N_DRIVE]; static struct blk_mq_tag_set tag_sets[N_DRIVE]; static struct block_device *opened_bdev[N_DRIVE]; static DEFINE_MUTEX(open_lock); static struct floppy_raw_cmd *raw_cmd, default_raw_cmd; /* * This struct defines the different floppy types. * * Bit 0 of 'stretch' tells if the tracks need to be doubled for some * types (e.g. 360kB diskette in 1.2MB drive, etc.). Bit 1 of 'stretch' * tells if the disk is in Commodore 1581 format, which means side 0 sectors * are located on side 1 of the disk but with a side 0 ID, and vice-versa. * This is the same as the Sharp MZ-80 5.25" CP/M disk format, except that the * 1581's logical side 0 is on physical side 1, whereas the Sharp's logical * side 0 is on physical side 0 (but with the misnamed sector IDs). * 'stretch' should probably be renamed to something more general, like * 'options'. * * Bits 2 through 9 of 'stretch' tell the number of the first sector. * The LSB (bit 2) is flipped. For most disks, the first sector * is 1 (represented by 0x00<<2). For some CP/M and music sampler * disks (such as Ensoniq EPS 16plus) it is 0 (represented as 0x01<<2). * For Amstrad CPC disks it is 0xC1 (represented as 0xC0<<2). * * Other parameters should be self-explanatory (see also setfdprm(8)). */ /* Size | Sectors per track | | Head | | | Tracks | | | | Stretch | | | | | Gap 1 size | | | | | | Data rate, | 0x40 for perp | | | | | | | Spec1 (stepping rate, head unload | | | | | | | | /fmt gap (gap2) */ static struct floppy_struct floppy_type[32] = { { 0, 0,0, 0,0,0x00,0x00,0x00,0x00,NULL }, /* 0 no testing */ { 720, 9,2,40,0,0x2A,0x02,0xDF,0x50,"d360" }, /* 1 360KB PC */ { 2400,15,2,80,0,0x1B,0x00,0xDF,0x54,"h1200" }, /* 2 1.2MB AT */ { 720, 9,1,80,0,0x2A,0x02,0xDF,0x50,"D360" }, /* 3 360KB SS 3.5" */ { 1440, 9,2,80,0,0x2A,0x02,0xDF,0x50,"D720" }, /* 4 720KB 3.5" */ { 720, 9,2,40,1,0x23,0x01,0xDF,0x50,"h360" }, /* 5 360KB AT */ { 1440, 9,2,80,0,0x23,0x01,0xDF,0x50,"h720" }, /* 6 720KB AT */ { 2880,18,2,80,0,0x1B,0x00,0xCF,0x6C,"H1440" }, /* 7 1.44MB 3.5" */ { 5760,36,2,80,0,0x1B,0x43,0xAF,0x54,"E2880" }, /* 8 2.88MB 3.5" */ { 6240,39,2,80,0,0x1B,0x43,0xAF,0x28,"E3120" }, /* 9 3.12MB 3.5" */ { 2880,18,2,80,0,0x25,0x00,0xDF,0x02,"h1440" }, /* 10 1.44MB 5.25" */ { 3360,21,2,80,0,0x1C,0x00,0xCF,0x0C,"H1680" }, /* 11 1.68MB 3.5" */ { 820,10,2,41,1,0x25,0x01,0xDF,0x2E,"h410" }, /* 12 410KB 5.25" */ { 1640,10,2,82,0,0x25,0x02,0xDF,0x2E,"H820" }, /* 13 820KB 3.5" */ { 2952,18,2,82,0,0x25,0x00,0xDF,0x02,"h1476" }, /* 14 1.48MB 5.25" */ { 3444,21,2,82,0,0x25,0x00,0xDF,0x0C,"H1722" }, /* 15 1.72MB 3.5" */ { 840,10,2,42,1,0x25,0x01,0xDF,0x2E,"h420" }, /* 16 420KB 5.25" */ { 1660,10,2,83,0,0x25,0x02,0xDF,0x2E,"H830" }, /* 17 830KB 3.5" */ { 2988,18,2,83,0,0x25,0x00,0xDF,0x02,"h1494" }, /* 18 1.49MB 5.25" */ { 3486,21,2,83,0,0x25,0x00,0xDF,0x0C,"H1743" }, /* 19 1.74 MB 3.5" */ { 1760,11,2,80,0,0x1C,0x09,0xCF,0x00,"h880" }, /* 20 880KB 5.25" */ { 2080,13,2,80,0,0x1C,0x01,0xCF,0x00,"D1040" }, /* 21 1.04MB 3.5" */ { 2240,14,2,80,0,0x1C,0x19,0xCF,0x00,"D1120" }, /* 22 1.12MB 3.5" */ { 3200,20,2,80,0,0x1C,0x20,0xCF,0x2C,"h1600" }, /* 23 1.6MB 5.25" */ { 3520,22,2,80,0,0x1C,0x08,0xCF,0x2e,"H1760" }, /* 24 1.76MB 3.5" */ { 3840,24,2,80,0,0x1C,0x20,0xCF,0x00,"H1920" }, /* 25 1.92MB 3.5" */ { 6400,40,2,80,0,0x25,0x5B,0xCF,0x00,"E3200" }, /* 26 3.20MB 3.5" */ { 7040,44,2,80,0,0x25,0x5B,0xCF,0x00,"E3520" }, /* 27 3.52MB 3.5" */ { 7680,48,2,80,0,0x25,0x63,0xCF,0x00,"E3840" }, /* 28 3.84MB 3.5" */ { 3680,23,2,80,0,0x1C,0x10,0xCF,0x00,"H1840" }, /* 29 1.84MB 3.5" */ { 1600,10,2,80,0,0x25,0x02,0xDF,0x2E,"D800" }, /* 30 800KB 3.5" */ { 3200,20,2,80,0,0x1C,0x00,0xCF,0x2C,"H1600" }, /* 31 1.6MB 3.5" */ }; #define SECTSIZE (_FD_SECTSIZE(*floppy)) /* Auto-detection: Disk type used until the next media change occurs. */ static struct floppy_struct *current_type[N_DRIVE]; /* * User-provided type information. current_type points to * the respective entry of this array. */ static struct floppy_struct user_params[N_DRIVE]; static sector_t floppy_sizes[256]; static char floppy_device_name[] = "floppy"; /* * The driver is trying to determine the correct media format * while probing is set. rw_interrupt() clears it after a * successful access. */ static int probing; /* Synchronization of FDC access. */ #define FD_COMMAND_NONE -1 #define FD_COMMAND_ERROR 2 #define FD_COMMAND_OKAY 3 static volatile int command_status = FD_COMMAND_NONE; static unsigned long fdc_busy; static DECLARE_WAIT_QUEUE_HEAD(fdc_wait); static DECLARE_WAIT_QUEUE_HEAD(command_done); /* Errors during formatting are counted here. */ static int format_errors; /* Format request descriptor. */ static struct format_descr format_req; /* * Rate is 0 for 500kb/s, 1 for 300kbps, 2 for 250kbps * Spec1 is 0xSH, where S is stepping rate (F=1ms, E=2ms, D=3ms etc), * H is head unload time (1=16ms, 2=32ms, etc) */ /* * Track buffer * Because these are written to by the DMA controller, they must * not contain a 64k byte boundary crossing, or data will be * corrupted/lost. */ static char *floppy_track_buffer; static int max_buffer_sectors; static int *errors; typedef void (*done_f)(int); static const struct cont_t { void (*interrupt)(void); /* this is called after the interrupt of the * main command */ void (*redo)(void); /* this is called to retry the operation */ void (*error)(void); /* this is called to tally an error */ done_f done; /* this is called to say if the operation has * succeeded/failed */ } *cont; static void floppy_ready(void); static void floppy_start(void); static void process_fd_request(void); static void recalibrate_floppy(void); static void floppy_shutdown(struct work_struct *); static int floppy_request_regions(int); static void floppy_release_regions(int); static int floppy_grab_irq_and_dma(void); static void floppy_release_irq_and_dma(void); /* * The "reset" variable should be tested whenever an interrupt is scheduled, * after the commands have been sent. This is to ensure that the driver doesn't * get wedged when the interrupt doesn't come because of a failed command. * reset doesn't need to be tested before sending commands, because * output_byte is automatically disabled when reset is set. */ static void reset_fdc(void); /* * These are global variables, as that's the easiest way to give * information to interrupts. They are the data used for the current * request. */ #define NO_TRACK -1 #define NEED_1_RECAL -2 #define NEED_2_RECAL -3 static atomic_t usage_count = ATOMIC_INIT(0); /* buffer related variables */ static int buffer_track = -1; static int buffer_drive = -1; static int buffer_min = -1; static int buffer_max = -1; /* fdc related variables, should end up in a struct */ static struct floppy_fdc_state fdc_state[N_FDC]; static int fdc; /* current fdc */ static struct workqueue_struct *floppy_wq; static struct floppy_struct *_floppy = floppy_type; static unsigned char current_drive; static long current_count_sectors; static unsigned char fsector_t; /* sector in track */ static unsigned char in_sector_offset; /* offset within physical sector, * expressed in units of 512 bytes */ static inline bool drive_no_geom(int drive) { return !current_type[drive] && !ITYPE(UDRS->fd_device); } #ifndef fd_eject static inline int fd_eject(int drive) { return -EINVAL; } #endif /* * Debugging * ========= */ #ifdef DEBUGT static long unsigned debugtimer; static inline void set_debugt(void) { debugtimer = jiffies; } static inline void debugt(const char *func, const char *msg) { if (DP->flags & DEBUGT) pr_info("%s:%s dtime=%lu\n", func, msg, jiffies - debugtimer); } #else static inline void set_debugt(void) { } static inline void debugt(const char *func, const char *msg) { } #endif /* DEBUGT */ static DECLARE_DELAYED_WORK(fd_timeout, floppy_shutdown); static const char *timeout_message; static void is_alive(const char *func, const char *message) { /* this routine checks whether the floppy driver is "alive" */ if (test_bit(0, &fdc_busy) && command_status < 2 && !delayed_work_pending(&fd_timeout)) { DPRINT("%s: timeout handler died. %s\n", func, message); } } static void (*do_floppy)(void) = NULL; #define OLOGSIZE 20 static void (*lasthandler)(void); static unsigned long interruptjiffies; static unsigned long resultjiffies; static int resultsize; static unsigned long lastredo; static struct output_log { unsigned char data; unsigned char status; unsigned long jiffies; } output_log[OLOGSIZE]; static int output_log_pos; #define current_reqD -1 #define MAXTIMEOUT -2 static void __reschedule_timeout(int drive, const char *message) { unsigned long delay; if (drive == current_reqD) drive = current_drive; if (drive < 0 || drive >= N_DRIVE) { delay = 20UL * HZ; drive = 0; } else delay = UDP->timeout; mod_delayed_work(floppy_wq, &fd_timeout, delay); if (UDP->flags & FD_DEBUG) DPRINT("reschedule timeout %s\n", message); timeout_message = message; } static void reschedule_timeout(int drive, const char *message) { unsigned long flags; spin_lock_irqsave(&floppy_lock, flags); __reschedule_timeout(drive, message); spin_unlock_irqrestore(&floppy_lock, flags); } #define INFBOUND(a, b) (a) = max_t(int, a, b) #define SUPBOUND(a, b) (a) = min_t(int, a, b) /* * Bottom half floppy driver. * ========================== * * This part of the file contains the code talking directly to the hardware, * and also the main service loop (seek-configure-spinup-command) */ /* * disk change. * This routine is responsible for maintaining the FD_DISK_CHANGE flag, * and the last_checked date. * * last_checked is the date of the last check which showed 'no disk change' * FD_DISK_CHANGE is set under two conditions: * 1. The floppy has been changed after some i/o to that floppy already * took place. * 2. No floppy disk is in the drive. This is done in order to ensure that * requests are quickly flushed in case there is no disk in the drive. It * follows that FD_DISK_CHANGE can only be cleared if there is a disk in * the drive. * * For 1., maxblock is observed. Maxblock is 0 if no i/o has taken place yet. * For 2., FD_DISK_NEWCHANGE is watched. FD_DISK_NEWCHANGE is cleared on * each seek. If a disk is present, the disk change line should also be * cleared on each seek. Thus, if FD_DISK_NEWCHANGE is clear, but the disk * change line is set, this means either that no disk is in the drive, or * that it has been removed since the last seek. * * This means that we really have a third possibility too: * The floppy has been changed after the last seek. */ static int disk_change(int drive) { int fdc = FDC(drive); if (time_before(jiffies, UDRS->select_date + UDP->select_delay)) DPRINT("WARNING disk change called early\n"); if (!(FDCS->dor & (0x10 << UNIT(drive))) || (FDCS->dor & 3) != UNIT(drive) || fdc != FDC(drive)) { DPRINT("probing disk change on unselected drive\n"); DPRINT("drive=%d fdc=%d dor=%x\n", drive, FDC(drive), (unsigned int)FDCS->dor); } debug_dcl(UDP->flags, "checking disk change line for drive %d\n", drive); debug_dcl(UDP->flags, "jiffies=%lu\n", jiffies); debug_dcl(UDP->flags, "disk change line=%x\n", fd_inb(FD_DIR) & 0x80); debug_dcl(UDP->flags, "flags=%lx\n", UDRS->flags); if (UDP->flags & FD_BROKEN_DCL) return test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); if ((fd_inb(FD_DIR) ^ UDP->flags) & 0x80) { set_bit(FD_VERIFY_BIT, &UDRS->flags); /* verify write protection */ if (UDRS->maxblock) /* mark it changed */ set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); /* invalidate its geometry */ if (UDRS->keep_data >= 0) { if ((UDP->flags & FTD_MSG) && current_type[drive] != NULL) DPRINT("Disk type is undefined after disk change\n"); current_type[drive] = NULL; floppy_sizes[TOMINOR(drive)] = MAX_DISK_SIZE << 1; } return 1; } else { UDRS->last_checked = jiffies; clear_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags); } return 0; } static inline int is_selected(int dor, int unit) { return ((dor & (0x10 << unit)) && (dor & 3) == unit); } static bool is_ready_state(int status) { int state = status & (STATUS_READY | STATUS_DIR | STATUS_DMA); return state == STATUS_READY; } static int set_dor(int fdc, char mask, char data) { unsigned char unit; unsigned char drive; unsigned char newdor; unsigned char olddor; if (FDCS->address == -1) return -1; olddor = FDCS->dor; newdor = (olddor & mask) | data; if (newdor != olddor) { unit = olddor & 0x3; if (is_selected(olddor, unit) && !is_selected(newdor, unit)) { drive = REVDRIVE(fdc, unit); debug_dcl(UDP->flags, "calling disk change from set_dor\n"); disk_change(drive); } FDCS->dor = newdor; fd_outb(newdor, FD_DOR); unit = newdor & 0x3; if (!is_selected(olddor, unit) && is_selected(newdor, unit)) { drive = REVDRIVE(fdc, unit); UDRS->select_date = jiffies; } } return olddor; } static void twaddle(void) { if (DP->select_delay) return; fd_outb(FDCS->dor & ~(0x10 << UNIT(current_drive)), FD_DOR); fd_outb(FDCS->dor, FD_DOR); DRS->select_date = jiffies; } /* * Reset all driver information about the current fdc. * This is needed after a reset, and after a raw command. */ static void reset_fdc_info(int mode) { int drive; FDCS->spec1 = FDCS->spec2 = -1; FDCS->need_configure = 1; FDCS->perp_mode = 1; FDCS->rawcmd = 0; for (drive = 0; drive < N_DRIVE; drive++) if (FDC(drive) == fdc && (mode || UDRS->track != NEED_1_RECAL)) UDRS->track = NEED_2_RECAL; } /* selects the fdc and drive, and enables the fdc's input/dma. */ static void set_fdc(int drive) { if (drive >= 0 && drive < N_DRIVE) { fdc = FDC(drive); current_drive = drive; } if (fdc != 1 && fdc != 0) { pr_info("bad fdc value\n"); return; } set_dor(fdc, ~0, 8); #if N_FDC > 1 set_dor(1 - fdc, ~8, 0); #endif if (FDCS->rawcmd == 2) reset_fdc_info(1); if (fd_inb(FD_STATUS) != STATUS_READY) FDCS->reset = 1; } /* locks the driver */ static int lock_fdc(int drive) { if (WARN(atomic_read(&usage_count) == 0, "Trying to lock fdc while usage count=0\n")) return -1; if (wait_event_interruptible(fdc_wait, !test_and_set_bit(0, &fdc_busy))) return -EINTR; command_status = FD_COMMAND_NONE; reschedule_timeout(drive, "lock fdc"); set_fdc(drive); return 0; } /* unlocks the driver */ static void unlock_fdc(void) { if (!test_bit(0, &fdc_busy)) DPRINT("FDC access conflict!\n"); raw_cmd = NULL; command_status = FD_COMMAND_NONE; cancel_delayed_work(&fd_timeout); do_floppy = NULL; cont = NULL; clear_bit(0, &fdc_busy); wake_up(&fdc_wait); } /* switches the motor off after a given timeout */ static void motor_off_callback(struct timer_list *t) { unsigned long nr = t - motor_off_timer; unsigned char mask = ~(0x10 << UNIT(nr)); if (WARN_ON_ONCE(nr >= N_DRIVE)) return; set_dor(FDC(nr), mask, 0); } /* schedules motor off */ static void floppy_off(unsigned int drive) { unsigned long volatile delta; int fdc = FDC(drive); if (!(FDCS->dor & (0x10 << UNIT(drive)))) return; del_timer(motor_off_timer + drive); /* make spindle stop in a position which minimizes spinup time * next time */ if (UDP->rps) { delta = jiffies - UDRS->first_read_date + HZ - UDP->spindown_offset; delta = ((delta * UDP->rps) % HZ) / UDP->rps; motor_off_timer[drive].expires = jiffies + UDP->spindown - delta; } add_timer(motor_off_timer + drive); } /* * cycle through all N_DRIVE floppy drives, for disk change testing. * stopping at current drive. This is done before any long operation, to * be sure to have up to date disk change information. */ static void scandrives(void) { int i; int drive; int saved_drive; if (DP->select_delay) return; saved_drive = current_drive; for (i = 0; i < N_DRIVE; i++) { drive = (saved_drive + i + 1) % N_DRIVE; if (UDRS->fd_ref == 0 || UDP->select_delay != 0) continue; /* skip closed drives */ set_fdc(drive); if (!(set_dor(fdc, ~3, UNIT(drive) | (0x10 << UNIT(drive))) & (0x10 << UNIT(drive)))) /* switch the motor off again, if it was off to * begin with */ set_dor(fdc, ~(0x10 << UNIT(drive)), 0); } set_fdc(saved_drive); } static void empty(void) { } static void (*floppy_work_fn)(void); static void floppy_work_workfn(struct work_struct *work) { floppy_work_fn(); } static DECLARE_WORK(floppy_work, floppy_work_workfn); static void schedule_bh(void (*handler)(void)) { WARN_ON(work_pending(&floppy_work)); floppy_work_fn = handler; queue_work(floppy_wq, &floppy_work); } static void (*fd_timer_fn)(void) = NULL; static void fd_timer_workfn(struct work_struct *work) { fd_timer_fn(); } static DECLARE_DELAYED_WORK(fd_timer, fd_timer_workfn); static void cancel_activity(void) { do_floppy = NULL; cancel_delayed_work_sync(&fd_timer); cancel_work_sync(&floppy_work); } /* this function makes sure that the disk stays in the drive during the * transfer */ static void fd_watchdog(void) { debug_dcl(DP->flags, "calling disk change from watchdog\n"); if (disk_change(current_drive)) { DPRINT("disk removed during i/o\n"); cancel_activity(); cont->done(0); reset_fdc(); } else { cancel_delayed_work(&fd_timer); fd_timer_fn = fd_watchdog; queue_delayed_work(floppy_wq, &fd_timer, HZ / 10); } } static void main_command_interrupt(void) { cancel_delayed_work(&fd_timer); cont->interrupt(); } /* waits for a delay (spinup or select) to pass */ static int fd_wait_for_completion(unsigned long expires, void (*function)(void)) { if (FDCS->reset) { reset_fdc(); /* do the reset during sleep to win time * if we don't need to sleep, it's a good * occasion anyways */ return 1; } if (time_before(jiffies, expires)) { cancel_delayed_work(&fd_timer); fd_timer_fn = function; queue_delayed_work(floppy_wq, &fd_timer, expires - jiffies); return 1; } return 0; } static void setup_DMA(void) { unsigned long f; if (raw_cmd->length == 0) { int i; pr_info("zero dma transfer size:"); for (i = 0; i < raw_cmd->cmd_count; i++) pr_cont("%x,", raw_cmd->cmd[i]); pr_cont("\n"); cont->done(0); FDCS->reset = 1; return; } if (((unsigned long)raw_cmd->kernel_data) % 512) { pr_info("non aligned address: %p\n", raw_cmd->kernel_data); cont->done(0); FDCS->reset = 1; return; } f = claim_dma_lock(); fd_disable_dma(); #ifdef fd_dma_setup if (fd_dma_setup(raw_cmd->kernel_data, raw_cmd->length, (raw_cmd->flags & FD_RAW_READ) ? DMA_MODE_READ : DMA_MODE_WRITE, FDCS->address) < 0) { release_dma_lock(f); cont->done(0); FDCS->reset = 1; return; } release_dma_lock(f); #else fd_clear_dma_ff(); fd_cacheflush(raw_cmd->kernel_data, raw_cmd->length); fd_set_dma_mode((raw_cmd->flags & FD_RAW_READ) ? DMA_MODE_READ : DMA_MODE_WRITE); fd_set_dma_addr(raw_cmd->kernel_data); fd_set_dma_count(raw_cmd->length); virtual_dma_port = FDCS->address; fd_enable_dma(); release_dma_lock(f); #endif } static void show_floppy(void); /* waits until the fdc becomes ready */ static int wait_til_ready(void) { int status; int counter; if (FDCS->reset) return -1; for (counter = 0; counter < 10000; counter++) { status = fd_inb(FD_STATUS); if (status & STATUS_READY) return status; } if (initialized) { DPRINT("Getstatus times out (%x) on fdc %d\n", status, fdc); show_floppy(); } FDCS->reset = 1; return -1; } /* sends a command byte to the fdc */ static int output_byte(char byte) { int status = wait_til_ready(); if (status < 0) return -1; if (is_ready_state(status)) { fd_outb(byte, FD_DATA); output_log[output_log_pos].data = byte; output_log[output_log_pos].status = status; output_log[output_log_pos].jiffies = jiffies; output_log_pos = (output_log_pos + 1) % OLOGSIZE; return 0; } FDCS->reset = 1; if (initialized) { DPRINT("Unable to send byte %x to FDC. Fdc=%x Status=%x\n", byte, fdc, status); show_floppy(); } return -1; } /* gets the response from the fdc */ static int result(void) { int i; int status = 0; for (i = 0; i < MAX_REPLIES; i++) { status = wait_til_ready(); if (status < 0) break; status &= STATUS_DIR | STATUS_READY | STATUS_BUSY | STATUS_DMA; if ((status & ~STATUS_BUSY) == STATUS_READY) { resultjiffies = jiffies; resultsize = i; return i; } if (status == (STATUS_DIR | STATUS_READY | STATUS_BUSY)) reply_buffer[i] = fd_inb(FD_DATA); else break; } if (initialized) { DPRINT("get result error. Fdc=%d Last status=%x Read bytes=%d\n", fdc, status, i); show_floppy(); } FDCS->reset = 1; return -1; } #define MORE_OUTPUT -2 /* does the fdc need more output? */ static int need_more_output(void) { int status = wait_til_ready(); if (status < 0) return -1; if (is_ready_state(status)) return MORE_OUTPUT; return result(); } /* Set perpendicular mode as required, based on data rate, if supported. * 82077 Now tested. 1Mbps data rate only possible with 82077-1. */ static void perpendicular_mode(void) { unsigned char perp_mode; if (raw_cmd->rate & 0x40) { switch (raw_cmd->rate & 3) { case 0: perp_mode = 2; break; case 3: perp_mode = 3; break; default: DPRINT("Invalid data rate for perpendicular mode!\n"); cont->done(0); FDCS->reset = 1; /* * convenient way to return to * redo without too much hassle * (deep stack et al.) */ return; } } else perp_mode = 0; if (FDCS->perp_mode == perp_mode) return; if (FDCS->version >= FDC_82077_ORIG) { output_byte(FD_PERPENDICULAR); output_byte(perp_mode); FDCS->perp_mode = perp_mode; } else if (perp_mode) { DPRINT("perpendicular mode not supported by this FDC.\n"); } } /* perpendicular_mode */ static int fifo_depth = 0xa; static int no_fifo; static int fdc_configure(void) { /* Turn on FIFO */ output_byte(FD_CONFIGURE); if (need_more_output() != MORE_OUTPUT) return 0; output_byte(0); output_byte(0x10 | (no_fifo & 0x20) | (fifo_depth & 0xf)); output_byte(0); /* pre-compensation from track 0 upwards */ return 1; } #define NOMINAL_DTR 500 /* Issue a "SPECIFY" command to set the step rate time, head unload time, * head load time, and DMA disable flag to values needed by floppy. * * The value "dtr" is the data transfer rate in Kbps. It is needed * to account for the data rate-based scaling done by the 82072 and 82077 * FDC types. This parameter is ignored for other types of FDCs (i.e. * 8272a). * * Note that changing the data transfer rate has a (probably deleterious) * effect on the parameters subject to scaling for 82072/82077 FDCs, so * fdc_specify is called again after each data transfer rate * change. * * srt: 1000 to 16000 in microseconds * hut: 16 to 240 milliseconds * hlt: 2 to 254 milliseconds * * These values are rounded up to the next highest available delay time. */ static void fdc_specify(void) { unsigned char spec1; unsigned char spec2; unsigned long srt; unsigned long hlt; unsigned long hut; unsigned long dtr = NOMINAL_DTR; unsigned long scale_dtr = NOMINAL_DTR; int hlt_max_code = 0x7f; int hut_max_code = 0xf; if (FDCS->need_configure && FDCS->version >= FDC_82072A) { fdc_configure(); FDCS->need_configure = 0; } switch (raw_cmd->rate & 0x03) { case 3: dtr = 1000; break; case 1: dtr = 300; if (FDCS->version >= FDC_82078) { /* chose the default rate table, not the one * where 1 = 2 Mbps */ output_byte(FD_DRIVESPEC); if (need_more_output() == MORE_OUTPUT) { output_byte(UNIT(current_drive)); output_byte(0xc0); } } break; case 2: dtr = 250; break; } if (FDCS->version >= FDC_82072) { scale_dtr = dtr; hlt_max_code = 0x00; /* 0==256msec*dtr0/dtr (not linear!) */ hut_max_code = 0x0; /* 0==256msec*dtr0/dtr (not linear!) */ } /* Convert step rate from microseconds to milliseconds and 4 bits */ srt = 16 - DIV_ROUND_UP(DP->srt * scale_dtr / 1000, NOMINAL_DTR); if (slow_floppy) srt = srt / 4; SUPBOUND(srt, 0xf); INFBOUND(srt, 0); hlt = DIV_ROUND_UP(DP->hlt * scale_dtr / 2, NOMINAL_DTR); if (hlt < 0x01) hlt = 0x01; else if (hlt > 0x7f) hlt = hlt_max_code; hut = DIV_ROUND_UP(DP->hut * scale_dtr / 16, NOMINAL_DTR); if (hut < 0x1) hut = 0x1; else if (hut > 0xf) hut = hut_max_code; spec1 = (srt << 4) | hut; spec2 = (hlt << 1) | (use_virtual_dma & 1); /* If these parameters did not change, just return with success */ if (FDCS->spec1 != spec1 || FDCS->spec2 != spec2) { /* Go ahead and set spec1 and spec2 */ output_byte(FD_SPECIFY); output_byte(FDCS->spec1 = spec1); output_byte(FDCS->spec2 = spec2); } } /* fdc_specify */ /* Set the FDC's data transfer rate on behalf of the specified drive. * NOTE: with 82072/82077 FDCs, changing the data rate requires a reissue * of the specify command (i.e. using the fdc_specify function). */ static int fdc_dtr(void) { /* If data rate not already set to desired value, set it. */ if ((raw_cmd->rate & 3) == FDCS->dtr) return 0; /* Set dtr */ fd_outb(raw_cmd->rate & 3, FD_DCR); /* TODO: some FDC/drive combinations (C&T 82C711 with TEAC 1.2MB) * need a stabilization period of several milliseconds to be * enforced after data rate changes before R/W operations. * Pause 5 msec to avoid trouble. (Needs to be 2 jiffies) */ FDCS->dtr = raw_cmd->rate & 3; return fd_wait_for_completion(jiffies + 2UL * HZ / 100, floppy_ready); } /* fdc_dtr */ static void tell_sector(void) { pr_cont(": track %d, head %d, sector %d, size %d", R_TRACK, R_HEAD, R_SECTOR, R_SIZECODE); } /* tell_sector */ static void print_errors(void) { DPRINT(""); if (ST0 & ST0_ECE) { pr_cont("Recalibrate failed!"); } else if (ST2 & ST2_CRC) { pr_cont("data CRC error"); tell_sector(); } else if (ST1 & ST1_CRC) { pr_cont("CRC error"); tell_sector(); } else if ((ST1 & (ST1_MAM | ST1_ND)) || (ST2 & ST2_MAM)) { if (!probing) { pr_cont("sector not found"); tell_sector(); } else pr_cont("probe failed..."); } else if (ST2 & ST2_WC) { /* seek error */ pr_cont("wrong cylinder"); } else if (ST2 & ST2_BC) { /* cylinder marked as bad */ pr_cont("bad cylinder"); } else { pr_cont("unknown error. ST[0..2] are: 0x%x 0x%x 0x%x", ST0, ST1, ST2); tell_sector(); } pr_cont("\n"); } /* * OK, this error interpreting routine is called after a * DMA read/write has succeeded * or failed, so we check the results, and copy any buffers. * hhb: Added better error reporting. * ak: Made this into a separate routine. */ static int interpret_errors(void) { char bad; if (inr != 7) { DPRINT("-- FDC reply error\n"); FDCS->reset = 1; return 1; } /* check IC to find cause of interrupt */ switch (ST0 & ST0_INTR) { case 0x40: /* error occurred during command execution */ if (ST1 & ST1_EOC) return 0; /* occurs with pseudo-DMA */ bad = 1; if (ST1 & ST1_WP) { DPRINT("Drive is write protected\n"); clear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags); cont->done(0); bad = 2; } else if (ST1 & ST1_ND) { set_bit(FD_NEED_TWADDLE_BIT, &DRS->flags); } else if (ST1 & ST1_OR) { if (DP->flags & FTD_MSG) DPRINT("Over/Underrun - retrying\n"); bad = 0; } else if (*errors >= DP->max_errors.reporting) { print_errors(); } if (ST2 & ST2_WC || ST2 & ST2_BC) /* wrong cylinder => recal */ DRS->track = NEED_2_RECAL; return bad; case 0x80: /* invalid command given */ DPRINT("Invalid FDC command given!\n"); cont->done(0); return 2; case 0xc0: DPRINT("Abnormal termination caused by polling\n"); cont->error(); return 2; default: /* (0) Normal command termination */ return 0; } } /* * This routine is called when everything should be correctly set up * for the transfer (i.e. floppy motor is on, the correct floppy is * selected, and the head is sitting on the right track). */ static void setup_rw_floppy(void) { int i; int r; int flags; unsigned long ready_date; void (*function)(void); flags = raw_cmd->flags; if (flags & (FD_RAW_READ | FD_RAW_WRITE)) flags |= FD_RAW_INTR; if ((flags & FD_RAW_SPIN) && !(flags & FD_RAW_NO_MOTOR)) { ready_date = DRS->spinup_date + DP->spinup; /* If spinup will take a long time, rerun scandrives * again just before spinup completion. Beware that * after scandrives, we must again wait for selection. */ if (time_after(ready_date, jiffies + DP->select_delay)) { ready_date -= DP->select_delay; function = floppy_start; } else function = setup_rw_floppy; /* wait until the floppy is spinning fast enough */ if (fd_wait_for_completion(ready_date, function)) return; } if ((flags & FD_RAW_READ) || (flags & FD_RAW_WRITE)) setup_DMA(); if (flags & FD_RAW_INTR) do_floppy = main_command_interrupt; r = 0; for (i = 0; i < raw_cmd->cmd_count; i++) r |= output_byte(raw_cmd->cmd[i]); debugt(__func__, "rw_command"); if (r) { cont->error(); reset_fdc(); return; } if (!(flags & FD_RAW_INTR)) { inr = result(); cont->interrupt(); } else if (flags & FD_RAW_NEED_DISK) fd_watchdog(); } static int blind_seek; /* * This is the routine called after every seek (or recalibrate) interrupt * from the floppy controller. */ static void seek_interrupt(void) { debugt(__func__, ""); if (inr != 2 || (ST0 & 0xF8) != 0x20) { DPRINT("seek failed\n"); DRS->track = NEED_2_RECAL; cont->error(); cont->redo(); return; } if (DRS->track >= 0 && DRS->track != ST1 && !blind_seek) { debug_dcl(DP->flags, "clearing NEWCHANGE flag because of effective seek\n"); debug_dcl(DP->flags, "jiffies=%lu\n", jiffies); clear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); /* effective seek */ DRS->select_date = jiffies; } DRS->track = ST1; floppy_ready(); } static void check_wp(void) { if (test_bit(FD_VERIFY_BIT, &DRS->flags)) { /* check write protection */ output_byte(FD_GETSTATUS); output_byte(UNIT(current_drive)); if (result() != 1) { FDCS->reset = 1; return; } clear_bit(FD_VERIFY_BIT, &DRS->flags); clear_bit(FD_NEED_TWADDLE_BIT, &DRS->flags); debug_dcl(DP->flags, "checking whether disk is write protected\n"); debug_dcl(DP->flags, "wp=%x\n", ST3 & 0x40); if (!(ST3 & 0x40)) set_bit(FD_DISK_WRITABLE_BIT, &DRS->flags); else clear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags); } } static void seek_floppy(void) { int track; blind_seek = 0; debug_dcl(DP->flags, "calling disk change from %s\n", __func__); if (!test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) && disk_change(current_drive) && (raw_cmd->flags & FD_RAW_NEED_DISK)) { /* the media changed flag should be cleared after the seek. * If it isn't, this means that there is really no disk in * the drive. */ set_bit(FD_DISK_CHANGED_BIT, &DRS->flags); cont->done(0); cont->redo(); return; } if (DRS->track <= NEED_1_RECAL) { recalibrate_floppy(); return; } else if (test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) && (raw_cmd->flags & FD_RAW_NEED_DISK) && (DRS->track <= NO_TRACK || DRS->track == raw_cmd->track)) { /* we seek to clear the media-changed condition. Does anybody * know a more elegant way, which works on all drives? */ if (raw_cmd->track) track = raw_cmd->track - 1; else { if (DP->flags & FD_SILENT_DCL_CLEAR) { set_dor(fdc, ~(0x10 << UNIT(current_drive)), 0); blind_seek = 1; raw_cmd->flags |= FD_RAW_NEED_SEEK; } track = 1; } } else { check_wp(); if (raw_cmd->track != DRS->track && (raw_cmd->flags & FD_RAW_NEED_SEEK)) track = raw_cmd->track; else { setup_rw_floppy(); return; } } do_floppy = seek_interrupt; output_byte(FD_SEEK); output_byte(UNIT(current_drive)); if (output_byte(track) < 0) { reset_fdc(); return; } debugt(__func__, ""); } static void recal_interrupt(void) { debugt(__func__, ""); if (inr != 2) FDCS->reset = 1; else if (ST0 & ST0_ECE) { switch (DRS->track) { case NEED_1_RECAL: debugt(__func__, "need 1 recal"); /* after a second recalibrate, we still haven't * reached track 0. Probably no drive. Raise an * error, as failing immediately might upset * computers possessed by the Devil :-) */ cont->error(); cont->redo(); return; case NEED_2_RECAL: debugt(__func__, "need 2 recal"); /* If we already did a recalibrate, * and we are not at track 0, this * means we have moved. (The only way * not to move at recalibration is to * be already at track 0.) Clear the * new change flag */ debug_dcl(DP->flags, "clearing NEWCHANGE flag because of second recalibrate\n"); clear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); DRS->select_date = jiffies; /* fall through */ default: debugt(__func__, "default"); /* Recalibrate moves the head by at * most 80 steps. If after one * recalibrate we don't have reached * track 0, this might mean that we * started beyond track 80. Try * again. */ DRS->track = NEED_1_RECAL; break; } } else DRS->track = ST1; floppy_ready(); } static void print_result(char *message, int inr) { int i; DPRINT("%s ", message); if (inr >= 0) for (i = 0; i < inr; i++) pr_cont("repl[%d]=%x ", i, reply_buffer[i]); pr_cont("\n"); } /* interrupt handler. Note that this can be called externally on the Sparc */ irqreturn_t floppy_interrupt(int irq, void *dev_id) { int do_print; unsigned long f; void (*handler)(void) = do_floppy; lasthandler = handler; interruptjiffies = jiffies; f = claim_dma_lock(); fd_disable_dma(); release_dma_lock(f); do_floppy = NULL; if (fdc >= N_FDC || FDCS->address == -1) { /* we don't even know which FDC is the culprit */ pr_info("DOR0=%x\n", fdc_state[0].dor); pr_info("floppy interrupt on bizarre fdc %d\n", fdc); pr_info("handler=%ps\n", handler); is_alive(__func__, "bizarre fdc"); return IRQ_NONE; } FDCS->reset = 0; /* We have to clear the reset flag here, because apparently on boxes * with level triggered interrupts (PS/2, Sparc, ...), it is needed to * emit SENSEI's to clear the interrupt line. And FDCS->reset blocks the * emission of the SENSEI's. * It is OK to emit floppy commands because we are in an interrupt * handler here, and thus we have to fear no interference of other * activity. */ do_print = !handler && print_unex && initialized; inr = result(); if (do_print) print_result("unexpected interrupt", inr); if (inr == 0) { int max_sensei = 4; do { output_byte(FD_SENSEI); inr = result(); if (do_print) print_result("sensei", inr); max_sensei--; } while ((ST0 & 0x83) != UNIT(current_drive) && inr == 2 && max_sensei); } if (!handler) { FDCS->reset = 1; return IRQ_NONE; } schedule_bh(handler); is_alive(__func__, "normal interrupt end"); /* FIXME! Was it really for us? */ return IRQ_HANDLED; } static void recalibrate_floppy(void) { debugt(__func__, ""); do_floppy = recal_interrupt; output_byte(FD_RECALIBRATE); if (output_byte(UNIT(current_drive)) < 0) reset_fdc(); } /* * Must do 4 FD_SENSEIs after reset because of ``drive polling''. */ static void reset_interrupt(void) { debugt(__func__, ""); result(); /* get the status ready for set_fdc */ if (FDCS->reset) { pr_info("reset set in interrupt, calling %ps\n", cont->error); cont->error(); /* a reset just after a reset. BAD! */ } cont->redo(); } /* * reset is done by pulling bit 2 of DOR low for a while (old FDCs), * or by setting the self clearing bit 7 of STATUS (newer FDCs) */ static void reset_fdc(void) { unsigned long flags; do_floppy = reset_interrupt; FDCS->reset = 0; reset_fdc_info(0); /* Pseudo-DMA may intercept 'reset finished' interrupt. */ /* Irrelevant for systems with true DMA (i386). */ flags = claim_dma_lock(); fd_disable_dma(); release_dma_lock(flags); if (FDCS->version >= FDC_82072A) fd_outb(0x80 | (FDCS->dtr & 3), FD_STATUS); else { fd_outb(FDCS->dor & ~0x04, FD_DOR); udelay(FD_RESET_DELAY); fd_outb(FDCS->dor, FD_DOR); } } static void show_floppy(void) { int i; pr_info("\n"); pr_info("floppy driver state\n"); pr_info("-------------------\n"); pr_info("now=%lu last interrupt=%lu diff=%lu last called handler=%ps\n", jiffies, interruptjiffies, jiffies - interruptjiffies, lasthandler); pr_info("timeout_message=%s\n", timeout_message); pr_info("last output bytes:\n"); for (i = 0; i < OLOGSIZE; i++) pr_info("%2x %2x %lu\n", output_log[(i + output_log_pos) % OLOGSIZE].data, output_log[(i + output_log_pos) % OLOGSIZE].status, output_log[(i + output_log_pos) % OLOGSIZE].jiffies); pr_info("last result at %lu\n", resultjiffies); pr_info("last redo_fd_request at %lu\n", lastredo); print_hex_dump(KERN_INFO, "", DUMP_PREFIX_NONE, 16, 1, reply_buffer, resultsize, true); pr_info("status=%x\n", fd_inb(FD_STATUS)); pr_info("fdc_busy=%lu\n", fdc_busy); if (do_floppy) pr_info("do_floppy=%ps\n", do_floppy); if (work_pending(&floppy_work)) pr_info("floppy_work.func=%ps\n", floppy_work.func); if (delayed_work_pending(&fd_timer)) pr_info("delayed work.function=%p expires=%ld\n", fd_timer.work.func, fd_timer.timer.expires - jiffies); if (delayed_work_pending(&fd_timeout)) pr_info("timer_function=%p expires=%ld\n", fd_timeout.work.func, fd_timeout.timer.expires - jiffies); pr_info("cont=%p\n", cont); pr_info("current_req=%p\n", current_req); pr_info("command_status=%d\n", command_status); pr_info("\n"); } static void floppy_shutdown(struct work_struct *arg) { unsigned long flags; if (initialized) show_floppy(); cancel_activity(); flags = claim_dma_lock(); fd_disable_dma(); release_dma_lock(flags); /* avoid dma going to a random drive after shutdown */ if (initialized) DPRINT("floppy timeout called\n"); FDCS->reset = 1; if (cont) { cont->done(0); cont->redo(); /* this will recall reset when needed */ } else { pr_info("no cont in shutdown!\n"); process_fd_request(); } is_alive(__func__, ""); } /* start motor, check media-changed condition and write protection */ static int start_motor(void (*function)(void)) { int mask; int data; mask = 0xfc; data = UNIT(current_drive); if (!(raw_cmd->flags & FD_RAW_NO_MOTOR)) { if (!(FDCS->dor & (0x10 << UNIT(current_drive)))) { set_debugt(); /* no read since this drive is running */ DRS->first_read_date = 0; /* note motor start time if motor is not yet running */ DRS->spinup_date = jiffies; data |= (0x10 << UNIT(current_drive)); } } else if (FDCS->dor & (0x10 << UNIT(current_drive))) mask &= ~(0x10 << UNIT(current_drive)); /* starts motor and selects floppy */ del_timer(motor_off_timer + current_drive); set_dor(fdc, mask, data); /* wait_for_completion also schedules reset if needed. */ return fd_wait_for_completion(DRS->select_date + DP->select_delay, function); } static void floppy_ready(void) { if (FDCS->reset) { reset_fdc(); return; } if (start_motor(floppy_ready)) return; if (fdc_dtr()) return; debug_dcl(DP->flags, "calling disk change from floppy_ready\n"); if (!(raw_cmd->flags & FD_RAW_NO_MOTOR) && disk_change(current_drive) && !DP->select_delay) twaddle(); /* this clears the dcl on certain * drive/controller combinations */ #ifdef fd_chose_dma_mode if ((raw_cmd->flags & FD_RAW_READ) || (raw_cmd->flags & FD_RAW_WRITE)) { unsigned long flags = claim_dma_lock(); fd_chose_dma_mode(raw_cmd->kernel_data, raw_cmd->length); release_dma_lock(flags); } #endif if (raw_cmd->flags & (FD_RAW_NEED_SEEK | FD_RAW_NEED_DISK)) { perpendicular_mode(); fdc_specify(); /* must be done here because of hut, hlt ... */ seek_floppy(); } else { if ((raw_cmd->flags & FD_RAW_READ) || (raw_cmd->flags & FD_RAW_WRITE)) fdc_specify(); setup_rw_floppy(); } } static void floppy_start(void) { reschedule_timeout(current_reqD, "floppy start"); scandrives(); debug_dcl(DP->flags, "setting NEWCHANGE in floppy_start\n"); set_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); floppy_ready(); } /* * ======================================================================== * here ends the bottom half. Exported routines are: * floppy_start, floppy_off, floppy_ready, lock_fdc, unlock_fdc, set_fdc, * start_motor, reset_fdc, reset_fdc_info, interpret_errors. * Initialization also uses output_byte, result, set_dor, floppy_interrupt * and set_dor. * ======================================================================== */ /* * General purpose continuations. * ============================== */ static void do_wakeup(void) { reschedule_timeout(MAXTIMEOUT, "do wakeup"); cont = NULL; command_status += 2; wake_up(&command_done); } static const struct cont_t wakeup_cont = { .interrupt = empty, .redo = do_wakeup, .error = empty, .done = (done_f)empty }; static const struct cont_t intr_cont = { .interrupt = empty, .redo = process_fd_request, .error = empty, .done = (done_f)empty }; static int wait_til_done(void (*handler)(void), bool interruptible) { int ret; schedule_bh(handler); if (interruptible) wait_event_interruptible(command_done, command_status >= 2); else wait_event(command_done, command_status >= 2); if (command_status < 2) { cancel_activity(); cont = &intr_cont; reset_fdc(); return -EINTR; } if (FDCS->reset) command_status = FD_COMMAND_ERROR; if (command_status == FD_COMMAND_OKAY) ret = 0; else ret = -EIO; command_status = FD_COMMAND_NONE; return ret; } static void generic_done(int result) { command_status = result; cont = &wakeup_cont; } static void generic_success(void) { cont->done(1); } static void generic_failure(void) { cont->done(0); } static void success_and_wakeup(void) { generic_success(); cont->redo(); } /* * formatting and rw support. * ========================== */ static int next_valid_format(void) { int probed_format; probed_format = DRS->probed_format; while (1) { if (probed_format >= 8 || !DP->autodetect[probed_format]) { DRS->probed_format = 0; return 1; } if (floppy_type[DP->autodetect[probed_format]].sect) { DRS->probed_format = probed_format; return 0; } probed_format++; } } static void bad_flp_intr(void) { int err_count; if (probing) { DRS->probed_format++; if (!next_valid_format()) return; } err_count = ++(*errors); INFBOUND(DRWE->badness, err_count); if (err_count > DP->max_errors.abort) cont->done(0); if (err_count > DP->max_errors.reset) FDCS->reset = 1; else if (err_count > DP->max_errors.recal) DRS->track = NEED_2_RECAL; } static void set_floppy(int drive) { int type = ITYPE(UDRS->fd_device); if (type) _floppy = floppy_type + type; else _floppy = current_type[drive]; } /* * formatting support. * =================== */ static void format_interrupt(void) { switch (interpret_errors()) { case 1: cont->error(); case 2: break; case 0: cont->done(1); } cont->redo(); } #define FM_MODE(x, y) ((y) & ~(((x)->rate & 0x80) >> 1)) #define CT(x) ((x) | 0xc0) static void setup_format_params(int track) { int n; int il; int count; int head_shift; int track_shift; struct fparm { unsigned char track, head, sect, size; } *here = (struct fparm *)floppy_track_buffer; raw_cmd = &default_raw_cmd; raw_cmd->track = track; raw_cmd->flags = (FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK); raw_cmd->rate = _floppy->rate & 0x43; raw_cmd->cmd_count = NR_F; COMMAND = FM_MODE(_floppy, FD_FORMAT); DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, format_req.head); F_SIZECODE = FD_SIZECODE(_floppy); F_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE; F_GAP = _floppy->fmt_gap; F_FILL = FD_FILL_BYTE; raw_cmd->kernel_data = floppy_track_buffer; raw_cmd->length = 4 * F_SECT_PER_TRACK; if (!F_SECT_PER_TRACK) return; /* allow for about 30ms for data transport per track */ head_shift = (F_SECT_PER_TRACK + 5) / 6; /* a ``cylinder'' is two tracks plus a little stepping time */ track_shift = 2 * head_shift + 3; /* position of logical sector 1 on this track */ n = (track_shift * format_req.track + head_shift * format_req.head) % F_SECT_PER_TRACK; /* determine interleave */ il = 1; if (_floppy->fmt_gap < 0x22) il++; /* initialize field */ for (count = 0; count < F_SECT_PER_TRACK; ++count) { here[count].track = format_req.track; here[count].head = format_req.head; here[count].sect = 0; here[count].size = F_SIZECODE; } /* place logical sectors */ for (count = 1; count <= F_SECT_PER_TRACK; ++count) { here[n].sect = count; n = (n + il) % F_SECT_PER_TRACK; if (here[n].sect) { /* sector busy, find next free sector */ ++n; if (n >= F_SECT_PER_TRACK) { n -= F_SECT_PER_TRACK; while (here[n].sect) ++n; } } } if (_floppy->stretch & FD_SECTBASEMASK) { for (count = 0; count < F_SECT_PER_TRACK; count++) here[count].sect += FD_SECTBASE(_floppy) - 1; } } static void redo_format(void) { buffer_track = -1; setup_format_params(format_req.track << STRETCH(_floppy)); floppy_start(); debugt(__func__, "queue format request"); } static const struct cont_t format_cont = { .interrupt = format_interrupt, .redo = redo_format, .error = bad_flp_intr, .done = generic_done }; static int do_format(int drive, struct format_descr *tmp_format_req) { int ret; if (lock_fdc(drive)) return -EINTR; set_floppy(drive); if (!_floppy || _floppy->track > DP->tracks || tmp_format_req->track >= _floppy->track || tmp_format_req->head >= _floppy->head || (_floppy->sect << 2) % (1 << FD_SIZECODE(_floppy)) || !_floppy->fmt_gap) { process_fd_request(); return -EINVAL; } format_req = *tmp_format_req; format_errors = 0; cont = &format_cont; errors = &format_errors; ret = wait_til_done(redo_format, true); if (ret == -EINTR) return -EINTR; process_fd_request(); return ret; } /* * Buffer read/write and support * ============================= */ static void floppy_end_request(struct request *req, blk_status_t error) { unsigned int nr_sectors = current_count_sectors; unsigned int drive = (unsigned long)req->rq_disk->private_data; /* current_count_sectors can be zero if transfer failed */ if (error) nr_sectors = blk_rq_cur_sectors(req); if (blk_update_request(req, error, nr_sectors << 9)) return; __blk_mq_end_request(req, error); /* We're done with the request */ floppy_off(drive); current_req = NULL; } /* new request_done. Can handle physical sectors which are smaller than a * logical buffer */ static void request_done(int uptodate) { struct request *req = current_req; int block; char msg[sizeof("request done ") + sizeof(int) * 3]; probing = 0; snprintf(msg, sizeof(msg), "request done %d", uptodate); reschedule_timeout(MAXTIMEOUT, msg); if (!req) { pr_info("floppy.c: no request in request_done\n"); return; } if (uptodate) { /* maintain values for invalidation on geometry * change */ block = current_count_sectors + blk_rq_pos(req); INFBOUND(DRS->maxblock, block); if (block > _floppy->sect) DRS->maxtrack = 1; floppy_end_request(req, 0); } else { if (rq_data_dir(req) == WRITE) { /* record write error information */ DRWE->write_errors++; if (DRWE->write_errors == 1) { DRWE->first_error_sector = blk_rq_pos(req); DRWE->first_error_generation = DRS->generation; } DRWE->last_error_sector = blk_rq_pos(req); DRWE->last_error_generation = DRS->generation; } floppy_end_request(req, BLK_STS_IOERR); } } /* Interrupt handler evaluating the result of the r/w operation */ static void rw_interrupt(void) { int eoc; int ssize; int heads; int nr_sectors; if (R_HEAD >= 2) { /* some Toshiba floppy controllers occasionnally seem to * return bogus interrupts after read/write operations, which * can be recognized by a bad head number (>= 2) */ return; } if (!DRS->first_read_date) DRS->first_read_date = jiffies; nr_sectors = 0; ssize = DIV_ROUND_UP(1 << SIZECODE, 4); if (ST1 & ST1_EOC) eoc = 1; else eoc = 0; if (COMMAND & 0x80) heads = 2; else heads = 1; nr_sectors = (((R_TRACK - TRACK) * heads + R_HEAD - HEAD) * SECT_PER_TRACK + R_SECTOR - SECTOR + eoc) << SIZECODE >> 2; if (nr_sectors / ssize > DIV_ROUND_UP(in_sector_offset + current_count_sectors, ssize)) { DPRINT("long rw: %x instead of %lx\n", nr_sectors, current_count_sectors); pr_info("rs=%d s=%d\n", R_SECTOR, SECTOR); pr_info("rh=%d h=%d\n", R_HEAD, HEAD); pr_info("rt=%d t=%d\n", R_TRACK, TRACK); pr_info("heads=%d eoc=%d\n", heads, eoc); pr_info("spt=%d st=%d ss=%d\n", SECT_PER_TRACK, fsector_t, ssize); pr_info("in_sector_offset=%d\n", in_sector_offset); } nr_sectors -= in_sector_offset; INFBOUND(nr_sectors, 0); SUPBOUND(current_count_sectors, nr_sectors); switch (interpret_errors()) { case 2: cont->redo(); return; case 1: if (!current_count_sectors) { cont->error(); cont->redo(); return; } break; case 0: if (!current_count_sectors) { cont->redo(); return; } current_type[current_drive] = _floppy; floppy_sizes[TOMINOR(current_drive)] = _floppy->size; break; } if (probing) { if (DP->flags & FTD_MSG) DPRINT("Auto-detected floppy type %s in fd%d\n", _floppy->name, current_drive); current_type[current_drive] = _floppy; floppy_sizes[TOMINOR(current_drive)] = _floppy->size; probing = 0; } if (CT(COMMAND) != FD_READ || raw_cmd->kernel_data == bio_data(current_req->bio)) { /* transfer directly from buffer */ cont->done(1); } else if (CT(COMMAND) == FD_READ) { buffer_track = raw_cmd->track; buffer_drive = current_drive; INFBOUND(buffer_max, nr_sectors + fsector_t); } cont->redo(); } /* Compute maximal contiguous buffer size. */ static int buffer_chain_size(void) { struct bio_vec bv; int size; struct req_iterator iter; char *base; base = bio_data(current_req->bio); size = 0; rq_for_each_segment(bv, current_req, iter) { if (page_address(bv.bv_page) + bv.bv_offset != base + size) break; size += bv.bv_len; } return size >> 9; } /* Compute the maximal transfer size */ static int transfer_size(int ssize, int max_sector, int max_size) { SUPBOUND(max_sector, fsector_t + max_size); /* alignment */ max_sector -= (max_sector % _floppy->sect) % ssize; /* transfer size, beginning not aligned */ current_count_sectors = max_sector - fsector_t; return max_sector; } /* * Move data from/to the track buffer to/from the buffer cache. */ static void copy_buffer(int ssize, int max_sector, int max_sector_2) { int remaining; /* number of transferred 512-byte sectors */ struct bio_vec bv; char *buffer; char *dma_buffer; int size; struct req_iterator iter; max_sector = transfer_size(ssize, min(max_sector, max_sector_2), blk_rq_sectors(current_req)); if (current_count_sectors <= 0 && CT(COMMAND) == FD_WRITE && buffer_max > fsector_t + blk_rq_sectors(current_req)) current_count_sectors = min_t(int, buffer_max - fsector_t, blk_rq_sectors(current_req)); remaining = current_count_sectors << 9; if (remaining > blk_rq_bytes(current_req) && CT(COMMAND) == FD_WRITE) { DPRINT("in copy buffer\n"); pr_info("current_count_sectors=%ld\n", current_count_sectors); pr_info("remaining=%d\n", remaining >> 9); pr_info("current_req->nr_sectors=%u\n", blk_rq_sectors(current_req)); pr_info("current_req->current_nr_sectors=%u\n", blk_rq_cur_sectors(current_req)); pr_info("max_sector=%d\n", max_sector); pr_info("ssize=%d\n", ssize); } buffer_max = max(max_sector, buffer_max); dma_buffer = floppy_track_buffer + ((fsector_t - buffer_min) << 9); size = blk_rq_cur_bytes(current_req); rq_for_each_segment(bv, current_req, iter) { if (!remaining) break; size = bv.bv_len; SUPBOUND(size, remaining); buffer = page_address(bv.bv_page) + bv.bv_offset; if (dma_buffer + size > floppy_track_buffer + (max_buffer_sectors << 10) || dma_buffer < floppy_track_buffer) { DPRINT("buffer overrun in copy buffer %d\n", (int)((floppy_track_buffer - dma_buffer) >> 9)); pr_info("fsector_t=%d buffer_min=%d\n", fsector_t, buffer_min); pr_info("current_count_sectors=%ld\n", current_count_sectors); if (CT(COMMAND) == FD_READ) pr_info("read\n"); if (CT(COMMAND) == FD_WRITE) pr_info("write\n"); break; } if (((unsigned long)buffer) % 512) DPRINT("%p buffer not aligned\n", buffer); if (CT(COMMAND) == FD_READ) memcpy(buffer, dma_buffer, size); else memcpy(dma_buffer, buffer, size); remaining -= size; dma_buffer += size; } if (remaining) { if (remaining > 0) max_sector -= remaining >> 9; DPRINT("weirdness: remaining %d\n", remaining >> 9); } } /* work around a bug in pseudo DMA * (on some FDCs) pseudo DMA does not stop when the CPU stops * sending data. Hence we need a different way to signal the * transfer length: We use SECT_PER_TRACK. Unfortunately, this * does not work with MT, hence we can only transfer one head at * a time */ static void virtualdmabug_workaround(void) { int hard_sectors; int end_sector; if (CT(COMMAND) == FD_WRITE) { COMMAND &= ~0x80; /* switch off multiple track mode */ hard_sectors = raw_cmd->length >> (7 + SIZECODE); end_sector = SECTOR + hard_sectors - 1; if (end_sector > SECT_PER_TRACK) { pr_info("too many sectors %d > %d\n", end_sector, SECT_PER_TRACK); return; } SECT_PER_TRACK = end_sector; /* make sure SECT_PER_TRACK * points to end of transfer */ } } /* * Formulate a read/write request. * this routine decides where to load the data (directly to buffer, or to * tmp floppy area), how much data to load (the size of the buffer, the whole * track, or a single sector) * All floppy_track_buffer handling goes in here. If we ever add track buffer * allocation on the fly, it should be done here. No other part should need * modification. */ static int make_raw_rw_request(void) { int aligned_sector_t; int max_sector; int max_size; int tracksize; int ssize; if (WARN(max_buffer_sectors == 0, "VFS: Block I/O scheduled on unopened device\n")) return 0; set_fdc((long)current_req->rq_disk->private_data); raw_cmd = &default_raw_cmd; raw_cmd->flags = FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK; raw_cmd->cmd_count = NR_RW; if (rq_data_dir(current_req) == READ) { raw_cmd->flags |= FD_RAW_READ; COMMAND = FM_MODE(_floppy, FD_READ); } else if (rq_data_dir(current_req) == WRITE) { raw_cmd->flags |= FD_RAW_WRITE; COMMAND = FM_MODE(_floppy, FD_WRITE); } else { DPRINT("%s: unknown command\n", __func__); return 0; } max_sector = _floppy->sect * _floppy->head; TRACK = (int)blk_rq_pos(current_req) / max_sector; fsector_t = (int)blk_rq_pos(current_req) % max_sector; if (_floppy->track && TRACK >= _floppy->track) { if (blk_rq_cur_sectors(current_req) & 1) { current_count_sectors = 1; return 1; } else return 0; } HEAD = fsector_t / _floppy->sect; if (((_floppy->stretch & (FD_SWAPSIDES | FD_SECTBASEMASK)) || test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) && fsector_t < _floppy->sect) max_sector = _floppy->sect; /* 2M disks have phantom sectors on the first track */ if ((_floppy->rate & FD_2M) && (!TRACK) && (!HEAD)) { max_sector = 2 * _floppy->sect / 3; if (fsector_t >= max_sector) { current_count_sectors = min_t(int, _floppy->sect - fsector_t, blk_rq_sectors(current_req)); return 1; } SIZECODE = 2; } else SIZECODE = FD_SIZECODE(_floppy); raw_cmd->rate = _floppy->rate & 0x43; if ((_floppy->rate & FD_2M) && (TRACK || HEAD) && raw_cmd->rate == 2) raw_cmd->rate = 1; if (SIZECODE) SIZECODE2 = 0xff; else SIZECODE2 = 0x80; raw_cmd->track = TRACK << STRETCH(_floppy); DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, HEAD); GAP = _floppy->gap; ssize = DIV_ROUND_UP(1 << SIZECODE, 4); SECT_PER_TRACK = _floppy->sect << 2 >> SIZECODE; SECTOR = ((fsector_t % _floppy->sect) << 2 >> SIZECODE) + FD_SECTBASE(_floppy); /* tracksize describes the size which can be filled up with sectors * of size ssize. */ tracksize = _floppy->sect - _floppy->sect % ssize; if (tracksize < _floppy->sect) { SECT_PER_TRACK++; if (tracksize <= fsector_t % _floppy->sect) SECTOR--; /* if we are beyond tracksize, fill up using smaller sectors */ while (tracksize <= fsector_t % _floppy->sect) { while (tracksize + ssize > _floppy->sect) { SIZECODE--; ssize >>= 1; } SECTOR++; SECT_PER_TRACK++; tracksize += ssize; } max_sector = HEAD * _floppy->sect + tracksize; } else if (!TRACK && !HEAD && !(_floppy->rate & FD_2M) && probing) { max_sector = _floppy->sect; } else if (!HEAD && CT(COMMAND) == FD_WRITE) { /* for virtual DMA bug workaround */ max_sector = _floppy->sect; } in_sector_offset = (fsector_t % _floppy->sect) % ssize; aligned_sector_t = fsector_t - in_sector_offset; max_size = blk_rq_sectors(current_req); if ((raw_cmd->track == buffer_track) && (current_drive == buffer_drive) && (fsector_t >= buffer_min) && (fsector_t < buffer_max)) { /* data already in track buffer */ if (CT(COMMAND) == FD_READ) { copy_buffer(1, max_sector, buffer_max); return 1; } } else if (in_sector_offset || blk_rq_sectors(current_req) < ssize) { if (CT(COMMAND) == FD_WRITE) { unsigned int sectors; sectors = fsector_t + blk_rq_sectors(current_req); if (sectors > ssize && sectors < ssize + ssize) max_size = ssize + ssize; else max_size = ssize; } raw_cmd->flags &= ~FD_RAW_WRITE; raw_cmd->flags |= FD_RAW_READ; COMMAND = FM_MODE(_floppy, FD_READ); } else if ((unsigned long)bio_data(current_req->bio) < MAX_DMA_ADDRESS) { unsigned long dma_limit; int direct, indirect; indirect = transfer_size(ssize, max_sector, max_buffer_sectors * 2) - fsector_t; /* * Do NOT use minimum() here---MAX_DMA_ADDRESS is 64 bits wide * on a 64 bit machine! */ max_size = buffer_chain_size(); dma_limit = (MAX_DMA_ADDRESS - ((unsigned long)bio_data(current_req->bio))) >> 9; if ((unsigned long)max_size > dma_limit) max_size = dma_limit; /* 64 kb boundaries */ if (CROSS_64KB(bio_data(current_req->bio), max_size << 9)) max_size = (K_64 - ((unsigned long)bio_data(current_req->bio)) % K_64) >> 9; direct = transfer_size(ssize, max_sector, max_size) - fsector_t; /* * We try to read tracks, but if we get too many errors, we * go back to reading just one sector at a time. * * This means we should be able to read a sector even if there * are other bad sectors on this track. */ if (!direct || (indirect * 2 > direct * 3 && *errors < DP->max_errors.read_track && ((!probing || (DP->read_track & (1 << DRS->probed_format)))))) { max_size = blk_rq_sectors(current_req); } else { raw_cmd->kernel_data = bio_data(current_req->bio); raw_cmd->length = current_count_sectors << 9; if (raw_cmd->length == 0) { DPRINT("%s: zero dma transfer attempted\n", __func__); DPRINT("indirect=%d direct=%d fsector_t=%d\n", indirect, direct, fsector_t); return 0; } virtualdmabug_workaround(); return 2; } } if (CT(COMMAND) == FD_READ) max_size = max_sector; /* unbounded */ /* claim buffer track if needed */ if (buffer_track != raw_cmd->track || /* bad track */ buffer_drive != current_drive || /* bad drive */ fsector_t > buffer_max || fsector_t < buffer_min || ((CT(COMMAND) == FD_READ || (!in_sector_offset && blk_rq_sectors(current_req) >= ssize)) && max_sector > 2 * max_buffer_sectors + buffer_min && max_size + fsector_t > 2 * max_buffer_sectors + buffer_min)) { /* not enough space */ buffer_track = -1; buffer_drive = current_drive; buffer_max = buffer_min = aligned_sector_t; } raw_cmd->kernel_data = floppy_track_buffer + ((aligned_sector_t - buffer_min) << 9); if (CT(COMMAND) == FD_WRITE) { /* copy write buffer to track buffer. * if we get here, we know that the write * is either aligned or the data already in the buffer * (buffer will be overwritten) */ if (in_sector_offset && buffer_track == -1) DPRINT("internal error offset !=0 on write\n"); buffer_track = raw_cmd->track; buffer_drive = current_drive; copy_buffer(ssize, max_sector, 2 * max_buffer_sectors + buffer_min); } else transfer_size(ssize, max_sector, 2 * max_buffer_sectors + buffer_min - aligned_sector_t); /* round up current_count_sectors to get dma xfer size */ raw_cmd->length = in_sector_offset + current_count_sectors; raw_cmd->length = ((raw_cmd->length - 1) | (ssize - 1)) + 1; raw_cmd->length <<= 9; if ((raw_cmd->length < current_count_sectors << 9) || (raw_cmd->kernel_data != bio_data(current_req->bio) && CT(COMMAND) == FD_WRITE && (aligned_sector_t + (raw_cmd->length >> 9) > buffer_max || aligned_sector_t < buffer_min)) || raw_cmd->length % (128 << SIZECODE) || raw_cmd->length <= 0 || current_count_sectors <= 0) { DPRINT("fractionary current count b=%lx s=%lx\n", raw_cmd->length, current_count_sectors); if (raw_cmd->kernel_data != bio_data(current_req->bio)) pr_info("addr=%d, length=%ld\n", (int)((raw_cmd->kernel_data - floppy_track_buffer) >> 9), current_count_sectors); pr_info("st=%d ast=%d mse=%d msi=%d\n", fsector_t, aligned_sector_t, max_sector, max_size); pr_info("ssize=%x SIZECODE=%d\n", ssize, SIZECODE); pr_info("command=%x SECTOR=%d HEAD=%d, TRACK=%d\n", COMMAND, SECTOR, HEAD, TRACK); pr_info("buffer drive=%d\n", buffer_drive); pr_info("buffer track=%d\n", buffer_track); pr_info("buffer_min=%d\n", buffer_min); pr_info("buffer_max=%d\n", buffer_max); return 0; } if (raw_cmd->kernel_data != bio_data(current_req->bio)) { if (raw_cmd->kernel_data < floppy_track_buffer || current_count_sectors < 0 || raw_cmd->length < 0 || raw_cmd->kernel_data + raw_cmd->length > floppy_track_buffer + (max_buffer_sectors << 10)) { DPRINT("buffer overrun in schedule dma\n"); pr_info("fsector_t=%d buffer_min=%d current_count=%ld\n", fsector_t, buffer_min, raw_cmd->length >> 9); pr_info("current_count_sectors=%ld\n", current_count_sectors); if (CT(COMMAND) == FD_READ) pr_info("read\n"); if (CT(COMMAND) == FD_WRITE) pr_info("write\n"); return 0; } } else if (raw_cmd->length > blk_rq_bytes(current_req) || current_count_sectors > blk_rq_sectors(current_req)) { DPRINT("buffer overrun in direct transfer\n"); return 0; } else if (raw_cmd->length < current_count_sectors << 9) { DPRINT("more sectors than bytes\n"); pr_info("bytes=%ld\n", raw_cmd->length >> 9); pr_info("sectors=%ld\n", current_count_sectors); } if (raw_cmd->length == 0) { DPRINT("zero dma transfer attempted from make_raw_request\n"); return 0; } virtualdmabug_workaround(); return 2; } static int set_next_request(void) { current_req = list_first_entry_or_null(&floppy_reqs, struct request, queuelist); if (current_req) { current_req->error_count = 0; list_del_init(&current_req->queuelist); } return current_req != NULL; } static void redo_fd_request(void) { int drive; int tmp; lastredo = jiffies; if (current_drive < N_DRIVE) floppy_off(current_drive); do_request: if (!current_req) { int pending; spin_lock_irq(&floppy_lock); pending = set_next_request(); spin_unlock_irq(&floppy_lock); if (!pending) { do_floppy = NULL; unlock_fdc(); return; } } drive = (long)current_req->rq_disk->private_data; set_fdc(drive); reschedule_timeout(current_reqD, "redo fd request"); set_floppy(drive); raw_cmd = &default_raw_cmd; raw_cmd->flags = 0; if (start_motor(redo_fd_request)) return; disk_change(current_drive); if (test_bit(current_drive, &fake_change) || test_bit(FD_DISK_CHANGED_BIT, &DRS->flags)) { DPRINT("disk absent or changed during operation\n"); request_done(0); goto do_request; } if (!_floppy) { /* Autodetection */ if (!probing) { DRS->probed_format = 0; if (next_valid_format()) { DPRINT("no autodetectable formats\n"); _floppy = NULL; request_done(0); goto do_request; } } probing = 1; _floppy = floppy_type + DP->autodetect[DRS->probed_format]; } else probing = 0; errors = &(current_req->error_count); tmp = make_raw_rw_request(); if (tmp < 2) { request_done(tmp); goto do_request; } if (test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) twaddle(); schedule_bh(floppy_start); debugt(__func__, "queue fd request"); return; } static const struct cont_t rw_cont = { .interrupt = rw_interrupt, .redo = redo_fd_request, .error = bad_flp_intr, .done = request_done }; static void process_fd_request(void) { cont = &rw_cont; schedule_bh(redo_fd_request); } static blk_status_t floppy_queue_rq(struct blk_mq_hw_ctx *hctx, const struct blk_mq_queue_data *bd) { blk_mq_start_request(bd->rq); if (WARN(max_buffer_sectors == 0, "VFS: %s called on non-open device\n", __func__)) return BLK_STS_IOERR; if (WARN(atomic_read(&usage_count) == 0, "warning: usage count=0, current_req=%p sect=%ld flags=%llx\n", current_req, (long)blk_rq_pos(current_req), (unsigned long long) current_req->cmd_flags)) return BLK_STS_IOERR; spin_lock_irq(&floppy_lock); list_add_tail(&bd->rq->queuelist, &floppy_reqs); spin_unlock_irq(&floppy_lock); if (test_and_set_bit(0, &fdc_busy)) { /* fdc busy, this new request will be treated when the current one is done */ is_alive(__func__, "old request running"); return BLK_STS_OK; } command_status = FD_COMMAND_NONE; __reschedule_timeout(MAXTIMEOUT, "fd_request"); set_fdc(0); process_fd_request(); is_alive(__func__, ""); return BLK_STS_OK; } static const struct cont_t poll_cont = { .interrupt = success_and_wakeup, .redo = floppy_ready, .error = generic_failure, .done = generic_done }; static int poll_drive(bool interruptible, int flag) { /* no auto-sense, just clear dcl */ raw_cmd = &default_raw_cmd; raw_cmd->flags = flag; raw_cmd->track = 0; raw_cmd->cmd_count = 0; cont = &poll_cont; debug_dcl(DP->flags, "setting NEWCHANGE in poll_drive\n"); set_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); return wait_til_done(floppy_ready, interruptible); } /* * User triggered reset * ==================== */ static void reset_intr(void) { pr_info("weird, reset interrupt called\n"); } static const struct cont_t reset_cont = { .interrupt = reset_intr, .redo = success_and_wakeup, .error = generic_failure, .done = generic_done }; static int user_reset_fdc(int drive, int arg, bool interruptible) { int ret; if (lock_fdc(drive)) return -EINTR; if (arg == FD_RESET_ALWAYS) FDCS->reset = 1; if (FDCS->reset) { cont = &reset_cont; ret = wait_til_done(reset_fdc, interruptible); if (ret == -EINTR) return -EINTR; } process_fd_request(); return 0; } /* * Misc Ioctl's and support * ======================== */ static inline int fd_copyout(void __user *param, const void *address, unsigned long size) { return copy_to_user(param, address, size) ? -EFAULT : 0; } static inline int fd_copyin(void __user *param, void *address, unsigned long size) { return copy_from_user(address, param, size) ? -EFAULT : 0; } static const char *drive_name(int type, int drive) { struct floppy_struct *floppy; if (type) floppy = floppy_type + type; else { if (UDP->native_format) floppy = floppy_type + UDP->native_format; else return "(null)"; } if (floppy->name) return floppy->name; else return "(null)"; } /* raw commands */ static void raw_cmd_done(int flag) { int i; if (!flag) { raw_cmd->flags |= FD_RAW_FAILURE; raw_cmd->flags |= FD_RAW_HARDFAILURE; } else { raw_cmd->reply_count = inr; if (raw_cmd->reply_count > MAX_REPLIES) raw_cmd->reply_count = 0; for (i = 0; i < raw_cmd->reply_count; i++) raw_cmd->reply[i] = reply_buffer[i]; if (raw_cmd->flags & (FD_RAW_READ | FD_RAW_WRITE)) { unsigned long flags; flags = claim_dma_lock(); raw_cmd->length = fd_get_dma_residue(); release_dma_lock(flags); } if ((raw_cmd->flags & FD_RAW_SOFTFAILURE) && (!raw_cmd->reply_count || (raw_cmd->reply[0] & 0xc0))) raw_cmd->flags |= FD_RAW_FAILURE; if (disk_change(current_drive)) raw_cmd->flags |= FD_RAW_DISK_CHANGE; else raw_cmd->flags &= ~FD_RAW_DISK_CHANGE; if (raw_cmd->flags & FD_RAW_NO_MOTOR_AFTER) motor_off_callback(&motor_off_timer[current_drive]); if (raw_cmd->next && (!(raw_cmd->flags & FD_RAW_FAILURE) || !(raw_cmd->flags & FD_RAW_STOP_IF_FAILURE)) && ((raw_cmd->flags & FD_RAW_FAILURE) || !(raw_cmd->flags & FD_RAW_STOP_IF_SUCCESS))) { raw_cmd = raw_cmd->next; return; } } generic_done(flag); } static const struct cont_t raw_cmd_cont = { .interrupt = success_and_wakeup, .redo = floppy_start, .error = generic_failure, .done = raw_cmd_done }; static int raw_cmd_copyout(int cmd, void __user *param, struct floppy_raw_cmd *ptr) { int ret; while (ptr) { struct floppy_raw_cmd cmd = *ptr; cmd.next = NULL; cmd.kernel_data = NULL; ret = copy_to_user(param, &cmd, sizeof(cmd)); if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) { if (ptr->length >= 0 && ptr->length <= ptr->buffer_length) { long length = ptr->buffer_length - ptr->length; ret = fd_copyout(ptr->data, ptr->kernel_data, length); if (ret) return ret; } } ptr = ptr->next; } return 0; } static void raw_cmd_free(struct floppy_raw_cmd **ptr) { struct floppy_raw_cmd *next; struct floppy_raw_cmd *this; this = *ptr; *ptr = NULL; while (this) { if (this->buffer_length) { fd_dma_mem_free((unsigned long)this->kernel_data, this->buffer_length); this->buffer_length = 0; } next = this->next; kfree(this); this = next; } } static int raw_cmd_copyin(int cmd, void __user *param, struct floppy_raw_cmd **rcmd) { struct floppy_raw_cmd *ptr; int ret; int i; *rcmd = NULL; loop: ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_KERNEL); if (!ptr) return -ENOMEM; *rcmd = ptr; ret = copy_from_user(ptr, param, sizeof(*ptr)); ptr->next = NULL; ptr->buffer_length = 0; ptr->kernel_data = NULL; if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if (ptr->cmd_count > 33) /* the command may now also take up the space * initially intended for the reply & the * reply count. Needed for long 82078 commands * such as RESTORE, which takes ... 17 command * bytes. Murphy's law #137: When you reserve * 16 bytes for a structure, you'll one day * discover that you really need 17... */ return -EINVAL; for (i = 0; i < 16; i++) ptr->reply[i] = 0; ptr->resultcode = 0; if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) { if (ptr->length <= 0) return -EINVAL; ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length); fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length); if (!ptr->kernel_data) return -ENOMEM; ptr->buffer_length = ptr->length; } if (ptr->flags & FD_RAW_WRITE) { ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length); if (ret) return ret; } if (ptr->flags & FD_RAW_MORE) { rcmd = &(ptr->next); ptr->rate &= 0x43; goto loop; } return 0; } static int raw_cmd_ioctl(int cmd, void __user *param) { struct floppy_raw_cmd *my_raw_cmd; int drive; int ret2; int ret; if (FDCS->rawcmd <= 1) FDCS->rawcmd = 1; for (drive = 0; drive < N_DRIVE; drive++) { if (FDC(drive) != fdc) continue; if (drive == current_drive) { if (UDRS->fd_ref > 1) { FDCS->rawcmd = 2; break; } } else if (UDRS->fd_ref) { FDCS->rawcmd = 2; break; } } if (FDCS->reset) return -EIO; ret = raw_cmd_copyin(cmd, param, &my_raw_cmd); if (ret) { raw_cmd_free(&my_raw_cmd); return ret; } raw_cmd = my_raw_cmd; cont = &raw_cmd_cont; ret = wait_til_done(floppy_start, true); debug_dcl(DP->flags, "calling disk change from raw_cmd ioctl\n"); if (ret != -EINTR && FDCS->reset) ret = -EIO; DRS->track = NO_TRACK; ret2 = raw_cmd_copyout(cmd, param, my_raw_cmd); if (!ret) ret = ret2; raw_cmd_free(&my_raw_cmd); return ret; } static int invalidate_drive(struct block_device *bdev) { /* invalidate the buffer track to force a reread */ set_bit((long)bdev->bd_disk->private_data, &fake_change); process_fd_request(); check_disk_change(bdev); return 0; } static int set_geometry(unsigned int cmd, struct floppy_struct *g, int drive, int type, struct block_device *bdev) { int cnt; /* sanity checking for parameters. */ if (g->sect <= 0 || g->head <= 0 || /* check for zero in F_SECT_PER_TRACK */ (unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 || g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) || /* check if reserved bits are set */ (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0) return -EINVAL; if (type) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&open_lock); if (lock_fdc(drive)) { mutex_unlock(&open_lock); return -EINTR; } floppy_type[type] = *g; floppy_type[type].name = "user format"; for (cnt = type << 2; cnt < (type << 2) + 4; cnt++) floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] = floppy_type[type].size + 1; process_fd_request(); for (cnt = 0; cnt < N_DRIVE; cnt++) { struct block_device *bdev = opened_bdev[cnt]; if (!bdev || ITYPE(drive_state[cnt].fd_device) != type) continue; __invalidate_device(bdev, true); } mutex_unlock(&open_lock); } else { int oldStretch; if (lock_fdc(drive)) return -EINTR; if (cmd != FDDEFPRM) { /* notice a disk change immediately, else * we lose our settings immediately*/ if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; } oldStretch = g->stretch; user_params[drive] = *g; if (buffer_drive == drive) SUPBOUND(buffer_max, user_params[drive].sect); current_type[drive] = &user_params[drive]; floppy_sizes[drive] = user_params[drive].size; if (cmd == FDDEFPRM) DRS->keep_data = -1; else DRS->keep_data = 1; /* invalidation. Invalidate only when needed, i.e. * when there are already sectors in the buffer cache * whose number will change. This is useful, because * mtools often changes the geometry of the disk after * looking at the boot block */ if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack || ((user_params[drive].sect ^ oldStretch) & (FD_SWAPSIDES | FD_SECTBASEMASK))) invalidate_drive(bdev); else process_fd_request(); } return 0; } /* handle obsolete ioctl's */ static unsigned int ioctl_table[] = { FDCLRPRM, FDSETPRM, FDDEFPRM, FDGETPRM, FDMSGON, FDMSGOFF, FDFMTBEG, FDFMTTRK, FDFMTEND, FDSETEMSGTRESH, FDFLUSH, FDSETMAXERRS, FDGETMAXERRS, FDGETDRVTYP, FDSETDRVPRM, FDGETDRVPRM, FDGETDRVSTAT, FDPOLLDRVSTAT, FDRESET, FDGETFDCSTAT, FDWERRORCLR, FDWERRORGET, FDRAWCMD, FDEJECT, FDTWADDLE }; static int normalize_ioctl(unsigned int *cmd, int *size) { int i; for (i = 0; i < ARRAY_SIZE(ioctl_table); i++) { if ((*cmd & 0xffff) == (ioctl_table[i] & 0xffff)) { *size = _IOC_SIZE(*cmd); *cmd = ioctl_table[i]; if (*size > _IOC_SIZE(*cmd)) { pr_info("ioctl not yet supported\n"); return -EFAULT; } return 0; } } return -EINVAL; } static int get_floppy_geometry(int drive, int type, struct floppy_struct **g) { if (type) *g = &floppy_type[type]; else { if (lock_fdc(drive)) return -EINTR; if (poll_drive(false, 0) == -EINTR) return -EINTR; process_fd_request(); *g = current_type[drive]; } if (!*g) return -ENODEV; return 0; } static int fd_getgeo(struct block_device *bdev, struct hd_geometry *geo) { int drive = (long)bdev->bd_disk->private_data; int type = ITYPE(drive_state[drive].fd_device); struct floppy_struct *g; int ret; ret = get_floppy_geometry(drive, type, &g); if (ret) return ret; geo->heads = g->head; geo->sectors = g->sect; geo->cylinders = g->track; return 0; } static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long param) { int drive = (long)bdev->bd_disk->private_data; int type = ITYPE(UDRS->fd_device); int i; int ret; int size; union inparam { struct floppy_struct g; /* geometry */ struct format_descr f; struct floppy_max_errors max_errors; struct floppy_drive_params dp; } inparam; /* parameters coming from user space */ const void *outparam; /* parameters passed back to user space */ /* convert compatibility eject ioctls into floppy eject ioctl. * We do this in order to provide a means to eject floppy disks before * installing the new fdutils package */ if (cmd == CDROMEJECT || /* CD-ROM eject */ cmd == 0x6470) { /* SunOS floppy eject */ DPRINT("obsolete eject ioctl\n"); DPRINT("please use floppycontrol --eject\n"); cmd = FDEJECT; } if (!((cmd & 0xff00) == 0x0200)) return -EINVAL; /* convert the old style command into a new style command */ ret = normalize_ioctl(&cmd, &size); if (ret) return ret; /* permission checks */ if (((cmd & 0x40) && !(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) || ((cmd & 0x80) && !capable(CAP_SYS_ADMIN))) return -EPERM; if (WARN_ON(size < 0 || size > sizeof(inparam))) return -EINVAL; /* copyin */ memset(&inparam, 0, sizeof(inparam)); if (_IOC_DIR(cmd) & _IOC_WRITE) { ret = fd_copyin((void __user *)param, &inparam, size); if (ret) return ret; } switch (cmd) { case FDEJECT: if (UDRS->fd_ref != 1) /* somebody else has this drive open */ return -EBUSY; if (lock_fdc(drive)) return -EINTR; /* do the actual eject. Fails on * non-Sparc architectures */ ret = fd_eject(UNIT(drive)); set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); set_bit(FD_VERIFY_BIT, &UDRS->flags); process_fd_request(); return ret; case FDCLRPRM: if (lock_fdc(drive)) return -EINTR; current_type[drive] = NULL; floppy_sizes[drive] = MAX_DISK_SIZE << 1; UDRS->keep_data = 0; return invalidate_drive(bdev); case FDSETPRM: case FDDEFPRM: return set_geometry(cmd, &inparam.g, drive, type, bdev); case FDGETPRM: ret = get_floppy_geometry(drive, type, (struct floppy_struct **)&outparam); if (ret) return ret; memcpy(&inparam.g, outparam, offsetof(struct floppy_struct, name)); outparam = &inparam.g; break; case FDMSGON: UDP->flags |= FTD_MSG; return 0; case FDMSGOFF: UDP->flags &= ~FTD_MSG; return 0; case FDFMTBEG: if (lock_fdc(drive)) return -EINTR; if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; ret = UDRS->flags; process_fd_request(); if (ret & FD_VERIFY) return -ENODEV; if (!(ret & FD_DISK_WRITABLE)) return -EROFS; return 0; case FDFMTTRK: if (UDRS->fd_ref != 1) return -EBUSY; return do_format(drive, &inparam.f); case FDFMTEND: case FDFLUSH: if (lock_fdc(drive)) return -EINTR; return invalidate_drive(bdev); case FDSETEMSGTRESH: UDP->max_errors.reporting = (unsigned short)(param & 0x0f); return 0; case FDGETMAXERRS: outparam = &UDP->max_errors; break; case FDSETMAXERRS: UDP->max_errors = inparam.max_errors; break; case FDGETDRVTYP: outparam = drive_name(type, drive); SUPBOUND(size, strlen((const char *)outparam) + 1); break; case FDSETDRVPRM: *UDP = inparam.dp; break; case FDGETDRVPRM: outparam = UDP; break; case FDPOLLDRVSTAT: if (lock_fdc(drive)) return -EINTR; if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; process_fd_request(); /* fall through */ case FDGETDRVSTAT: outparam = UDRS; break; case FDRESET: return user_reset_fdc(drive, (int)param, true); case FDGETFDCSTAT: outparam = UFDCS; break; case FDWERRORCLR: memset(UDRWE, 0, sizeof(*UDRWE)); return 0; case FDWERRORGET: outparam = UDRWE; break; case FDRAWCMD: if (type) return -EINVAL; if (lock_fdc(drive)) return -EINTR; set_floppy(drive); i = raw_cmd_ioctl(cmd, (void __user *)param); if (i == -EINTR) return -EINTR; process_fd_request(); return i; case FDTWADDLE: if (lock_fdc(drive)) return -EINTR; twaddle(); process_fd_request(); return 0; default: return -EINVAL; } if (_IOC_DIR(cmd) & _IOC_READ) return fd_copyout((void __user *)param, outparam, size); return 0; } static int fd_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long param) { int ret; mutex_lock(&floppy_mutex); ret = fd_locked_ioctl(bdev, mode, cmd, param); mutex_unlock(&floppy_mutex); return ret; } #ifdef CONFIG_COMPAT struct compat_floppy_drive_params { char cmos; compat_ulong_t max_dtr; compat_ulong_t hlt; compat_ulong_t hut; compat_ulong_t srt; compat_ulong_t spinup; compat_ulong_t spindown; unsigned char spindown_offset; unsigned char select_delay; unsigned char rps; unsigned char tracks; compat_ulong_t timeout; unsigned char interleave_sect; struct floppy_max_errors max_errors; char flags; char read_track; short autodetect[8]; compat_int_t checkfreq; compat_int_t native_format; }; struct compat_floppy_drive_struct { signed char flags; compat_ulong_t spinup_date; compat_ulong_t select_date; compat_ulong_t first_read_date; short probed_format; short track; short maxblock; short maxtrack; compat_int_t generation; compat_int_t keep_data; compat_int_t fd_ref; compat_int_t fd_device; compat_int_t last_checked; compat_caddr_t dmabuf; compat_int_t bufblocks; }; struct compat_floppy_fdc_state { compat_int_t spec1; compat_int_t spec2; compat_int_t dtr; unsigned char version; unsigned char dor; compat_ulong_t address; unsigned int rawcmd:2; unsigned int reset:1; unsigned int need_configure:1; unsigned int perp_mode:2; unsigned int has_fifo:1; unsigned int driver_version; unsigned char track[4]; }; struct compat_floppy_write_errors { unsigned int write_errors; compat_ulong_t first_error_sector; compat_int_t first_error_generation; compat_ulong_t last_error_sector; compat_int_t last_error_generation; compat_uint_t badness; }; #define FDSETPRM32 _IOW(2, 0x42, struct compat_floppy_struct) #define FDDEFPRM32 _IOW(2, 0x43, struct compat_floppy_struct) #define FDSETDRVPRM32 _IOW(2, 0x90, struct compat_floppy_drive_params) #define FDGETDRVPRM32 _IOR(2, 0x11, struct compat_floppy_drive_params) #define FDGETDRVSTAT32 _IOR(2, 0x12, struct compat_floppy_drive_struct) #define FDPOLLDRVSTAT32 _IOR(2, 0x13, struct compat_floppy_drive_struct) #define FDGETFDCSTAT32 _IOR(2, 0x15, struct compat_floppy_fdc_state) #define FDWERRORGET32 _IOR(2, 0x17, struct compat_floppy_write_errors) static int compat_set_geometry(struct block_device *bdev, fmode_t mode, unsigned int cmd, struct compat_floppy_struct __user *arg) { struct floppy_struct v; int drive, type; int err; BUILD_BUG_ON(offsetof(struct floppy_struct, name) != offsetof(struct compat_floppy_struct, name)); if (!(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) return -EPERM; memset(&v, 0, sizeof(struct floppy_struct)); if (copy_from_user(&v, arg, offsetof(struct floppy_struct, name))) return -EFAULT; mutex_lock(&floppy_mutex); drive = (long)bdev->bd_disk->private_data; type = ITYPE(UDRS->fd_device); err = set_geometry(cmd == FDSETPRM32 ? FDSETPRM : FDDEFPRM, &v, drive, type, bdev); mutex_unlock(&floppy_mutex); return err; } static int compat_get_prm(int drive, struct compat_floppy_struct __user *arg) { struct compat_floppy_struct v; struct floppy_struct *p; int err; memset(&v, 0, sizeof(v)); mutex_lock(&floppy_mutex); err = get_floppy_geometry(drive, ITYPE(UDRS->fd_device), &p); if (err) { mutex_unlock(&floppy_mutex); return err; } memcpy(&v, p, offsetof(struct floppy_struct, name)); mutex_unlock(&floppy_mutex); if (copy_to_user(arg, &v, sizeof(struct compat_floppy_struct))) return -EFAULT; return 0; } static int compat_setdrvprm(int drive, struct compat_floppy_drive_params __user *arg) { struct compat_floppy_drive_params v; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (copy_from_user(&v, arg, sizeof(struct compat_floppy_drive_params))) return -EFAULT; mutex_lock(&floppy_mutex); UDP->cmos = v.cmos; UDP->max_dtr = v.max_dtr; UDP->hlt = v.hlt; UDP->hut = v.hut; UDP->srt = v.srt; UDP->spinup = v.spinup; UDP->spindown = v.spindown; UDP->spindown_offset = v.spindown_offset; UDP->select_delay = v.select_delay; UDP->rps = v.rps; UDP->tracks = v.tracks; UDP->timeout = v.timeout; UDP->interleave_sect = v.interleave_sect; UDP->max_errors = v.max_errors; UDP->flags = v.flags; UDP->read_track = v.read_track; memcpy(UDP->autodetect, v.autodetect, sizeof(v.autodetect)); UDP->checkfreq = v.checkfreq; UDP->native_format = v.native_format; mutex_unlock(&floppy_mutex); return 0; } static int compat_getdrvprm(int drive, struct compat_floppy_drive_params __user *arg) { struct compat_floppy_drive_params v; memset(&v, 0, sizeof(struct compat_floppy_drive_params)); mutex_lock(&floppy_mutex); v.cmos = UDP->cmos; v.max_dtr = UDP->max_dtr; v.hlt = UDP->hlt; v.hut = UDP->hut; v.srt = UDP->srt; v.spinup = UDP->spinup; v.spindown = UDP->spindown; v.spindown_offset = UDP->spindown_offset; v.select_delay = UDP->select_delay; v.rps = UDP->rps; v.tracks = UDP->tracks; v.timeout = UDP->timeout; v.interleave_sect = UDP->interleave_sect; v.max_errors = UDP->max_errors; v.flags = UDP->flags; v.read_track = UDP->read_track; memcpy(v.autodetect, UDP->autodetect, sizeof(v.autodetect)); v.checkfreq = UDP->checkfreq; v.native_format = UDP->native_format; mutex_unlock(&floppy_mutex); if (copy_from_user(arg, &v, sizeof(struct compat_floppy_drive_params))) return -EFAULT; return 0; } static int compat_getdrvstat(int drive, bool poll, struct compat_floppy_drive_struct __user *arg) { struct compat_floppy_drive_struct v; memset(&v, 0, sizeof(struct compat_floppy_drive_struct)); mutex_lock(&floppy_mutex); if (poll) { if (lock_fdc(drive)) goto Eintr; if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) goto Eintr; process_fd_request(); } v.spinup_date = UDRS->spinup_date; v.select_date = UDRS->select_date; v.first_read_date = UDRS->first_read_date; v.probed_format = UDRS->probed_format; v.track = UDRS->track; v.maxblock = UDRS->maxblock; v.maxtrack = UDRS->maxtrack; v.generation = UDRS->generation; v.keep_data = UDRS->keep_data; v.fd_ref = UDRS->fd_ref; v.fd_device = UDRS->fd_device; v.last_checked = UDRS->last_checked; v.dmabuf = (uintptr_t)UDRS->dmabuf; v.bufblocks = UDRS->bufblocks; mutex_unlock(&floppy_mutex); if (copy_from_user(arg, &v, sizeof(struct compat_floppy_drive_struct))) return -EFAULT; return 0; Eintr: mutex_unlock(&floppy_mutex); return -EINTR; } static int compat_getfdcstat(int drive, struct compat_floppy_fdc_state __user *arg) { struct compat_floppy_fdc_state v32; struct floppy_fdc_state v; mutex_lock(&floppy_mutex); v = *UFDCS; mutex_unlock(&floppy_mutex); memset(&v32, 0, sizeof(struct compat_floppy_fdc_state)); v32.spec1 = v.spec1; v32.spec2 = v.spec2; v32.dtr = v.dtr; v32.version = v.version; v32.dor = v.dor; v32.address = v.address; v32.rawcmd = v.rawcmd; v32.reset = v.reset; v32.need_configure = v.need_configure; v32.perp_mode = v.perp_mode; v32.has_fifo = v.has_fifo; v32.driver_version = v.driver_version; memcpy(v32.track, v.track, 4); if (copy_to_user(arg, &v32, sizeof(struct compat_floppy_fdc_state))) return -EFAULT; return 0; } static int compat_werrorget(int drive, struct compat_floppy_write_errors __user *arg) { struct compat_floppy_write_errors v32; struct floppy_write_errors v; memset(&v32, 0, sizeof(struct compat_floppy_write_errors)); mutex_lock(&floppy_mutex); v = *UDRWE; mutex_unlock(&floppy_mutex); v32.write_errors = v.write_errors; v32.first_error_sector = v.first_error_sector; v32.first_error_generation = v.first_error_generation; v32.last_error_sector = v.last_error_sector; v32.last_error_generation = v.last_error_generation; v32.badness = v.badness; if (copy_to_user(arg, &v32, sizeof(struct compat_floppy_write_errors))) return -EFAULT; return 0; } static int fd_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long param) { int drive = (long)bdev->bd_disk->private_data; switch (cmd) { case FDMSGON: case FDMSGOFF: case FDSETEMSGTRESH: case FDFLUSH: case FDWERRORCLR: case FDEJECT: case FDCLRPRM: case FDFMTBEG: case FDRESET: case FDTWADDLE: return fd_ioctl(bdev, mode, cmd, param); case FDSETMAXERRS: case FDGETMAXERRS: case FDGETDRVTYP: case FDFMTEND: case FDFMTTRK: case FDRAWCMD: return fd_ioctl(bdev, mode, cmd, (unsigned long)compat_ptr(param)); case FDSETPRM32: case FDDEFPRM32: return compat_set_geometry(bdev, mode, cmd, compat_ptr(param)); case FDGETPRM32: return compat_get_prm(drive, compat_ptr(param)); case FDSETDRVPRM32: return compat_setdrvprm(drive, compat_ptr(param)); case FDGETDRVPRM32: return compat_getdrvprm(drive, compat_ptr(param)); case FDPOLLDRVSTAT32: return compat_getdrvstat(drive, true, compat_ptr(param)); case FDGETDRVSTAT32: return compat_getdrvstat(drive, false, compat_ptr(param)); case FDGETFDCSTAT32: return compat_getfdcstat(drive, compat_ptr(param)); case FDWERRORGET32: return compat_werrorget(drive, compat_ptr(param)); } return -EINVAL; } #endif static void __init config_types(void) { bool has_drive = false; int drive; /* read drive info out of physical CMOS */ drive = 0; if (!UDP->cmos) UDP->cmos = FLOPPY0_TYPE; drive = 1; if (!UDP->cmos && FLOPPY1_TYPE) UDP->cmos = FLOPPY1_TYPE; /* FIXME: additional physical CMOS drive detection should go here */ for (drive = 0; drive < N_DRIVE; drive++) { unsigned int type = UDP->cmos; struct floppy_drive_params *params; const char *name = NULL; char temparea[32]; if (type < ARRAY_SIZE(default_drive_params)) { params = &default_drive_params[type].params; if (type) { name = default_drive_params[type].name; allowed_drive_mask |= 1 << drive; } else allowed_drive_mask &= ~(1 << drive); } else { params = &default_drive_params[0].params; snprintf(temparea, sizeof(temparea), "unknown type %d (usb?)", type); name = temparea; } if (name) { const char *prepend; if (!has_drive) { prepend = ""; has_drive = true; pr_info("Floppy drive(s):"); } else { prepend = ","; } pr_cont("%s fd%d is %s", prepend, drive, name); } *UDP = *params; } if (has_drive) pr_cont("\n"); } static void floppy_release(struct gendisk *disk, fmode_t mode) { int drive = (long)disk->private_data; mutex_lock(&floppy_mutex); mutex_lock(&open_lock); if (!UDRS->fd_ref--) { DPRINT("floppy_release with fd_ref == 0"); UDRS->fd_ref = 0; } if (!UDRS->fd_ref) opened_bdev[drive] = NULL; mutex_unlock(&open_lock); mutex_unlock(&floppy_mutex); } /* * floppy_open check for aliasing (/dev/fd0 can be the same as * /dev/PS0 etc), and disallows simultaneous access to the same * drive with different device numbers. */ static int floppy_open(struct block_device *bdev, fmode_t mode) { int drive = (long)bdev->bd_disk->private_data; int old_dev, new_dev; int try; int res = -EBUSY; char *tmp; mutex_lock(&floppy_mutex); mutex_lock(&open_lock); old_dev = UDRS->fd_device; if (opened_bdev[drive] && opened_bdev[drive] != bdev) goto out2; if (!UDRS->fd_ref && (UDP->flags & FD_BROKEN_DCL)) { set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); set_bit(FD_VERIFY_BIT, &UDRS->flags); } UDRS->fd_ref++; opened_bdev[drive] = bdev; res = -ENXIO; if (!floppy_track_buffer) { /* if opening an ED drive, reserve a big buffer, * else reserve a small one */ if ((UDP->cmos == 6) || (UDP->cmos == 5)) try = 64; /* Only 48 actually useful */ else try = 32; /* Only 24 actually useful */ tmp = (char *)fd_dma_mem_alloc(1024 * try); if (!tmp && !floppy_track_buffer) { try >>= 1; /* buffer only one side */ INFBOUND(try, 16); tmp = (char *)fd_dma_mem_alloc(1024 * try); } if (!tmp && !floppy_track_buffer) fallback_on_nodma_alloc(&tmp, 2048 * try); if (!tmp && !floppy_track_buffer) { DPRINT("Unable to allocate DMA memory\n"); goto out; } if (floppy_track_buffer) { if (tmp) fd_dma_mem_free((unsigned long)tmp, try * 1024); } else { buffer_min = buffer_max = -1; floppy_track_buffer = tmp; max_buffer_sectors = try; } } new_dev = MINOR(bdev->bd_dev); UDRS->fd_device = new_dev; set_capacity(disks[drive], floppy_sizes[new_dev]); if (old_dev != -1 && old_dev != new_dev) { if (buffer_drive == drive) buffer_track = -1; } if (UFDCS->rawcmd == 1) UFDCS->rawcmd = 2; if (!(mode & FMODE_NDELAY)) { if (mode & (FMODE_READ|FMODE_WRITE)) { UDRS->last_checked = 0; clear_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags); check_disk_change(bdev); if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags)) goto out; if (test_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags)) goto out; } res = -EROFS; if ((mode & FMODE_WRITE) && !test_bit(FD_DISK_WRITABLE_BIT, &UDRS->flags)) goto out; } mutex_unlock(&open_lock); mutex_unlock(&floppy_mutex); return 0; out: UDRS->fd_ref--; if (!UDRS->fd_ref) opened_bdev[drive] = NULL; out2: mutex_unlock(&open_lock); mutex_unlock(&floppy_mutex); return res; } /* * Check if the disk has been changed or if a change has been faked. */ static unsigned int floppy_check_events(struct gendisk *disk, unsigned int clearing) { int drive = (long)disk->private_data; if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags)) return DISK_EVENT_MEDIA_CHANGE; if (time_after(jiffies, UDRS->last_checked + UDP->checkfreq)) { if (lock_fdc(drive)) return 0; poll_drive(false, 0); process_fd_request(); } if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags) || test_bit(drive, &fake_change) || drive_no_geom(drive)) return DISK_EVENT_MEDIA_CHANGE; return 0; } /* * This implements "read block 0" for floppy_revalidate(). * Needed for format autodetection, checking whether there is * a disk in the drive, and whether that disk is writable. */ struct rb0_cbdata { int drive; struct completion complete; }; static void floppy_rb0_cb(struct bio *bio) { struct rb0_cbdata *cbdata = (struct rb0_cbdata *)bio->bi_private; int drive = cbdata->drive; if (bio->bi_status) { pr_info("floppy: error %d while reading block 0\n", bio->bi_status); set_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags); } complete(&cbdata->complete); } static int __floppy_read_block_0(struct block_device *bdev, int drive) { struct bio bio; struct bio_vec bio_vec; struct page *page; struct rb0_cbdata cbdata; size_t size; page = alloc_page(GFP_NOIO); if (!page) { process_fd_request(); return -ENOMEM; } size = bdev->bd_block_size; if (!size) size = 1024; cbdata.drive = drive; bio_init(&bio, &bio_vec, 1); bio_set_dev(&bio, bdev); bio_add_page(&bio, page, size, 0); bio.bi_iter.bi_sector = 0; bio.bi_flags |= (1 << BIO_QUIET); bio.bi_private = &cbdata; bio.bi_end_io = floppy_rb0_cb; bio_set_op_attrs(&bio, REQ_OP_READ, 0); init_completion(&cbdata.complete); submit_bio(&bio); process_fd_request(); wait_for_completion(&cbdata.complete); __free_page(page); return 0; } /* revalidate the floppy disk, i.e. trigger format autodetection by reading * the bootblock (block 0). "Autodetection" is also needed to check whether * there is a disk in the drive at all... Thus we also do it for fixed * geometry formats */ static int floppy_revalidate(struct gendisk *disk) { int drive = (long)disk->private_data; int cf; int res = 0; if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags) || test_bit(drive, &fake_change) || drive_no_geom(drive)) { if (WARN(atomic_read(&usage_count) == 0, "VFS: revalidate called on non-open device.\n")) return -EFAULT; res = lock_fdc(drive); if (res) return res; cf = (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags)); if (!(cf || test_bit(drive, &fake_change) || drive_no_geom(drive))) { process_fd_request(); /*already done by another thread */ return 0; } UDRS->maxblock = 0; UDRS->maxtrack = 0; if (buffer_drive == drive) buffer_track = -1; clear_bit(drive, &fake_change); clear_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); if (cf) UDRS->generation++; if (drive_no_geom(drive)) { /* auto-sensing */ res = __floppy_read_block_0(opened_bdev[drive], drive); } else { if (cf) poll_drive(false, FD_RAW_NEED_DISK); process_fd_request(); } } set_capacity(disk, floppy_sizes[UDRS->fd_device]); return res; } static const struct block_device_operations floppy_fops = { .owner = THIS_MODULE, .open = floppy_open, .release = floppy_release, .ioctl = fd_ioctl, .getgeo = fd_getgeo, .check_events = floppy_check_events, .revalidate_disk = floppy_revalidate, #ifdef CONFIG_COMPAT .compat_ioctl = fd_compat_ioctl, #endif }; /* * Floppy Driver initialization * ============================= */ /* Determine the floppy disk controller type */ /* This routine was written by David C. Niemi */ static char __init get_fdc_version(void) { int r; output_byte(FD_DUMPREGS); /* 82072 and better know DUMPREGS */ if (FDCS->reset) return FDC_NONE; r = result(); if (r <= 0x00) return FDC_NONE; /* No FDC present ??? */ if ((r == 1) && (reply_buffer[0] == 0x80)) { pr_info("FDC %d is an 8272A\n", fdc); return FDC_8272A; /* 8272a/765 don't know DUMPREGS */ } if (r != 10) { pr_info("FDC %d init: DUMPREGS: unexpected return of %d bytes.\n", fdc, r); return FDC_UNKNOWN; } if (!fdc_configure()) { pr_info("FDC %d is an 82072\n", fdc); return FDC_82072; /* 82072 doesn't know CONFIGURE */ } output_byte(FD_PERPENDICULAR); if (need_more_output() == MORE_OUTPUT) { output_byte(0); } else { pr_info("FDC %d is an 82072A\n", fdc); return FDC_82072A; /* 82072A as found on Sparcs. */ } output_byte(FD_UNLOCK); r = result(); if ((r == 1) && (reply_buffer[0] == 0x80)) { pr_info("FDC %d is a pre-1991 82077\n", fdc); return FDC_82077_ORIG; /* Pre-1991 82077, doesn't know * LOCK/UNLOCK */ } if ((r != 1) || (reply_buffer[0] != 0x00)) { pr_info("FDC %d init: UNLOCK: unexpected return of %d bytes.\n", fdc, r); return FDC_UNKNOWN; } output_byte(FD_PARTID); r = result(); if (r != 1) { pr_info("FDC %d init: PARTID: unexpected return of %d bytes.\n", fdc, r); return FDC_UNKNOWN; } if (reply_buffer[0] == 0x80) { pr_info("FDC %d is a post-1991 82077\n", fdc); return FDC_82077; /* Revised 82077AA passes all the tests */ } switch (reply_buffer[0] >> 5) { case 0x0: /* Either a 82078-1 or a 82078SL running at 5Volt */ pr_info("FDC %d is an 82078.\n", fdc); return FDC_82078; case 0x1: pr_info("FDC %d is a 44pin 82078\n", fdc); return FDC_82078; case 0x2: pr_info("FDC %d is a S82078B\n", fdc); return FDC_S82078B; case 0x3: pr_info("FDC %d is a National Semiconductor PC87306\n", fdc); return FDC_87306; default: pr_info("FDC %d init: 82078 variant with unknown PARTID=%d.\n", fdc, reply_buffer[0] >> 5); return FDC_82078_UNKN; } } /* get_fdc_version */ /* lilo configuration */ static void __init floppy_set_flags(int *ints, int param, int param2) { int i; for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) { if (param) default_drive_params[i].params.flags |= param2; else default_drive_params[i].params.flags &= ~param2; } DPRINT("%s flag 0x%x\n", param2 ? "Setting" : "Clearing", param); } static void __init daring(int *ints, int param, int param2) { int i; for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) { if (param) { default_drive_params[i].params.select_delay = 0; default_drive_params[i].params.flags |= FD_SILENT_DCL_CLEAR; } else { default_drive_params[i].params.select_delay = 2 * HZ / 100; default_drive_params[i].params.flags &= ~FD_SILENT_DCL_CLEAR; } } DPRINT("Assuming %s floppy hardware\n", param ? "standard" : "broken"); } static void __init set_cmos(int *ints, int dummy, int dummy2) { int current_drive = 0; if (ints[0] != 2) { DPRINT("wrong number of parameters for CMOS\n"); return; } current_drive = ints[1]; if (current_drive < 0 || current_drive >= 8) { DPRINT("bad drive for set_cmos\n"); return; } #if N_FDC > 1 if (current_drive >= 4 && !FDC2) FDC2 = 0x370; #endif DP->cmos = ints[2]; DPRINT("setting CMOS code to %d\n", ints[2]); } static struct param_table { const char *name; void (*fn) (int *ints, int param, int param2); int *var; int def_param; int param2; } config_params[] __initdata = { {"allowed_drive_mask", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */ {"all_drives", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */ {"asus_pci", NULL, &allowed_drive_mask, 0x33, 0}, {"irq", NULL, &FLOPPY_IRQ, 6, 0}, {"dma", NULL, &FLOPPY_DMA, 2, 0}, {"daring", daring, NULL, 1, 0}, #if N_FDC > 1 {"two_fdc", NULL, &FDC2, 0x370, 0}, {"one_fdc", NULL, &FDC2, 0, 0}, #endif {"thinkpad", floppy_set_flags, NULL, 1, FD_INVERTED_DCL}, {"broken_dcl", floppy_set_flags, NULL, 1, FD_BROKEN_DCL}, {"messages", floppy_set_flags, NULL, 1, FTD_MSG}, {"silent_dcl_clear", floppy_set_flags, NULL, 1, FD_SILENT_DCL_CLEAR}, {"debug", floppy_set_flags, NULL, 1, FD_DEBUG}, {"nodma", NULL, &can_use_virtual_dma, 1, 0}, {"omnibook", NULL, &can_use_virtual_dma, 1, 0}, {"yesdma", NULL, &can_use_virtual_dma, 0, 0}, {"fifo_depth", NULL, &fifo_depth, 0xa, 0}, {"nofifo", NULL, &no_fifo, 0x20, 0}, {"usefifo", NULL, &no_fifo, 0, 0}, {"cmos", set_cmos, NULL, 0, 0}, {"slow", NULL, &slow_floppy, 1, 0}, {"unexpected_interrupts", NULL, &print_unex, 1, 0}, {"no_unexpected_interrupts", NULL, &print_unex, 0, 0}, {"L40SX", NULL, &print_unex, 0, 0} EXTRA_FLOPPY_PARAMS }; static int __init floppy_setup(char *str) { int i; int param; int ints[11]; str = get_options(str, ARRAY_SIZE(ints), ints); if (str) { for (i = 0; i < ARRAY_SIZE(config_params); i++) { if (strcmp(str, config_params[i].name) == 0) { if (ints[0]) param = ints[1]; else param = config_params[i].def_param; if (config_params[i].fn) config_params[i].fn(ints, param, config_params[i]. param2); if (config_params[i].var) { DPRINT("%s=%d\n", str, param); *config_params[i].var = param; } return 1; } } } if (str) { DPRINT("unknown floppy option [%s]\n", str); DPRINT("allowed options are:"); for (i = 0; i < ARRAY_SIZE(config_params); i++) pr_cont(" %s", config_params[i].name); pr_cont("\n"); } else DPRINT("botched floppy option\n"); DPRINT("Read Documentation/blockdev/floppy.txt\n"); return 0; } static int have_no_fdc = -ENODEV; static ssize_t floppy_cmos_show(struct device *dev, struct device_attribute *attr, char *buf) { struct platform_device *p = to_platform_device(dev); int drive; drive = p->id; return sprintf(buf, "%X\n", UDP->cmos); } static DEVICE_ATTR(cmos, 0444, floppy_cmos_show, NULL); static struct attribute *floppy_dev_attrs[] = { &dev_attr_cmos.attr, NULL }; ATTRIBUTE_GROUPS(floppy_dev); static void floppy_device_release(struct device *dev) { } static int floppy_resume(struct device *dev) { int fdc; for (fdc = 0; fdc < N_FDC; fdc++) if (FDCS->address != -1) user_reset_fdc(-1, FD_RESET_ALWAYS, false); return 0; } static const struct dev_pm_ops floppy_pm_ops = { .resume = floppy_resume, .restore = floppy_resume, }; static struct platform_driver floppy_driver = { .driver = { .name = "floppy", .pm = &floppy_pm_ops, }, }; static const struct blk_mq_ops floppy_mq_ops = { .queue_rq = floppy_queue_rq, }; static struct platform_device floppy_device[N_DRIVE]; static bool floppy_available(int drive) { if (!(allowed_drive_mask & (1 << drive))) return false; if (fdc_state[FDC(drive)].version == FDC_NONE) return false; return true; } static struct kobject *floppy_find(dev_t dev, int *part, void *data) { int drive = (*part & 3) | ((*part & 0x80) >> 5); if (drive >= N_DRIVE || !floppy_available(drive)) return NULL; if (((*part >> 2) & 0x1f) >= ARRAY_SIZE(floppy_type)) return NULL; *part = 0; return get_disk_and_module(disks[drive]); } static int __init do_floppy_init(void) { int i, unit, drive, err; set_debugt(); interruptjiffies = resultjiffies = jiffies; #if defined(CONFIG_PPC) if (check_legacy_ioport(FDC1)) return -ENODEV; #endif raw_cmd = NULL; floppy_wq = alloc_ordered_workqueue("floppy", 0); if (!floppy_wq) return -ENOMEM; for (drive = 0; drive < N_DRIVE; drive++) { disks[drive] = alloc_disk(1); if (!disks[drive]) { err = -ENOMEM; goto out_put_disk; } disks[drive]->queue = blk_mq_init_sq_queue(&tag_sets[drive], &floppy_mq_ops, 2, BLK_MQ_F_SHOULD_MERGE); if (IS_ERR(disks[drive]->queue)) { err = PTR_ERR(disks[drive]->queue); disks[drive]->queue = NULL; goto out_put_disk; } blk_queue_bounce_limit(disks[drive]->queue, BLK_BOUNCE_HIGH); blk_queue_max_hw_sectors(disks[drive]->queue, 64); disks[drive]->major = FLOPPY_MAJOR; disks[drive]->first_minor = TOMINOR(drive); disks[drive]->fops = &floppy_fops; disks[drive]->events = DISK_EVENT_MEDIA_CHANGE; sprintf(disks[drive]->disk_name, "fd%d", drive); timer_setup(&motor_off_timer[drive], motor_off_callback, 0); } err = register_blkdev(FLOPPY_MAJOR, "fd"); if (err) goto out_put_disk; err = platform_driver_register(&floppy_driver); if (err) goto out_unreg_blkdev; blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE, floppy_find, NULL, NULL); for (i = 0; i < 256; i++) if (ITYPE(i)) floppy_sizes[i] = floppy_type[ITYPE(i)].size; else floppy_sizes[i] = MAX_DISK_SIZE << 1; reschedule_timeout(MAXTIMEOUT, "floppy init"); config_types(); for (i = 0; i < N_FDC; i++) { fdc = i; memset(FDCS, 0, sizeof(*FDCS)); FDCS->dtr = -1; FDCS->dor = 0x4; #if defined(__sparc__) || defined(__mc68000__) /*sparcs/sun3x don't have a DOR reset which we can fall back on to */ #ifdef __mc68000__ if (MACH_IS_SUN3X) #endif FDCS->version = FDC_82072A; #endif } use_virtual_dma = can_use_virtual_dma & 1; fdc_state[0].address = FDC1; if (fdc_state[0].address == -1) { cancel_delayed_work(&fd_timeout); err = -ENODEV; goto out_unreg_region; } #if N_FDC > 1 fdc_state[1].address = FDC2; #endif fdc = 0; /* reset fdc in case of unexpected interrupt */ err = floppy_grab_irq_and_dma(); if (err) { cancel_delayed_work(&fd_timeout); err = -EBUSY; goto out_unreg_region; } /* initialise drive state */ for (drive = 0; drive < N_DRIVE; drive++) { memset(UDRS, 0, sizeof(*UDRS)); memset(UDRWE, 0, sizeof(*UDRWE)); set_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags); set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); set_bit(FD_VERIFY_BIT, &UDRS->flags); UDRS->fd_device = -1; floppy_track_buffer = NULL; max_buffer_sectors = 0; } /* * Small 10 msec delay to let through any interrupt that * initialization might have triggered, to not * confuse detection: */ msleep(10); for (i = 0; i < N_FDC; i++) { fdc = i; FDCS->driver_version = FD_DRIVER_VERSION; for (unit = 0; unit < 4; unit++) FDCS->track[unit] = 0; if (FDCS->address == -1) continue; FDCS->rawcmd = 2; if (user_reset_fdc(-1, FD_RESET_ALWAYS, false)) { /* free ioports reserved by floppy_grab_irq_and_dma() */ floppy_release_regions(fdc); FDCS->address = -1; FDCS->version = FDC_NONE; continue; } /* Try to determine the floppy controller type */ FDCS->version = get_fdc_version(); if (FDCS->version == FDC_NONE) { /* free ioports reserved by floppy_grab_irq_and_dma() */ floppy_release_regions(fdc); FDCS->address = -1; continue; } if (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A) can_use_virtual_dma = 0; have_no_fdc = 0; /* Not all FDCs seem to be able to handle the version command * properly, so force a reset for the standard FDC clones, * to avoid interrupt garbage. */ user_reset_fdc(-1, FD_RESET_ALWAYS, false); } fdc = 0; cancel_delayed_work(&fd_timeout); current_drive = 0; initialized = true; if (have_no_fdc) { DPRINT("no floppy controllers found\n"); err = have_no_fdc; goto out_release_dma; } for (drive = 0; drive < N_DRIVE; drive++) { if (!floppy_available(drive)) continue; floppy_device[drive].name = floppy_device_name; floppy_device[drive].id = drive; floppy_device[drive].dev.release = floppy_device_release; floppy_device[drive].dev.groups = floppy_dev_groups; err = platform_device_register(&floppy_device[drive]); if (err) goto out_remove_drives; /* to be cleaned up... */ disks[drive]->private_data = (void *)(long)drive; disks[drive]->flags |= GENHD_FL_REMOVABLE; device_add_disk(&floppy_device[drive].dev, disks[drive], NULL); } return 0; out_remove_drives: while (drive--) { if (floppy_available(drive)) { del_gendisk(disks[drive]); platform_device_unregister(&floppy_device[drive]); } } out_release_dma: if (atomic_read(&usage_count)) floppy_release_irq_and_dma(); out_unreg_region: blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256); platform_driver_unregister(&floppy_driver); out_unreg_blkdev: unregister_blkdev(FLOPPY_MAJOR, "fd"); out_put_disk: destroy_workqueue(floppy_wq); for (drive = 0; drive < N_DRIVE; drive++) { if (!disks[drive]) break; if (disks[drive]->queue) { del_timer_sync(&motor_off_timer[drive]); blk_cleanup_queue(disks[drive]->queue); disks[drive]->queue = NULL; blk_mq_free_tag_set(&tag_sets[drive]); } put_disk(disks[drive]); } return err; } #ifndef MODULE static __init void floppy_async_init(void *data, async_cookie_t cookie) { do_floppy_init(); } #endif static int __init floppy_init(void) { #ifdef MODULE return do_floppy_init(); #else /* Don't hold up the bootup by the floppy initialization */ async_schedule(floppy_async_init, NULL); return 0; #endif } static const struct io_region { int offset; int size; } io_regions[] = { { 2, 1 }, /* address + 3 is sometimes reserved by pnp bios for motherboard */ { 4, 2 }, /* address + 6 is reserved, and may be taken by IDE. * Unfortunately, Adaptec doesn't know this :-(, */ { 7, 1 }, }; static void floppy_release_allocated_regions(int fdc, const struct io_region *p) { while (p != io_regions) { p--; release_region(FDCS->address + p->offset, p->size); } } #define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)])) static int floppy_request_regions(int fdc) { const struct io_region *p; for (p = io_regions; p < ARRAY_END(io_regions); p++) { if (!request_region(FDCS->address + p->offset, p->size, "floppy")) { DPRINT("Floppy io-port 0x%04lx in use\n", FDCS->address + p->offset); floppy_release_allocated_regions(fdc, p); return -EBUSY; } } return 0; } static void floppy_release_regions(int fdc) { floppy_release_allocated_regions(fdc, ARRAY_END(io_regions)); } static int floppy_grab_irq_and_dma(void) { if (atomic_inc_return(&usage_count) > 1) return 0; /* * We might have scheduled a free_irq(), wait it to * drain first: */ flush_workqueue(floppy_wq); if (fd_request_irq()) { DPRINT("Unable to grab IRQ%d for the floppy driver\n", FLOPPY_IRQ); atomic_dec(&usage_count); return -1; } if (fd_request_dma()) { DPRINT("Unable to grab DMA%d for the floppy driver\n", FLOPPY_DMA); if (can_use_virtual_dma & 2) use_virtual_dma = can_use_virtual_dma = 1; if (!(can_use_virtual_dma & 1)) { fd_free_irq(); atomic_dec(&usage_count); return -1; } } for (fdc = 0; fdc < N_FDC; fdc++) { if (FDCS->address != -1) { if (floppy_request_regions(fdc)) goto cleanup; } } for (fdc = 0; fdc < N_FDC; fdc++) { if (FDCS->address != -1) { reset_fdc_info(1); fd_outb(FDCS->dor, FD_DOR); } } fdc = 0; set_dor(0, ~0, 8); /* avoid immediate interrupt */ for (fdc = 0; fdc < N_FDC; fdc++) if (FDCS->address != -1) fd_outb(FDCS->dor, FD_DOR); /* * The driver will try and free resources and relies on us * to know if they were allocated or not. */ fdc = 0; irqdma_allocated = 1; return 0; cleanup: fd_free_irq(); fd_free_dma(); while (--fdc >= 0) floppy_release_regions(fdc); atomic_dec(&usage_count); return -1; } static void floppy_release_irq_and_dma(void) { int old_fdc; #ifndef __sparc__ int drive; #endif long tmpsize; unsigned long tmpaddr; if (!atomic_dec_and_test(&usage_count)) return; if (irqdma_allocated) { fd_disable_dma(); fd_free_dma(); fd_free_irq(); irqdma_allocated = 0; } set_dor(0, ~0, 8); #if N_FDC > 1 set_dor(1, ~8, 0); #endif if (floppy_track_buffer && max_buffer_sectors) { tmpsize = max_buffer_sectors * 1024; tmpaddr = (unsigned long)floppy_track_buffer; floppy_track_buffer = NULL; max_buffer_sectors = 0; buffer_min = buffer_max = -1; fd_dma_mem_free(tmpaddr, tmpsize); } #ifndef __sparc__ for (drive = 0; drive < N_FDC * 4; drive++) if (timer_pending(motor_off_timer + drive)) pr_info("motor off timer %d still active\n", drive); #endif if (delayed_work_pending(&fd_timeout)) pr_info("floppy timer still active:%s\n", timeout_message); if (delayed_work_pending(&fd_timer)) pr_info("auxiliary floppy timer still active\n"); if (work_pending(&floppy_work)) pr_info("work still pending\n"); old_fdc = fdc; for (fdc = 0; fdc < N_FDC; fdc++) if (FDCS->address != -1) floppy_release_regions(fdc); fdc = old_fdc; } #ifdef MODULE static char *floppy; static void __init parse_floppy_cfg_string(char *cfg) { char *ptr; while (*cfg) { ptr = cfg; while (*cfg && *cfg != ' ' && *cfg != '\t') cfg++; if (*cfg) { *cfg = '\0'; cfg++; } if (*ptr) floppy_setup(ptr); } } static int __init floppy_module_init(void) { if (floppy) parse_floppy_cfg_string(floppy); return floppy_init(); } module_init(floppy_module_init); static void __exit floppy_module_exit(void) { int drive; blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256); unregister_blkdev(FLOPPY_MAJOR, "fd"); platform_driver_unregister(&floppy_driver); destroy_workqueue(floppy_wq); for (drive = 0; drive < N_DRIVE; drive++) { del_timer_sync(&motor_off_timer[drive]); if (floppy_available(drive)) { del_gendisk(disks[drive]); platform_device_unregister(&floppy_device[drive]); } blk_cleanup_queue(disks[drive]->queue); blk_mq_free_tag_set(&tag_sets[drive]); /* * These disks have not called add_disk(). Don't put down * queue reference in put_disk(). */ if (!(allowed_drive_mask & (1 << drive)) || fdc_state[FDC(drive)].version == FDC_NONE) disks[drive]->queue = NULL; put_disk(disks[drive]); } cancel_delayed_work_sync(&fd_timeout); cancel_delayed_work_sync(&fd_timer); if (atomic_read(&usage_count)) floppy_release_irq_and_dma(); /* eject disk, if any */ fd_eject(0); } module_exit(floppy_module_exit); module_param(floppy, charp, 0); module_param(FLOPPY_IRQ, int, 0); module_param(FLOPPY_DMA, int, 0); MODULE_AUTHOR("Alain L. Knaff"); MODULE_SUPPORTED_DEVICE("fd"); MODULE_LICENSE("GPL"); /* This doesn't actually get used other than for module information */ static const struct pnp_device_id floppy_pnpids[] = { {"PNP0700", 0}, {} }; MODULE_DEVICE_TABLE(pnp, floppy_pnpids); #else __setup("floppy=", floppy_setup); module_init(floppy_init) #endif MODULE_ALIAS_BLOCKDEV_MAJOR(FLOPPY_MAJOR);
./CrossVul/dataset_final_sorted/CWE-369/c/good_967_0
crossvul-cpp_data_good_538_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" /** @defgroup PI PI - Implementation of a packet iterator */ /*@{*/ /** @name Local static functions */ /*@{*/ /** Get next packet in layer-resolution-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-layer-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-precinct-component-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi); /** Get next packet in precinct-component-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi); /** Get next packet in component-precinct-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static opj_bool pi_next_cprl(opj_pi_iterator_t * pi); /*@}*/ /*@}*/ /* ========================================================== local functions ========================================================== */ static opj_bool pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { goto LABEL_SKIP; } else { int compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static opj_bool pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { int compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } } } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } static opj_bool pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } /* ========================================================== Packet iterator interface ========================================================== */ opj_pi_iterator_t *pi_create_decode(opj_image_t *image, opj_cp_t *cp, int tileno) { int p, q; int compno, resno, pino; opj_pi_iterator_t *pi = NULL; opj_tcp_t *tcp = NULL; opj_tccp_t *tccp = NULL; tcp = &cp->tcps[tileno]; pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1), sizeof(opj_pi_iterator_t)); if (!pi) { /* TODO: throw an error */ return NULL; } for (pino = 0; pino < tcp->numpocs + 1; pino++) { /* change */ int maxres = 0; int maxprec = 0; p = tileno % cp->tw; q = tileno / cp->tw; pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0); pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0); pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1); pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1); pi[pino].numcomps = image->numcomps; pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (!pi[pino].comps) { /* TODO: throw an error */ pi_destroy(pi, cp, tileno); return NULL; } for (compno = 0; compno < pi->numcomps; compno++) { int tcx0, tcy0, tcx1, tcy1; opj_pi_comp_t *comp = &pi[pino].comps[compno]; tccp = &tcp->tccps[compno]; comp->dx = image->comps[compno].dx; comp->dy = image->comps[compno].dy; comp->numresolutions = tccp->numresolutions; comp->resolutions = (opj_pi_resolution_t*) opj_calloc(comp->numresolutions, sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { /* TODO: throw an error */ pi_destroy(pi, cp, tileno); return NULL; } tcx0 = int_ceildiv(pi->tx0, comp->dx); tcy0 = int_ceildiv(pi->ty0, comp->dy); tcx1 = int_ceildiv(pi->tx1, comp->dx); tcy1 = int_ceildiv(pi->ty1, comp->dy); if (comp->numresolutions > maxres) { maxres = comp->numresolutions; } for (resno = 0; resno < comp->numresolutions; resno++) { int levelno; int rx0, ry0, rx1, ry1; int px0, py0, px1, py1; opj_pi_resolution_t *res = &comp->resolutions[resno]; if (tccp->csty & J2K_CCP_CSTY_PRT) { res->pdx = tccp->prcw[resno]; res->pdy = tccp->prch[resno]; } else { res->pdx = 15; res->pdy = 15; } levelno = comp->numresolutions - 1 - resno; rx0 = int_ceildivpow2(tcx0, levelno); ry0 = int_ceildivpow2(tcy0, levelno); rx1 = int_ceildivpow2(tcx1, levelno); ry1 = int_ceildivpow2(tcy1, levelno); px0 = int_floordivpow2(rx0, res->pdx) << res->pdx; py0 = int_floordivpow2(ry0, res->pdy) << res->pdy; px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx; py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy; res->pw = (rx0 == rx1) ? 0 : ((px1 - px0) >> res->pdx); res->ph = (ry0 == ry1) ? 0 : ((py1 - py0) >> res->pdy); if (res->pw * res->ph > maxprec) { maxprec = res->pw * res->ph; } } } tccp = &tcp->tccps[0]; pi[pino].step_p = 1; pi[pino].step_c = maxprec * pi[pino].step_p; pi[pino].step_r = image->numcomps * pi[pino].step_c; pi[pino].step_l = maxres * pi[pino].step_r; if (pino == 0) { pi[pino].include = (short int*) opj_calloc(image->numcomps * maxres * tcp->numlayers * maxprec, sizeof(short int)); if (!pi[pino].include) { /* TODO: throw an error */ pi_destroy(pi, cp, tileno); return NULL; } } else { pi[pino].include = pi[pino - 1].include; } if (tcp->POC == 0) { pi[pino].first = 1; pi[pino].poc.resno0 = 0; pi[pino].poc.compno0 = 0; pi[pino].poc.layno1 = tcp->numlayers; pi[pino].poc.resno1 = maxres; pi[pino].poc.compno1 = image->numcomps; pi[pino].poc.prg = tcp->prg; } else { pi[pino].first = 1; pi[pino].poc.resno0 = tcp->pocs[pino].resno0; pi[pino].poc.compno0 = tcp->pocs[pino].compno0; pi[pino].poc.layno1 = tcp->pocs[pino].layno1; pi[pino].poc.resno1 = tcp->pocs[pino].resno1; pi[pino].poc.compno1 = tcp->pocs[pino].compno1; pi[pino].poc.prg = tcp->pocs[pino].prg; } pi[pino].poc.layno0 = 0; pi[pino].poc.precno0 = 0; pi[pino].poc.precno1 = maxprec; } return pi; } opj_pi_iterator_t *pi_initialise_encode(opj_image_t *image, opj_cp_t *cp, int tileno, J2K_T2_MODE t2_mode) { int p, q, pino; int compno, resno; int maxres = 0; int maxprec = 0; opj_pi_iterator_t *pi = NULL; opj_tcp_t *tcp = NULL; opj_tccp_t *tccp = NULL; tcp = &cp->tcps[tileno]; pi = (opj_pi_iterator_t*) opj_calloc((tcp->numpocs + 1), sizeof(opj_pi_iterator_t)); if (!pi) { return NULL; } pi->tp_on = cp->tp_on; for (pino = 0; pino < tcp->numpocs + 1 ; pino ++) { p = tileno % cp->tw; q = tileno / cp->tw; pi[pino].tx0 = int_max(cp->tx0 + p * cp->tdx, image->x0); pi[pino].ty0 = int_max(cp->ty0 + q * cp->tdy, image->y0); pi[pino].tx1 = int_min(cp->tx0 + (p + 1) * cp->tdx, image->x1); pi[pino].ty1 = int_min(cp->ty0 + (q + 1) * cp->tdy, image->y1); pi[pino].numcomps = image->numcomps; pi[pino].comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (!pi[pino].comps) { pi_destroy(pi, cp, tileno); return NULL; } for (compno = 0; compno < pi[pino].numcomps; compno++) { int tcx0, tcy0, tcx1, tcy1; opj_pi_comp_t *comp = &pi[pino].comps[compno]; tccp = &tcp->tccps[compno]; comp->dx = image->comps[compno].dx; comp->dy = image->comps[compno].dy; comp->numresolutions = tccp->numresolutions; comp->resolutions = (opj_pi_resolution_t*) opj_malloc(comp->numresolutions * sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { pi_destroy(pi, cp, tileno); return NULL; } tcx0 = int_ceildiv(pi[pino].tx0, comp->dx); tcy0 = int_ceildiv(pi[pino].ty0, comp->dy); tcx1 = int_ceildiv(pi[pino].tx1, comp->dx); tcy1 = int_ceildiv(pi[pino].ty1, comp->dy); if (comp->numresolutions > maxres) { maxres = comp->numresolutions; } for (resno = 0; resno < comp->numresolutions; resno++) { int levelno; int rx0, ry0, rx1, ry1; int px0, py0, px1, py1; opj_pi_resolution_t *res = &comp->resolutions[resno]; if (tccp->csty & J2K_CCP_CSTY_PRT) { res->pdx = tccp->prcw[resno]; res->pdy = tccp->prch[resno]; } else { res->pdx = 15; res->pdy = 15; } levelno = comp->numresolutions - 1 - resno; rx0 = int_ceildivpow2(tcx0, levelno); ry0 = int_ceildivpow2(tcy0, levelno); rx1 = int_ceildivpow2(tcx1, levelno); ry1 = int_ceildivpow2(tcy1, levelno); px0 = int_floordivpow2(rx0, res->pdx) << res->pdx; py0 = int_floordivpow2(ry0, res->pdy) << res->pdy; px1 = int_ceildivpow2(rx1, res->pdx) << res->pdx; py1 = int_ceildivpow2(ry1, res->pdy) << res->pdy; res->pw = (rx0 == rx1) ? 0 : ((px1 - px0) >> res->pdx); res->ph = (ry0 == ry1) ? 0 : ((py1 - py0) >> res->pdy); if (res->pw * res->ph > maxprec) { maxprec = res->pw * res->ph; } } } tccp = &tcp->tccps[0]; pi[pino].step_p = 1; pi[pino].step_c = maxprec * pi[pino].step_p; pi[pino].step_r = image->numcomps * pi[pino].step_c; pi[pino].step_l = maxres * pi[pino].step_r; for (compno = 0; compno < pi->numcomps; compno++) { opj_pi_comp_t *comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; opj_pi_resolution_t *res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi[pino].dx = !pi->dx ? dx : int_min(pi->dx, dx); pi[pino].dy = !pi->dy ? dy : int_min(pi->dy, dy); } } if (pino == 0) { pi[pino].include = (short int*) opj_calloc(tcp->numlayers * pi[pino].step_l, sizeof(short int)); if (!pi[pino].include) { pi_destroy(pi, cp, tileno); return NULL; } } else { pi[pino].include = pi[pino - 1].include; } /* Generation of boundaries for each prog flag*/ if (tcp->POC && (cp->cinema || ((!cp->cinema) && (t2_mode == FINAL_PASS)))) { tcp->pocs[pino].compS = tcp->pocs[pino].compno0; tcp->pocs[pino].compE = tcp->pocs[pino].compno1; tcp->pocs[pino].resS = tcp->pocs[pino].resno0; tcp->pocs[pino].resE = tcp->pocs[pino].resno1; tcp->pocs[pino].layE = tcp->pocs[pino].layno1; tcp->pocs[pino].prg = tcp->pocs[pino].prg1; if (pino > 0) { tcp->pocs[pino].layS = (tcp->pocs[pino].layE > tcp->pocs[pino - 1].layE) ? tcp->pocs[pino - 1].layE : 0; } } else { tcp->pocs[pino].compS = 0; tcp->pocs[pino].compE = image->numcomps; tcp->pocs[pino].resS = 0; tcp->pocs[pino].resE = maxres; tcp->pocs[pino].layS = 0; tcp->pocs[pino].layE = tcp->numlayers; tcp->pocs[pino].prg = tcp->prg; } tcp->pocs[pino].prcS = 0; tcp->pocs[pino].prcE = maxprec;; tcp->pocs[pino].txS = pi[pino].tx0; tcp->pocs[pino].txE = pi[pino].tx1; tcp->pocs[pino].tyS = pi[pino].ty0; tcp->pocs[pino].tyE = pi[pino].ty1; tcp->pocs[pino].dx = pi[pino].dx; tcp->pocs[pino].dy = pi[pino].dy; } return pi; } void pi_destroy(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno) { int compno, pino; opj_tcp_t *tcp = &cp->tcps[tileno]; if (pi) { for (pino = 0; pino < tcp->numpocs + 1; pino++) { if (pi[pino].comps) { for (compno = 0; compno < pi->numcomps; compno++) { opj_pi_comp_t *comp = &pi[pino].comps[compno]; if (comp->resolutions) { opj_free(comp->resolutions); } } opj_free(pi[pino].comps); } } if (pi->include) { opj_free(pi->include); } opj_free(pi); } } opj_bool pi_next(opj_pi_iterator_t * pi) { switch (pi->poc.prg) { case LRCP: return pi_next_lrcp(pi); case RLCP: return pi_next_rlcp(pi); case RPCL: return pi_next_rpcl(pi); case PCRL: return pi_next_pcrl(pi); case CPRL: return pi_next_cprl(pi); case PROG_UNKNOWN: return OPJ_FALSE; } return OPJ_FALSE; } opj_bool pi_create_encode(opj_pi_iterator_t *pi, opj_cp_t *cp, int tileno, int pino, int tpnum, int tppos, J2K_T2_MODE t2_mode, int cur_totnum_tp) { char prog[4]; int i; int incr_top = 1, resetX = 0; opj_tcp_t *tcps = &cp->tcps[tileno]; opj_poc_t *tcp = &tcps->pocs[pino]; pi[pino].first = 1; pi[pino].poc.prg = tcp->prg; switch (tcp->prg) { case CPRL: strncpy(prog, "CPRL", 4); break; case LRCP: strncpy(prog, "LRCP", 4); break; case PCRL: strncpy(prog, "PCRL", 4); break; case RLCP: strncpy(prog, "RLCP", 4); break; case RPCL: strncpy(prog, "RPCL", 4); break; case PROG_UNKNOWN: return OPJ_TRUE; } if (!(cp->tp_on && ((!cp->cinema && (t2_mode == FINAL_PASS)) || cp->cinema))) { pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; pi[pino].poc.tx0 = tcp->txS; pi[pino].poc.ty0 = tcp->tyS; pi[pino].poc.tx1 = tcp->txE; pi[pino].poc.ty1 = tcp->tyE; } else { if (tpnum < cur_totnum_tp) { for (i = 3; i >= 0; i--) { switch (prog[i]) { case 'C': if (i > tppos) { pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; } else { if (tpnum == 0) { tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; } else { if (incr_top == 1) { if (tcp->comp_t == tcp->compE) { tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; incr_top = 1; } else { pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t + 1; tcp->comp_t += 1; incr_top = 0; } } else { pi[pino].poc.compno0 = tcp->comp_t - 1; pi[pino].poc.compno1 = tcp->comp_t; } } } break; case 'R': if (i > tppos) { pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; } else { if (tpnum == 0) { tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; } else { if (incr_top == 1) { if (tcp->res_t == tcp->resE) { tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; incr_top = 1; } else { pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t + 1; tcp->res_t += 1; incr_top = 0; } } else { pi[pino].poc.resno0 = tcp->res_t - 1; pi[pino].poc.resno1 = tcp->res_t; } } } break; case 'L': if (i > tppos) { pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; } else { if (tpnum == 0) { tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; } else { if (incr_top == 1) { if (tcp->lay_t == tcp->layE) { tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; incr_top = 1; } else { pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t + 1; tcp->lay_t += 1; incr_top = 0; } } else { pi[pino].poc.layno0 = tcp->lay_t - 1; pi[pino].poc.layno1 = tcp->lay_t; } } } break; case 'P': switch (tcp->prg) { case LRCP: case RLCP: if (i > tppos) { pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; } else { if (tpnum == 0) { tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; } else { if (incr_top == 1) { if (tcp->prc_t == tcp->prcE) { tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; incr_top = 1; } else { pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t + 1; tcp->prc_t += 1; incr_top = 0; } } else { pi[pino].poc.precno0 = tcp->prc_t - 1; pi[pino].poc.precno1 = tcp->prc_t; } } } break; default: if (i > tppos) { pi[pino].poc.tx0 = tcp->txS; pi[pino].poc.ty0 = tcp->tyS; pi[pino].poc.tx1 = tcp->txE; pi[pino].poc.ty1 = tcp->tyE; } else { if (tpnum == 0) { tcp->tx0_t = tcp->txS; tcp->ty0_t = tcp->tyS; pi[pino].poc.tx0 = tcp->tx0_t; pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx); pi[pino].poc.ty0 = tcp->ty0_t; pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); tcp->tx0_t = pi[pino].poc.tx1; tcp->ty0_t = pi[pino].poc.ty1; } else { if (incr_top == 1) { if (tcp->tx0_t >= tcp->txE) { if (tcp->ty0_t >= tcp->tyE) { tcp->ty0_t = tcp->tyS; pi[pino].poc.ty0 = tcp->ty0_t; pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); tcp->ty0_t = pi[pino].poc.ty1; incr_top = 1; resetX = 1; } else { pi[pino].poc.ty0 = tcp->ty0_t; pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy); tcp->ty0_t = pi[pino].poc.ty1; incr_top = 0; resetX = 1; } if (resetX == 1) { tcp->tx0_t = tcp->txS; pi[pino].poc.tx0 = tcp->tx0_t; pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx); tcp->tx0_t = pi[pino].poc.tx1; } } else { pi[pino].poc.tx0 = tcp->tx0_t; pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx); tcp->tx0_t = pi[pino].poc.tx1; pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy); pi[pino].poc.ty1 = tcp->ty0_t ; incr_top = 0; } } else { pi[pino].poc.tx0 = tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx); pi[pino].poc.tx1 = tcp->tx0_t ; pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy); pi[pino].poc.ty1 = tcp->ty0_t ; } } } break; } break; } } } } return OPJ_FALSE; }
./CrossVul/dataset_final_sorted/CWE-369/c/good_538_0
crossvul-cpp_data_good_225_0
/* pngrutil.c - utilities to read a PNG file * * Last changed in libpng 1.6.35 [(PENDING RELEASE)] * Copyright (c) 1998-2002,2004,2006-2018 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * This file contains routines that are only called from within * libpng itself during the course of reading an image. */ #include "pngpriv.h" #ifdef PNG_READ_SUPPORTED png_uint_32 PNGAPI png_get_uint_31(png_const_structrp png_ptr, png_const_bytep buf) { png_uint_32 uval = png_get_uint_32(buf); if (uval > PNG_UINT_31_MAX) png_error(png_ptr, "PNG unsigned integer out of range"); return (uval); } #if defined(PNG_READ_gAMA_SUPPORTED) || defined(PNG_READ_cHRM_SUPPORTED) /* The following is a variation on the above for use with the fixed * point values used for gAMA and cHRM. Instead of png_error it * issues a warning and returns (-1) - an invalid value because both * gAMA and cHRM use *unsigned* integers for fixed point values. */ #define PNG_FIXED_ERROR (-1) static png_fixed_point /* PRIVATE */ png_get_fixed_point(png_structrp png_ptr, png_const_bytep buf) { png_uint_32 uval = png_get_uint_32(buf); if (uval <= PNG_UINT_31_MAX) return (png_fixed_point)uval; /* known to be in range */ /* The caller can turn off the warning by passing NULL. */ if (png_ptr != NULL) png_warning(png_ptr, "PNG fixed point integer out of range"); return PNG_FIXED_ERROR; } #endif #ifdef PNG_READ_INT_FUNCTIONS_SUPPORTED /* NOTE: the read macros will obscure these definitions, so that if * PNG_USE_READ_MACROS is set the library will not use them internally, * but the APIs will still be available externally. * * The parentheses around "PNGAPI function_name" in the following three * functions are necessary because they allow the macros to co-exist with * these (unused but exported) functions. */ /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */ png_uint_32 (PNGAPI png_get_uint_32)(png_const_bytep buf) { png_uint_32 uval = ((png_uint_32)(*(buf )) << 24) + ((png_uint_32)(*(buf + 1)) << 16) + ((png_uint_32)(*(buf + 2)) << 8) + ((png_uint_32)(*(buf + 3)) ) ; return uval; } /* Grab a signed 32-bit integer from a buffer in big-endian format. The * data is stored in the PNG file in two's complement format and there * is no guarantee that a 'png_int_32' is exactly 32 bits, therefore * the following code does a two's complement to native conversion. */ png_int_32 (PNGAPI png_get_int_32)(png_const_bytep buf) { png_uint_32 uval = png_get_uint_32(buf); if ((uval & 0x80000000) == 0) /* non-negative */ return (png_int_32)uval; uval = (uval ^ 0xffffffff) + 1; /* 2's complement: -x = ~x+1 */ if ((uval & 0x80000000) == 0) /* no overflow */ return -(png_int_32)uval; /* The following has to be safe; this function only gets called on PNG data * and if we get here that data is invalid. 0 is the most safe value and * if not then an attacker would surely just generate a PNG with 0 instead. */ return 0; } /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */ png_uint_16 (PNGAPI png_get_uint_16)(png_const_bytep buf) { /* ANSI-C requires an int value to accommodate at least 16 bits so this * works and allows the compiler not to worry about possible narrowing * on 32-bit systems. (Pre-ANSI systems did not make integers smaller * than 16 bits either.) */ unsigned int val = ((unsigned int)(*buf) << 8) + ((unsigned int)(*(buf + 1))); return (png_uint_16)val; } #endif /* READ_INT_FUNCTIONS */ /* Read and check the PNG file signature */ void /* PRIVATE */ png_read_sig(png_structrp png_ptr, png_inforp info_ptr) { size_t num_checked, num_to_check; /* Exit if the user application does not expect a signature. */ if (png_ptr->sig_bytes >= 8) return; num_checked = png_ptr->sig_bytes; num_to_check = 8 - num_checked; #ifdef PNG_IO_STATE_SUPPORTED png_ptr->io_state = PNG_IO_READING | PNG_IO_SIGNATURE; #endif /* The signature must be serialized in a single I/O call. */ png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check); png_ptr->sig_bytes = 8; if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check) != 0) { if (num_checked < 4 && png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4)) png_error(png_ptr, "Not a PNG file"); else png_error(png_ptr, "PNG file corrupted by ASCII conversion"); } if (num_checked < 3) png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE; } /* Read the chunk header (length + type name). * Put the type name into png_ptr->chunk_name, and return the length. */ png_uint_32 /* PRIVATE */ png_read_chunk_header(png_structrp png_ptr) { png_byte buf[8]; png_uint_32 length; #ifdef PNG_IO_STATE_SUPPORTED png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_HDR; #endif /* Read the length and the chunk name. * This must be performed in a single I/O call. */ png_read_data(png_ptr, buf, 8); length = png_get_uint_31(png_ptr, buf); /* Put the chunk name into png_ptr->chunk_name. */ png_ptr->chunk_name = PNG_CHUNK_FROM_STRING(buf+4); png_debug2(0, "Reading %lx chunk, length = %lu", (unsigned long)png_ptr->chunk_name, (unsigned long)length); /* Reset the crc and run it over the chunk name. */ png_reset_crc(png_ptr); png_calculate_crc(png_ptr, buf + 4, 4); /* Check to see if chunk name is valid. */ png_check_chunk_name(png_ptr, png_ptr->chunk_name); /* Check for too-large chunk length */ png_check_chunk_length(png_ptr, length); #ifdef PNG_IO_STATE_SUPPORTED png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_DATA; #endif return length; } /* Read data, and (optionally) run it through the CRC. */ void /* PRIVATE */ png_crc_read(png_structrp png_ptr, png_bytep buf, png_uint_32 length) { if (png_ptr == NULL) return; png_read_data(png_ptr, buf, length); png_calculate_crc(png_ptr, buf, length); } /* Optionally skip data and then check the CRC. Depending on whether we * are reading an ancillary or critical chunk, and how the program has set * things up, we may calculate the CRC on the data and print a message. * Returns '1' if there was a CRC error, '0' otherwise. */ int /* PRIVATE */ png_crc_finish(png_structrp png_ptr, png_uint_32 skip) { /* The size of the local buffer for inflate is a good guess as to a * reasonable size to use for buffering reads from the application. */ while (skip > 0) { png_uint_32 len; png_byte tmpbuf[PNG_INFLATE_BUF_SIZE]; len = (sizeof tmpbuf); if (len > skip) len = skip; skip -= len; png_crc_read(png_ptr, tmpbuf, len); } if (png_crc_error(png_ptr) != 0) { if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0 ? (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0 : (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE) != 0) { png_chunk_warning(png_ptr, "CRC error"); } else png_chunk_error(png_ptr, "CRC error"); return (1); } return (0); } /* Compare the CRC stored in the PNG file with that calculated by libpng from * the data it has read thus far. */ int /* PRIVATE */ png_crc_error(png_structrp png_ptr) { png_byte crc_bytes[4]; png_uint_32 crc; int need_crc = 1; if (PNG_CHUNK_ANCILLARY(png_ptr->chunk_name) != 0) { if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) == (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN)) need_crc = 0; } else /* critical */ { if ((png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE) != 0) need_crc = 0; } #ifdef PNG_IO_STATE_SUPPORTED png_ptr->io_state = PNG_IO_READING | PNG_IO_CHUNK_CRC; #endif /* The chunk CRC must be serialized in a single I/O call. */ png_read_data(png_ptr, crc_bytes, 4); if (need_crc != 0) { crc = png_get_uint_32(crc_bytes); return ((int)(crc != png_ptr->crc)); } else return (0); } #if defined(PNG_READ_iCCP_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) ||\ defined(PNG_READ_pCAL_SUPPORTED) || defined(PNG_READ_sCAL_SUPPORTED) ||\ defined(PNG_READ_sPLT_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) ||\ defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_SEQUENTIAL_READ_SUPPORTED) /* Manage the read buffer; this simply reallocates the buffer if it is not small * enough (or if it is not allocated). The routine returns a pointer to the * buffer; if an error occurs and 'warn' is set the routine returns NULL, else * it will call png_error (via png_malloc) on failure. (warn == 2 means * 'silent'). */ static png_bytep png_read_buffer(png_structrp png_ptr, png_alloc_size_t new_size, int warn) { png_bytep buffer = png_ptr->read_buffer; if (buffer != NULL && new_size > png_ptr->read_buffer_size) { png_ptr->read_buffer = NULL; png_ptr->read_buffer = NULL; png_ptr->read_buffer_size = 0; png_free(png_ptr, buffer); buffer = NULL; } if (buffer == NULL) { buffer = png_voidcast(png_bytep, png_malloc_base(png_ptr, new_size)); if (buffer != NULL) { memset(buffer, 0, new_size); /* just in case */ png_ptr->read_buffer = buffer; png_ptr->read_buffer_size = new_size; } else if (warn < 2) /* else silent */ { if (warn != 0) png_chunk_warning(png_ptr, "insufficient memory to read chunk"); else png_chunk_error(png_ptr, "insufficient memory to read chunk"); } } return buffer; } #endif /* READ_iCCP|iTXt|pCAL|sCAL|sPLT|tEXt|zTXt|SEQUENTIAL_READ */ /* png_inflate_claim: claim the zstream for some nefarious purpose that involves * decompression. Returns Z_OK on success, else a zlib error code. It checks * the owner but, in final release builds, just issues a warning if some other * chunk apparently owns the stream. Prior to release it does a png_error. */ static int png_inflate_claim(png_structrp png_ptr, png_uint_32 owner) { if (png_ptr->zowner != 0) { char msg[64]; PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner); /* So the message that results is "<chunk> using zstream"; this is an * internal error, but is very useful for debugging. i18n requirements * are minimal. */ (void)png_safecat(msg, (sizeof msg), 4, " using zstream"); #if PNG_RELEASE_BUILD png_chunk_warning(png_ptr, msg); png_ptr->zowner = 0; #else png_chunk_error(png_ptr, msg); #endif } /* Implementation note: unlike 'png_deflate_claim' this internal function * does not take the size of the data as an argument. Some efficiency could * be gained by using this when it is known *if* the zlib stream itself does * not record the number; however, this is an illusion: the original writer * of the PNG may have selected a lower window size, and we really must * follow that because, for systems with with limited capabilities, we * would otherwise reject the application's attempts to use a smaller window * size (zlib doesn't have an interface to say "this or lower"!). * * inflateReset2 was added to zlib 1.2.4; before this the window could not be * reset, therefore it is necessary to always allocate the maximum window * size with earlier zlibs just in case later compressed chunks need it. */ { int ret; /* zlib return code */ #if ZLIB_VERNUM >= 0x1240 int window_bits = 0; # if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW) if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) == PNG_OPTION_ON) { window_bits = 15; png_ptr->zstream_start = 0; /* fixed window size */ } else { png_ptr->zstream_start = 1; } # endif #endif /* ZLIB_VERNUM >= 0x1240 */ /* Set this for safety, just in case the previous owner left pointers to * memory allocations. */ png_ptr->zstream.next_in = NULL; png_ptr->zstream.avail_in = 0; png_ptr->zstream.next_out = NULL; png_ptr->zstream.avail_out = 0; if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0) { #if ZLIB_VERNUM >= 0x1240 ret = inflateReset2(&png_ptr->zstream, window_bits); #else ret = inflateReset(&png_ptr->zstream); #endif } else { #if ZLIB_VERNUM >= 0x1240 ret = inflateInit2(&png_ptr->zstream, window_bits); #else ret = inflateInit(&png_ptr->zstream); #endif if (ret == Z_OK) png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED; } #if ZLIB_VERNUM >= 0x1290 && \ defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_IGNORE_ADLER32) if (((png_ptr->options >> PNG_IGNORE_ADLER32) & 3) == PNG_OPTION_ON) /* Turn off validation of the ADLER32 checksum in IDAT chunks */ ret = inflateValidate(&png_ptr->zstream, 0); #endif if (ret == Z_OK) png_ptr->zowner = owner; else png_zstream_error(png_ptr, ret); return ret; } #ifdef window_bits # undef window_bits #endif } #if ZLIB_VERNUM >= 0x1240 /* Handle the start of the inflate stream if we called inflateInit2(strm,0); * in this case some zlib versions skip validation of the CINFO field and, in * certain circumstances, libpng may end up displaying an invalid image, in * contrast to implementations that call zlib in the normal way (e.g. libpng * 1.5). */ int /* PRIVATE */ png_zlib_inflate(png_structrp png_ptr, int flush) { if (png_ptr->zstream_start && png_ptr->zstream.avail_in > 0) { if ((*png_ptr->zstream.next_in >> 4) > 7) { png_ptr->zstream.msg = "invalid window size (libpng)"; return Z_DATA_ERROR; } png_ptr->zstream_start = 0; } return inflate(&png_ptr->zstream, flush); } #endif /* Zlib >= 1.2.4 */ #ifdef PNG_READ_COMPRESSED_TEXT_SUPPORTED #if defined(PNG_READ_zTXt_SUPPORTED) || defined (PNG_READ_iTXt_SUPPORTED) /* png_inflate now returns zlib error codes including Z_OK and Z_STREAM_END to * allow the caller to do multiple calls if required. If the 'finish' flag is * set Z_FINISH will be passed to the final inflate() call and Z_STREAM_END must * be returned or there has been a problem, otherwise Z_SYNC_FLUSH is used and * Z_OK or Z_STREAM_END will be returned on success. * * The input and output sizes are updated to the actual amounts of data consumed * or written, not the amount available (as in a z_stream). The data pointers * are not changed, so the next input is (data+input_size) and the next * available output is (output+output_size). */ static int png_inflate(png_structrp png_ptr, png_uint_32 owner, int finish, /* INPUT: */ png_const_bytep input, png_uint_32p input_size_ptr, /* OUTPUT: */ png_bytep output, png_alloc_size_t *output_size_ptr) { if (png_ptr->zowner == owner) /* Else not claimed */ { int ret; png_alloc_size_t avail_out = *output_size_ptr; png_uint_32 avail_in = *input_size_ptr; /* zlib can't necessarily handle more than 65535 bytes at once (i.e. it * can't even necessarily handle 65536 bytes) because the type uInt is * "16 bits or more". Consequently it is necessary to chunk the input to * zlib. This code uses ZLIB_IO_MAX, from pngpriv.h, as the maximum (the * maximum value that can be stored in a uInt.) It is possible to set * ZLIB_IO_MAX to a lower value in pngpriv.h and this may sometimes have * a performance advantage, because it reduces the amount of data accessed * at each step and that may give the OS more time to page it in. */ png_ptr->zstream.next_in = PNGZ_INPUT_CAST(input); /* avail_in and avail_out are set below from 'size' */ png_ptr->zstream.avail_in = 0; png_ptr->zstream.avail_out = 0; /* Read directly into the output if it is available (this is set to * a local buffer below if output is NULL). */ if (output != NULL) png_ptr->zstream.next_out = output; do { uInt avail; Byte local_buffer[PNG_INFLATE_BUF_SIZE]; /* zlib INPUT BUFFER */ /* The setting of 'avail_in' used to be outside the loop; by setting it * inside it is possible to chunk the input to zlib and simply rely on * zlib to advance the 'next_in' pointer. This allows arbitrary * amounts of data to be passed through zlib at the unavoidable cost of * requiring a window save (memcpy of up to 32768 output bytes) * every ZLIB_IO_MAX input bytes. */ avail_in += png_ptr->zstream.avail_in; /* not consumed last time */ avail = ZLIB_IO_MAX; if (avail_in < avail) avail = (uInt)avail_in; /* safe: < than ZLIB_IO_MAX */ avail_in -= avail; png_ptr->zstream.avail_in = avail; /* zlib OUTPUT BUFFER */ avail_out += png_ptr->zstream.avail_out; /* not written last time */ avail = ZLIB_IO_MAX; /* maximum zlib can process */ if (output == NULL) { /* Reset the output buffer each time round if output is NULL and * make available the full buffer, up to 'remaining_space' */ png_ptr->zstream.next_out = local_buffer; if ((sizeof local_buffer) < avail) avail = (sizeof local_buffer); } if (avail_out < avail) avail = (uInt)avail_out; /* safe: < ZLIB_IO_MAX */ png_ptr->zstream.avail_out = avail; avail_out -= avail; /* zlib inflate call */ /* In fact 'avail_out' may be 0 at this point, that happens at the end * of the read when the final LZ end code was not passed at the end of * the previous chunk of input data. Tell zlib if we have reached the * end of the output buffer. */ ret = PNG_INFLATE(png_ptr, avail_out > 0 ? Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH)); } while (ret == Z_OK); /* For safety kill the local buffer pointer now */ if (output == NULL) png_ptr->zstream.next_out = NULL; /* Claw back the 'size' and 'remaining_space' byte counts. */ avail_in += png_ptr->zstream.avail_in; avail_out += png_ptr->zstream.avail_out; /* Update the input and output sizes; the updated values are the amount * consumed or written, effectively the inverse of what zlib uses. */ if (avail_out > 0) *output_size_ptr -= avail_out; if (avail_in > 0) *input_size_ptr -= avail_in; /* Ensure png_ptr->zstream.msg is set (even in the success case!) */ png_zstream_error(png_ptr, ret); return ret; } else { /* This is a bad internal error. The recovery assigns to the zstream msg * pointer, which is not owned by the caller, but this is safe; it's only * used on errors! */ png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed"); return Z_STREAM_ERROR; } } /* * Decompress trailing data in a chunk. The assumption is that read_buffer * points at an allocated area holding the contents of a chunk with a * trailing compressed part. What we get back is an allocated area * holding the original prefix part and an uncompressed version of the * trailing part (the malloc area passed in is freed). */ static int png_decompress_chunk(png_structrp png_ptr, png_uint_32 chunklength, png_uint_32 prefix_size, png_alloc_size_t *newlength /* must be initialized to the maximum! */, int terminate /*add a '\0' to the end of the uncompressed data*/) { /* TODO: implement different limits for different types of chunk. * * The caller supplies *newlength set to the maximum length of the * uncompressed data, but this routine allocates space for the prefix and * maybe a '\0' terminator too. We have to assume that 'prefix_size' is * limited only by the maximum chunk size. */ png_alloc_size_t limit = PNG_SIZE_MAX; # ifdef PNG_SET_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_malloc_max > 0 && png_ptr->user_chunk_malloc_max < limit) limit = png_ptr->user_chunk_malloc_max; # elif PNG_USER_CHUNK_MALLOC_MAX > 0 if (PNG_USER_CHUNK_MALLOC_MAX < limit) limit = PNG_USER_CHUNK_MALLOC_MAX; # endif if (limit >= prefix_size + (terminate != 0)) { int ret; limit -= prefix_size + (terminate != 0); if (limit < *newlength) *newlength = limit; /* Now try to claim the stream. */ ret = png_inflate_claim(png_ptr, png_ptr->chunk_name); if (ret == Z_OK) { png_uint_32 lzsize = chunklength - prefix_size; ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/, /* input: */ png_ptr->read_buffer + prefix_size, &lzsize, /* output: */ NULL, newlength); if (ret == Z_STREAM_END) { /* Use 'inflateReset' here, not 'inflateReset2' because this * preserves the previously decided window size (otherwise it would * be necessary to store the previous window size.) In practice * this doesn't matter anyway, because png_inflate will call inflate * with Z_FINISH in almost all cases, so the window will not be * maintained. */ if (inflateReset(&png_ptr->zstream) == Z_OK) { /* Because of the limit checks above we know that the new, * expanded, size will fit in a size_t (let alone an * png_alloc_size_t). Use png_malloc_base here to avoid an * extra OOM message. */ png_alloc_size_t new_size = *newlength; png_alloc_size_t buffer_size = prefix_size + new_size + (terminate != 0); png_bytep text = png_voidcast(png_bytep, png_malloc_base(png_ptr, buffer_size)); if (text != NULL) { memset(text, 0, buffer_size); ret = png_inflate(png_ptr, png_ptr->chunk_name, 1/*finish*/, png_ptr->read_buffer + prefix_size, &lzsize, text + prefix_size, newlength); if (ret == Z_STREAM_END) { if (new_size == *newlength) { if (terminate != 0) text[prefix_size + *newlength] = 0; if (prefix_size > 0) memcpy(text, png_ptr->read_buffer, prefix_size); { png_bytep old_ptr = png_ptr->read_buffer; png_ptr->read_buffer = text; png_ptr->read_buffer_size = buffer_size; text = old_ptr; /* freed below */ } } else { /* The size changed on the second read, there can be no * guarantee that anything is correct at this point. * The 'msg' pointer has been set to "unexpected end of * LZ stream", which is fine, but return an error code * that the caller won't accept. */ ret = PNG_UNEXPECTED_ZLIB_RETURN; } } else if (ret == Z_OK) ret = PNG_UNEXPECTED_ZLIB_RETURN; /* for safety */ /* Free the text pointer (this is the old read_buffer on * success) */ png_free(png_ptr, text); /* This really is very benign, but it's still an error because * the extra space may otherwise be used as a Trojan Horse. */ if (ret == Z_STREAM_END && chunklength - prefix_size != lzsize) png_chunk_benign_error(png_ptr, "extra compressed data"); } else { /* Out of memory allocating the buffer */ ret = Z_MEM_ERROR; png_zstream_error(png_ptr, Z_MEM_ERROR); } } else { /* inflateReset failed, store the error message */ png_zstream_error(png_ptr, ret); ret = PNG_UNEXPECTED_ZLIB_RETURN; } } else if (ret == Z_OK) ret = PNG_UNEXPECTED_ZLIB_RETURN; /* Release the claimed stream */ png_ptr->zowner = 0; } else /* the claim failed */ if (ret == Z_STREAM_END) /* impossible! */ ret = PNG_UNEXPECTED_ZLIB_RETURN; return ret; } else { /* Application/configuration limits exceeded */ png_zstream_error(png_ptr, Z_MEM_ERROR); return Z_MEM_ERROR; } } #endif /* READ_zTXt || READ_iTXt */ #endif /* READ_COMPRESSED_TEXT */ #ifdef PNG_READ_iCCP_SUPPORTED /* Perform a partial read and decompress, producing 'avail_out' bytes and * reading from the current chunk as required. */ static int png_inflate_read(png_structrp png_ptr, png_bytep read_buffer, uInt read_size, png_uint_32p chunk_bytes, png_bytep next_out, png_alloc_size_t *out_size, int finish) { if (png_ptr->zowner == png_ptr->chunk_name) { int ret; /* next_in and avail_in must have been initialized by the caller. */ png_ptr->zstream.next_out = next_out; png_ptr->zstream.avail_out = 0; /* set in the loop */ do { if (png_ptr->zstream.avail_in == 0) { if (read_size > *chunk_bytes) read_size = (uInt)*chunk_bytes; *chunk_bytes -= read_size; if (read_size > 0) png_crc_read(png_ptr, read_buffer, read_size); png_ptr->zstream.next_in = read_buffer; png_ptr->zstream.avail_in = read_size; } if (png_ptr->zstream.avail_out == 0) { uInt avail = ZLIB_IO_MAX; if (avail > *out_size) avail = (uInt)*out_size; *out_size -= avail; png_ptr->zstream.avail_out = avail; } /* Use Z_SYNC_FLUSH when there is no more chunk data to ensure that all * the available output is produced; this allows reading of truncated * streams. */ ret = PNG_INFLATE(png_ptr, *chunk_bytes > 0 ? Z_NO_FLUSH : (finish ? Z_FINISH : Z_SYNC_FLUSH)); } while (ret == Z_OK && (*out_size > 0 || png_ptr->zstream.avail_out > 0)); *out_size += png_ptr->zstream.avail_out; png_ptr->zstream.avail_out = 0; /* Should not be required, but is safe */ /* Ensure the error message pointer is always set: */ png_zstream_error(png_ptr, ret); return ret; } else { png_ptr->zstream.msg = PNGZ_MSG_CAST("zstream unclaimed"); return Z_STREAM_ERROR; } } #endif /* READ_iCCP */ /* Read and check the IDHR chunk */ void /* PRIVATE */ png_handle_IHDR(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[13]; png_uint_32 width, height; int bit_depth, color_type, compression_type, filter_type; int interlace_type; png_debug(1, "in png_handle_IHDR"); if ((png_ptr->mode & PNG_HAVE_IHDR) != 0) png_chunk_error(png_ptr, "out of place"); /* Check the length */ if (length != 13) png_chunk_error(png_ptr, "invalid"); png_ptr->mode |= PNG_HAVE_IHDR; png_crc_read(png_ptr, buf, 13); png_crc_finish(png_ptr, 0); width = png_get_uint_31(png_ptr, buf); height = png_get_uint_31(png_ptr, buf + 4); bit_depth = buf[8]; color_type = buf[9]; compression_type = buf[10]; filter_type = buf[11]; interlace_type = buf[12]; /* Set internal variables */ png_ptr->width = width; png_ptr->height = height; png_ptr->bit_depth = (png_byte)bit_depth; png_ptr->interlaced = (png_byte)interlace_type; png_ptr->color_type = (png_byte)color_type; #ifdef PNG_MNG_FEATURES_SUPPORTED png_ptr->filter_type = (png_byte)filter_type; #endif png_ptr->compression_type = (png_byte)compression_type; /* Find number of channels */ switch (png_ptr->color_type) { default: /* invalid, png_set_IHDR calls png_error */ case PNG_COLOR_TYPE_GRAY: case PNG_COLOR_TYPE_PALETTE: png_ptr->channels = 1; break; case PNG_COLOR_TYPE_RGB: png_ptr->channels = 3; break; case PNG_COLOR_TYPE_GRAY_ALPHA: png_ptr->channels = 2; break; case PNG_COLOR_TYPE_RGB_ALPHA: png_ptr->channels = 4; break; } /* Set up other useful info */ png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth * png_ptr->channels); png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->width); png_debug1(3, "bit_depth = %d", png_ptr->bit_depth); png_debug1(3, "channels = %d", png_ptr->channels); png_debug1(3, "rowbytes = %lu", (unsigned long)png_ptr->rowbytes); png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type, interlace_type, compression_type, filter_type); } /* Read and check the palette */ void /* PRIVATE */ png_handle_PLTE(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_color palette[PNG_MAX_PALETTE_LENGTH]; int max_palette_length, num, i; #ifdef PNG_POINTER_INDEXING_SUPPORTED png_colorp pal_ptr; #endif png_debug(1, "in png_handle_PLTE"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); /* Moved to before the 'after IDAT' check below because otherwise duplicate * PLTE chunks are potentially ignored (the spec says there shall not be more * than one PLTE, the error is not treated as benign, so this check trumps * the requirement that PLTE appears before IDAT.) */ else if ((png_ptr->mode & PNG_HAVE_PLTE) != 0) png_chunk_error(png_ptr, "duplicate"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { /* This is benign because the non-benign error happened before, when an * IDAT was encountered in a color-mapped image with no PLTE. */ png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } png_ptr->mode |= PNG_HAVE_PLTE; if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "ignored in grayscale PNG"); return; } #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) { png_crc_finish(png_ptr, length); return; } #endif if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3) { png_crc_finish(png_ptr, length); if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE) png_chunk_benign_error(png_ptr, "invalid"); else png_chunk_error(png_ptr, "invalid"); return; } /* The cast is safe because 'length' is less than 3*PNG_MAX_PALETTE_LENGTH */ num = (int)length / 3; /* If the palette has 256 or fewer entries but is too large for the bit * depth, we don't issue an error, to preserve the behavior of previous * libpng versions. We silently truncate the unused extra palette entries * here. */ if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) max_palette_length = (1 << png_ptr->bit_depth); else max_palette_length = PNG_MAX_PALETTE_LENGTH; if (num > max_palette_length) num = max_palette_length; #ifdef PNG_POINTER_INDEXING_SUPPORTED for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); pal_ptr->red = buf[0]; pal_ptr->green = buf[1]; pal_ptr->blue = buf[2]; } #else for (i = 0; i < num; i++) { png_byte buf[3]; png_crc_read(png_ptr, buf, 3); /* Don't depend upon png_color being any order */ palette[i].red = buf[0]; palette[i].green = buf[1]; palette[i].blue = buf[2]; } #endif /* If we actually need the PLTE chunk (ie for a paletted image), we do * whatever the normal CRC configuration tells us. However, if we * have an RGB image, the PLTE can be considered ancillary, so * we will act as though it is. */ #ifndef PNG_READ_OPT_PLTE_SUPPORTED if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) #endif { png_crc_finish(png_ptr, (png_uint_32) (length - (unsigned int)num * 3)); } #ifndef PNG_READ_OPT_PLTE_SUPPORTED else if (png_crc_error(png_ptr) != 0) /* Only if we have a CRC error */ { /* If we don't want to use the data from an ancillary chunk, * we have two options: an error abort, or a warning and we * ignore the data in this chunk (which should be OK, since * it's considered ancillary for a RGB or RGBA image). * * IMPLEMENTATION NOTE: this is only here because png_crc_finish uses the * chunk type to determine whether to check the ancillary or the critical * flags. */ if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE) == 0) { if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) != 0) return; else png_chunk_error(png_ptr, "CRC error"); } /* Otherwise, we (optionally) emit a warning and use the chunk. */ else if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN) == 0) png_chunk_warning(png_ptr, "CRC error"); } #endif /* TODO: png_set_PLTE has the side effect of setting png_ptr->palette to its * own copy of the palette. This has the side effect that when png_start_row * is called (this happens after any call to png_read_update_info) the * info_ptr palette gets changed. This is extremely unexpected and * confusing. * * Fix this by not sharing the palette in this way. */ png_set_PLTE(png_ptr, info_ptr, palette, num); /* The three chunks, bKGD, hIST and tRNS *must* appear after PLTE and before * IDAT. Prior to 1.6.0 this was not checked; instead the code merely * checked the apparent validity of a tRNS chunk inserted before PLTE on a * palette PNG. 1.6.0 attempts to rigorously follow the standard and * therefore does a benign error if the erroneous condition is detected *and* * cancels the tRNS if the benign error returns. The alternative is to * amend the standard since it would be rather hypocritical of the standards * maintainers to ignore it. */ #ifdef PNG_READ_tRNS_SUPPORTED if (png_ptr->num_trans > 0 || (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0)) { /* Cancel this because otherwise it would be used if the transforms * require it. Don't cancel the 'valid' flag because this would prevent * detection of duplicate chunks. */ png_ptr->num_trans = 0; if (info_ptr != NULL) info_ptr->num_trans = 0; png_chunk_benign_error(png_ptr, "tRNS must be after"); } #endif #ifdef PNG_READ_hIST_SUPPORTED if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0) png_chunk_benign_error(png_ptr, "hIST must be after"); #endif #ifdef PNG_READ_bKGD_SUPPORTED if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0) png_chunk_benign_error(png_ptr, "bKGD must be after"); #endif } void /* PRIVATE */ png_handle_IEND(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_debug(1, "in png_handle_IEND"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0 || (png_ptr->mode & PNG_HAVE_IDAT) == 0) png_chunk_error(png_ptr, "out of place"); png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND); png_crc_finish(png_ptr, length); if (length != 0) png_chunk_benign_error(png_ptr, "invalid"); PNG_UNUSED(info_ptr) } #ifdef PNG_READ_gAMA_SUPPORTED void /* PRIVATE */ png_handle_gAMA(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_fixed_point igamma; png_byte buf[4]; png_debug(1, "in png_handle_gAMA"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } if (length != 4) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 4); if (png_crc_finish(png_ptr, 0) != 0) return; igamma = png_get_fixed_point(NULL, buf); png_colorspace_set_gamma(png_ptr, &png_ptr->colorspace, igamma); png_colorspace_sync(png_ptr, info_ptr); } #endif #ifdef PNG_READ_sBIT_SUPPORTED void /* PRIVATE */ png_handle_sBIT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { unsigned int truelen, i; png_byte sample_depth; png_byte buf[4]; png_debug(1, "in png_handle_sBIT"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { truelen = 3; sample_depth = 8; } else { truelen = png_ptr->channels; sample_depth = png_ptr->bit_depth; } if (length != truelen || length > 4) { png_chunk_benign_error(png_ptr, "invalid"); png_crc_finish(png_ptr, length); return; } buf[0] = buf[1] = buf[2] = buf[3] = sample_depth; png_crc_read(png_ptr, buf, truelen); if (png_crc_finish(png_ptr, 0) != 0) return; for (i=0; i<truelen; ++i) { if (buf[i] == 0 || buf[i] > sample_depth) { png_chunk_benign_error(png_ptr, "invalid"); return; } } if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0) { png_ptr->sig_bit.red = buf[0]; png_ptr->sig_bit.green = buf[1]; png_ptr->sig_bit.blue = buf[2]; png_ptr->sig_bit.alpha = buf[3]; } else { png_ptr->sig_bit.gray = buf[0]; png_ptr->sig_bit.red = buf[0]; png_ptr->sig_bit.green = buf[0]; png_ptr->sig_bit.blue = buf[0]; png_ptr->sig_bit.alpha = buf[1]; } png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit)); } #endif #ifdef PNG_READ_cHRM_SUPPORTED void /* PRIVATE */ png_handle_cHRM(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[32]; png_xy xy; png_debug(1, "in png_handle_cHRM"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } if (length != 32) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 32); if (png_crc_finish(png_ptr, 0) != 0) return; xy.whitex = png_get_fixed_point(NULL, buf); xy.whitey = png_get_fixed_point(NULL, buf + 4); xy.redx = png_get_fixed_point(NULL, buf + 8); xy.redy = png_get_fixed_point(NULL, buf + 12); xy.greenx = png_get_fixed_point(NULL, buf + 16); xy.greeny = png_get_fixed_point(NULL, buf + 20); xy.bluex = png_get_fixed_point(NULL, buf + 24); xy.bluey = png_get_fixed_point(NULL, buf + 28); if (xy.whitex == PNG_FIXED_ERROR || xy.whitey == PNG_FIXED_ERROR || xy.redx == PNG_FIXED_ERROR || xy.redy == PNG_FIXED_ERROR || xy.greenx == PNG_FIXED_ERROR || xy.greeny == PNG_FIXED_ERROR || xy.bluex == PNG_FIXED_ERROR || xy.bluey == PNG_FIXED_ERROR) { png_chunk_benign_error(png_ptr, "invalid values"); return; } /* If a colorspace error has already been output skip this chunk */ if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0) return; if ((png_ptr->colorspace.flags & PNG_COLORSPACE_FROM_cHRM) != 0) { png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID; png_colorspace_sync(png_ptr, info_ptr); png_chunk_benign_error(png_ptr, "duplicate"); return; } png_ptr->colorspace.flags |= PNG_COLORSPACE_FROM_cHRM; (void)png_colorspace_set_chromaticities(png_ptr, &png_ptr->colorspace, &xy, 1/*prefer cHRM values*/); png_colorspace_sync(png_ptr, info_ptr); } #endif #ifdef PNG_READ_sRGB_SUPPORTED void /* PRIVATE */ png_handle_sRGB(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte intent; png_debug(1, "in png_handle_sRGB"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } if (length != 1) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, &intent, 1); if (png_crc_finish(png_ptr, 0) != 0) return; /* If a colorspace error has already been output skip this chunk */ if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0) return; /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect * this. */ if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) != 0) { png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID; png_colorspace_sync(png_ptr, info_ptr); png_chunk_benign_error(png_ptr, "too many profiles"); return; } (void)png_colorspace_set_sRGB(png_ptr, &png_ptr->colorspace, intent); png_colorspace_sync(png_ptr, info_ptr); } #endif /* READ_sRGB */ #ifdef PNG_READ_iCCP_SUPPORTED void /* PRIVATE */ png_handle_iCCP(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) /* Note: this does not properly handle profiles that are > 64K under DOS */ { png_const_charp errmsg = NULL; /* error message output, or no error */ int finished = 0; /* crc checked */ png_debug(1, "in png_handle_iCCP"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & (PNG_HAVE_IDAT|PNG_HAVE_PLTE)) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } /* Consistent with all the above colorspace handling an obviously *invalid* * chunk is just ignored, so does not invalidate the color space. An * alternative is to set the 'invalid' flags at the start of this routine * and only clear them in they were not set before and all the tests pass. */ /* The keyword must be at least one character and there is a * terminator (0) byte and the compression method byte, and the * 'zlib' datastream is at least 11 bytes. */ if (length < 14) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "too short"); return; } /* If a colorspace error has already been output skip this chunk */ if ((png_ptr->colorspace.flags & PNG_COLORSPACE_INVALID) != 0) { png_crc_finish(png_ptr, length); return; } /* Only one sRGB or iCCP chunk is allowed, use the HAVE_INTENT flag to detect * this. */ if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_INTENT) == 0) { uInt read_length, keyword_length; char keyword[81]; /* Find the keyword; the keyword plus separator and compression method * bytes can be at most 81 characters long. */ read_length = 81; /* maximum */ if (read_length > length) read_length = (uInt)length; png_crc_read(png_ptr, (png_bytep)keyword, read_length); length -= read_length; /* The minimum 'zlib' stream is assumed to be just the 2 byte header, * 5 bytes minimum 'deflate' stream, and the 4 byte checksum. */ if (length < 11) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "too short"); return; } keyword_length = 0; while (keyword_length < 80 && keyword_length < read_length && keyword[keyword_length] != 0) ++keyword_length; /* TODO: make the keyword checking common */ if (keyword_length >= 1 && keyword_length <= 79) { /* We only understand '0' compression - deflate - so if we get a * different value we can't safely decode the chunk. */ if (keyword_length+1 < read_length && keyword[keyword_length+1] == PNG_COMPRESSION_TYPE_BASE) { read_length -= keyword_length+2; if (png_inflate_claim(png_ptr, png_iCCP) == Z_OK) { Byte profile_header[132]={0}; Byte local_buffer[PNG_INFLATE_BUF_SIZE]; png_alloc_size_t size = (sizeof profile_header); png_ptr->zstream.next_in = (Bytef*)keyword + (keyword_length+2); png_ptr->zstream.avail_in = read_length; (void)png_inflate_read(png_ptr, local_buffer, (sizeof local_buffer), &length, profile_header, &size, 0/*finish: don't, because the output is too small*/); if (size == 0) { /* We have the ICC profile header; do the basic header checks. */ const png_uint_32 profile_length = png_get_uint_32(profile_header); if (png_icc_check_length(png_ptr, &png_ptr->colorspace, keyword, profile_length) != 0) { /* The length is apparently ok, so we can check the 132 * byte header. */ if (png_icc_check_header(png_ptr, &png_ptr->colorspace, keyword, profile_length, profile_header, png_ptr->color_type) != 0) { /* Now read the tag table; a variable size buffer is * needed at this point, allocate one for the whole * profile. The header check has already validated * that none of this stuff will overflow. */ const png_uint_32 tag_count = png_get_uint_32( profile_header+128); png_bytep profile = png_read_buffer(png_ptr, profile_length, 2/*silent*/); if (profile != NULL) { memcpy(profile, profile_header, (sizeof profile_header)); size = 12 * tag_count; (void)png_inflate_read(png_ptr, local_buffer, (sizeof local_buffer), &length, profile + (sizeof profile_header), &size, 0); /* Still expect a buffer error because we expect * there to be some tag data! */ if (size == 0) { if (png_icc_check_tag_table(png_ptr, &png_ptr->colorspace, keyword, profile_length, profile) != 0) { /* The profile has been validated for basic * security issues, so read the whole thing in. */ size = profile_length - (sizeof profile_header) - 12 * tag_count; (void)png_inflate_read(png_ptr, local_buffer, (sizeof local_buffer), &length, profile + (sizeof profile_header) + 12 * tag_count, &size, 1/*finish*/); if (length > 0 && !(png_ptr->flags & PNG_FLAG_BENIGN_ERRORS_WARN)) errmsg = "extra compressed data"; /* But otherwise allow extra data: */ else if (size == 0) { if (length > 0) { /* This can be handled completely, so * keep going. */ png_chunk_warning(png_ptr, "extra compressed data"); } png_crc_finish(png_ptr, length); finished = 1; # if defined(PNG_sRGB_SUPPORTED) && PNG_sRGB_PROFILE_CHECKS >= 0 /* Check for a match against sRGB */ png_icc_set_sRGB(png_ptr, &png_ptr->colorspace, profile, png_ptr->zstream.adler); # endif /* Steal the profile for info_ptr. */ if (info_ptr != NULL) { png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0); info_ptr->iccp_name = png_voidcast(char*, png_malloc_base(png_ptr, keyword_length+1)); if (info_ptr->iccp_name != NULL) { memcpy(info_ptr->iccp_name, keyword, keyword_length+1); info_ptr->iccp_proflen = profile_length; info_ptr->iccp_profile = profile; png_ptr->read_buffer = NULL; /*steal*/ info_ptr->free_me |= PNG_FREE_ICCP; info_ptr->valid |= PNG_INFO_iCCP; } else { png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID; errmsg = "out of memory"; } } /* else the profile remains in the read * buffer which gets reused for subsequent * chunks. */ if (info_ptr != NULL) png_colorspace_sync(png_ptr, info_ptr); if (errmsg == NULL) { png_ptr->zowner = 0; return; } } if (errmsg == NULL) errmsg = png_ptr->zstream.msg; } /* else png_icc_check_tag_table output an error */ } else /* profile truncated */ errmsg = png_ptr->zstream.msg; } else errmsg = "out of memory"; } /* else png_icc_check_header output an error */ } /* else png_icc_check_length output an error */ } else /* profile truncated */ errmsg = png_ptr->zstream.msg; /* Release the stream */ png_ptr->zowner = 0; } else /* png_inflate_claim failed */ errmsg = png_ptr->zstream.msg; } else errmsg = "bad compression method"; /* or missing */ } else errmsg = "bad keyword"; } else errmsg = "too many profiles"; /* Failure: the reason is in 'errmsg' */ if (finished == 0) png_crc_finish(png_ptr, length); png_ptr->colorspace.flags |= PNG_COLORSPACE_INVALID; png_colorspace_sync(png_ptr, info_ptr); if (errmsg != NULL) /* else already output */ png_chunk_benign_error(png_ptr, errmsg); } #endif /* READ_iCCP */ #ifdef PNG_READ_sPLT_SUPPORTED void /* PRIVATE */ png_handle_sPLT(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) /* Note: this does not properly handle chunks that are > 64K under DOS */ { png_bytep entry_start, buffer; png_sPLT_t new_palette; png_sPLT_entryp pp; png_uint_32 data_length; int entry_size, i; png_uint_32 skip = 0; png_uint_32 dl; size_t max_dl; png_debug(1, "in png_handle_sPLT"); #ifdef PNG_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_cache_max != 0) { if (png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); return; } if (--png_ptr->user_chunk_cache_max == 1) { png_warning(png_ptr, "No space in chunk cache for sPLT"); png_crc_finish(png_ptr, length); return; } } #endif if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } #ifdef PNG_MAX_MALLOC_64K if (length > 65535U) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "too large to fit in memory"); return; } #endif buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/); if (buffer == NULL) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of memory"); return; } /* WARNING: this may break if size_t is less than 32 bits; it is assumed * that the PNG_MAX_MALLOC_64K test is enabled in this case, but this is a * potential breakage point if the types in pngconf.h aren't exactly right. */ png_crc_read(png_ptr, buffer, length); if (png_crc_finish(png_ptr, skip) != 0) return; buffer[length] = 0; for (entry_start = buffer; *entry_start; entry_start++) /* Empty loop to find end of name */ ; ++entry_start; /* A sample depth should follow the separator, and we should be on it */ if (length < 2U || entry_start > buffer + (length - 2U)) { png_warning(png_ptr, "malformed sPLT chunk"); return; } new_palette.depth = *entry_start++; entry_size = (new_palette.depth == 8 ? 6 : 10); /* This must fit in a png_uint_32 because it is derived from the original * chunk data length. */ data_length = length - (png_uint_32)(entry_start - buffer); /* Integrity-check the data length */ if ((data_length % (unsigned int)entry_size) != 0) { png_warning(png_ptr, "sPLT chunk has bad length"); return; } dl = (png_uint_32)(data_length / (unsigned int)entry_size); max_dl = PNG_SIZE_MAX / (sizeof (png_sPLT_entry)); if (dl > max_dl) { png_warning(png_ptr, "sPLT chunk too long"); return; } new_palette.nentries = (png_int_32)(data_length / (unsigned int)entry_size); new_palette.entries = (png_sPLT_entryp)png_malloc_warn(png_ptr, (png_alloc_size_t) new_palette.nentries * (sizeof (png_sPLT_entry))); if (new_palette.entries == NULL) { png_warning(png_ptr, "sPLT chunk requires too much memory"); return; } #ifdef PNG_POINTER_INDEXING_SUPPORTED for (i = 0; i < new_palette.nentries; i++) { pp = new_palette.entries + i; if (new_palette.depth == 8) { pp->red = *entry_start++; pp->green = *entry_start++; pp->blue = *entry_start++; pp->alpha = *entry_start++; } else { pp->red = png_get_uint_16(entry_start); entry_start += 2; pp->green = png_get_uint_16(entry_start); entry_start += 2; pp->blue = png_get_uint_16(entry_start); entry_start += 2; pp->alpha = png_get_uint_16(entry_start); entry_start += 2; } pp->frequency = png_get_uint_16(entry_start); entry_start += 2; } #else pp = new_palette.entries; for (i = 0; i < new_palette.nentries; i++) { if (new_palette.depth == 8) { pp[i].red = *entry_start++; pp[i].green = *entry_start++; pp[i].blue = *entry_start++; pp[i].alpha = *entry_start++; } else { pp[i].red = png_get_uint_16(entry_start); entry_start += 2; pp[i].green = png_get_uint_16(entry_start); entry_start += 2; pp[i].blue = png_get_uint_16(entry_start); entry_start += 2; pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2; } pp[i].frequency = png_get_uint_16(entry_start); entry_start += 2; } #endif /* Discard all chunk data except the name and stash that */ new_palette.name = (png_charp)buffer; png_set_sPLT(png_ptr, info_ptr, &new_palette, 1); png_free(png_ptr, new_palette.entries); } #endif /* READ_sPLT */ #ifdef PNG_READ_tRNS_SUPPORTED void /* PRIVATE */ png_handle_tRNS(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte readbuf[PNG_MAX_PALETTE_LENGTH]; png_debug(1, "in png_handle_tRNS"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) { png_byte buf[2]; if (length != 2) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 2); png_ptr->num_trans = 1; png_ptr->trans_color.gray = png_get_uint_16(buf); } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) { png_byte buf[6]; if (length != 6) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, length); png_ptr->num_trans = 1; png_ptr->trans_color.red = png_get_uint_16(buf); png_ptr->trans_color.green = png_get_uint_16(buf + 2); png_ptr->trans_color.blue = png_get_uint_16(buf + 4); } else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if ((png_ptr->mode & PNG_HAVE_PLTE) == 0) { /* TODO: is this actually an error in the ISO spec? */ png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } if (length > (unsigned int) png_ptr->num_palette || length > (unsigned int) PNG_MAX_PALETTE_LENGTH || length == 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, readbuf, length); png_ptr->num_trans = (png_uint_16)length; } else { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid with alpha channel"); return; } if (png_crc_finish(png_ptr, 0) != 0) { png_ptr->num_trans = 0; return; } /* TODO: this is a horrible side effect in the palette case because the * png_struct ends up with a pointer to the tRNS buffer owned by the * png_info. Fix this. */ png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans, &(png_ptr->trans_color)); } #endif #ifdef PNG_READ_bKGD_SUPPORTED void /* PRIVATE */ png_handle_bKGD(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { unsigned int truelen; png_byte buf[6]; png_color_16 background; png_debug(1, "in png_handle_bKGD"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 || (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && (png_ptr->mode & PNG_HAVE_PLTE) == 0)) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) truelen = 1; else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) != 0) truelen = 6; else truelen = 2; if (length != truelen) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, truelen); if (png_crc_finish(png_ptr, 0) != 0) return; /* We convert the index value into RGB components so that we can allow * arbitrary RGB values for background when we have transparency, and * so it is easy to determine the RGB values of the background color * from the info_ptr struct. */ if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { background.index = buf[0]; if (info_ptr != NULL && info_ptr->num_palette != 0) { if (buf[0] >= info_ptr->num_palette) { png_chunk_benign_error(png_ptr, "invalid index"); return; } background.red = (png_uint_16)png_ptr->palette[buf[0]].red; background.green = (png_uint_16)png_ptr->palette[buf[0]].green; background.blue = (png_uint_16)png_ptr->palette[buf[0]].blue; } else background.red = background.green = background.blue = 0; background.gray = 0; } else if ((png_ptr->color_type & PNG_COLOR_MASK_COLOR) == 0) /* GRAY */ { if (png_ptr->bit_depth <= 8) { if (buf[0] != 0 || buf[1] >= (unsigned int)(1 << png_ptr->bit_depth)) { png_chunk_benign_error(png_ptr, "invalid gray level"); return; } } background.index = 0; background.red = background.green = background.blue = background.gray = png_get_uint_16(buf); } else { if (png_ptr->bit_depth <= 8) { if (buf[0] != 0 || buf[2] != 0 || buf[4] != 0) { png_chunk_benign_error(png_ptr, "invalid color"); return; } } background.index = 0; background.red = png_get_uint_16(buf); background.green = png_get_uint_16(buf + 2); background.blue = png_get_uint_16(buf + 4); background.gray = 0; } png_set_bKGD(png_ptr, info_ptr, &background); } #endif #ifdef PNG_READ_eXIf_SUPPORTED void /* PRIVATE */ png_handle_eXIf(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { unsigned int i; png_debug(1, "in png_handle_eXIf"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); if (length < 2) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "too short"); return; } else if (info_ptr == NULL || (info_ptr->valid & PNG_INFO_eXIf) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } info_ptr->free_me |= PNG_FREE_EXIF; info_ptr->eXIf_buf = png_voidcast(png_bytep, png_malloc_warn(png_ptr, length)); if (info_ptr->eXIf_buf == NULL) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of memory"); return; } for (i = 0; i < length; i++) { png_byte buf[1]; png_crc_read(png_ptr, buf, 1); info_ptr->eXIf_buf[i] = buf[0]; if (i == 1 && buf[0] != 'M' && buf[0] != 'I' && info_ptr->eXIf_buf[0] != buf[0]) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "incorrect byte-order specifier"); png_free(png_ptr, info_ptr->eXIf_buf); info_ptr->eXIf_buf = NULL; return; } } if (png_crc_finish(png_ptr, 0) != 0) return; png_set_eXIf_1(png_ptr, info_ptr, length, info_ptr->eXIf_buf); png_free(png_ptr, info_ptr->eXIf_buf); info_ptr->eXIf_buf = NULL; } #endif #ifdef PNG_READ_hIST_SUPPORTED void /* PRIVATE */ png_handle_hIST(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { unsigned int num, i; png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH]; png_debug(1, "in png_handle_hIST"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0 || (png_ptr->mode & PNG_HAVE_PLTE) == 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } num = length / 2 ; if (num != (unsigned int) png_ptr->num_palette || num > (unsigned int) PNG_MAX_PALETTE_LENGTH) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } for (i = 0; i < num; i++) { png_byte buf[2]; png_crc_read(png_ptr, buf, 2); readbuf[i] = png_get_uint_16(buf); } if (png_crc_finish(png_ptr, 0) != 0) return; png_set_hIST(png_ptr, info_ptr, readbuf); } #endif #ifdef PNG_READ_pHYs_SUPPORTED void /* PRIVATE */ png_handle_pHYs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[9]; png_uint_32 res_x, res_y; int unit_type; png_debug(1, "in png_handle_pHYs"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if (length != 9) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 9); if (png_crc_finish(png_ptr, 0) != 0) return; res_x = png_get_uint_32(buf); res_y = png_get_uint_32(buf + 4); unit_type = buf[8]; png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type); } #endif #ifdef PNG_READ_oFFs_SUPPORTED void /* PRIVATE */ png_handle_oFFs(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[9]; png_int_32 offset_x, offset_y; int unit_type; png_debug(1, "in png_handle_oFFs"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if (length != 9) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 9); if (png_crc_finish(png_ptr, 0) != 0) return; offset_x = png_get_int_32(buf); offset_y = png_get_int_32(buf + 4); unit_type = buf[8]; png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type); } #endif #ifdef PNG_READ_pCAL_SUPPORTED /* Read the pCAL chunk (described in the PNG Extensions document) */ void /* PRIVATE */ png_handle_pCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_int_32 X0, X1; png_byte type, nparams; png_bytep buffer, buf, units, endptr; png_charpp params; int i; png_debug(1, "in png_handle_pCAL"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } png_debug1(2, "Allocating and reading pCAL chunk data (%u bytes)", length + 1); buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/); if (buffer == NULL) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of memory"); return; } png_crc_read(png_ptr, buffer, length); if (png_crc_finish(png_ptr, 0) != 0) return; buffer[length] = 0; /* Null terminate the last string */ png_debug(3, "Finding end of pCAL purpose string"); for (buf = buffer; *buf; buf++) /* Empty loop */ ; endptr = buffer + length; /* We need to have at least 12 bytes after the purpose string * in order to get the parameter information. */ if (endptr - buf <= 12) { png_chunk_benign_error(png_ptr, "invalid"); return; } png_debug(3, "Reading pCAL X0, X1, type, nparams, and units"); X0 = png_get_int_32((png_bytep)buf+1); X1 = png_get_int_32((png_bytep)buf+5); type = buf[9]; nparams = buf[10]; units = buf + 11; png_debug(3, "Checking pCAL equation type and number of parameters"); /* Check that we have the right number of parameters for known * equation types. */ if ((type == PNG_EQUATION_LINEAR && nparams != 2) || (type == PNG_EQUATION_BASE_E && nparams != 3) || (type == PNG_EQUATION_ARBITRARY && nparams != 3) || (type == PNG_EQUATION_HYPERBOLIC && nparams != 4)) { png_chunk_benign_error(png_ptr, "invalid parameter count"); return; } else if (type >= PNG_EQUATION_LAST) { png_chunk_benign_error(png_ptr, "unrecognized equation type"); } for (buf = units; *buf; buf++) /* Empty loop to move past the units string. */ ; png_debug(3, "Allocating pCAL parameters array"); params = png_voidcast(png_charpp, png_malloc_warn(png_ptr, nparams * (sizeof (png_charp)))); if (params == NULL) { png_chunk_benign_error(png_ptr, "out of memory"); return; } /* Get pointers to the start of each parameter string. */ for (i = 0; i < nparams; i++) { buf++; /* Skip the null string terminator from previous parameter. */ png_debug1(3, "Reading pCAL parameter %d", i); for (params[i] = (png_charp)buf; buf <= endptr && *buf != 0; buf++) /* Empty loop to move past each parameter string */ ; /* Make sure we haven't run out of data yet */ if (buf > endptr) { png_free(png_ptr, params); png_chunk_benign_error(png_ptr, "invalid data"); return; } } png_set_pCAL(png_ptr, info_ptr, (png_charp)buffer, X0, X1, type, nparams, (png_charp)units, params); png_free(png_ptr, params); } #endif #ifdef PNG_READ_sCAL_SUPPORTED /* Read the sCAL chunk */ void /* PRIVATE */ png_handle_sCAL(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_bytep buffer; size_t i; int state; png_debug(1, "in png_handle_sCAL"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of place"); return; } else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } /* Need unit type, width, \0, height: minimum 4 bytes */ else if (length < 4) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_debug1(2, "Allocating and reading sCAL chunk data (%u bytes)", length + 1); buffer = png_read_buffer(png_ptr, length+1, 2/*silent*/); if (buffer == NULL) { png_chunk_benign_error(png_ptr, "out of memory"); png_crc_finish(png_ptr, length); return; } png_crc_read(png_ptr, buffer, length); buffer[length] = 0; /* Null terminate the last string */ if (png_crc_finish(png_ptr, 0) != 0) return; /* Validate the unit. */ if (buffer[0] != 1 && buffer[0] != 2) { png_chunk_benign_error(png_ptr, "invalid unit"); return; } /* Validate the ASCII numbers, need two ASCII numbers separated by * a '\0' and they need to fit exactly in the chunk data. */ i = 1; state = 0; if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 || i >= length || buffer[i++] != 0) png_chunk_benign_error(png_ptr, "bad width format"); else if (PNG_FP_IS_POSITIVE(state) == 0) png_chunk_benign_error(png_ptr, "non-positive width"); else { size_t heighti = i; state = 0; if (png_check_fp_number((png_const_charp)buffer, length, &state, &i) == 0 || i != length) png_chunk_benign_error(png_ptr, "bad height format"); else if (PNG_FP_IS_POSITIVE(state) == 0) png_chunk_benign_error(png_ptr, "non-positive height"); else /* This is the (only) success case. */ png_set_sCAL_s(png_ptr, info_ptr, buffer[0], (png_charp)buffer+1, (png_charp)buffer+heighti); } } #endif #ifdef PNG_READ_tIME_SUPPORTED void /* PRIVATE */ png_handle_tIME(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_byte buf[7]; png_time mod_time; png_debug(1, "in png_handle_tIME"); if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME) != 0) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "duplicate"); return; } if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; if (length != 7) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "invalid"); return; } png_crc_read(png_ptr, buf, 7); if (png_crc_finish(png_ptr, 0) != 0) return; mod_time.second = buf[6]; mod_time.minute = buf[5]; mod_time.hour = buf[4]; mod_time.day = buf[3]; mod_time.month = buf[2]; mod_time.year = png_get_uint_16(buf); png_set_tIME(png_ptr, info_ptr, &mod_time); } #endif #ifdef PNG_READ_tEXt_SUPPORTED /* Note: this does not properly handle chunks that are > 64K under DOS */ void /* PRIVATE */ png_handle_tEXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_text text_info; png_bytep buffer; png_charp key; png_charp text; png_uint_32 skip = 0; png_debug(1, "in png_handle_tEXt"); #ifdef PNG_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_cache_max != 0) { if (png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); return; } if (--png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "no space in chunk cache"); return; } } #endif if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; #ifdef PNG_MAX_MALLOC_64K if (length > 65535U) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "too large to fit in memory"); return; } #endif buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/); if (buffer == NULL) { png_chunk_benign_error(png_ptr, "out of memory"); return; } png_crc_read(png_ptr, buffer, length); if (png_crc_finish(png_ptr, skip) != 0) return; key = (png_charp)buffer; key[length] = 0; for (text = key; *text; text++) /* Empty loop to find end of key */ ; if (text != key + length) text++; text_info.compression = PNG_TEXT_COMPRESSION_NONE; text_info.key = key; text_info.lang = NULL; text_info.lang_key = NULL; text_info.itxt_length = 0; text_info.text = text; text_info.text_length = strlen(text); if (png_set_text_2(png_ptr, info_ptr, &text_info, 1) != 0) png_warning(png_ptr, "Insufficient memory to process text chunk"); } #endif #ifdef PNG_READ_zTXt_SUPPORTED /* Note: this does not correctly handle chunks that are > 64K under DOS */ void /* PRIVATE */ png_handle_zTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_const_charp errmsg = NULL; png_bytep buffer; png_uint_32 keyword_length; png_debug(1, "in png_handle_zTXt"); #ifdef PNG_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_cache_max != 0) { if (png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); return; } if (--png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "no space in chunk cache"); return; } } #endif if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; /* Note, "length" is sufficient here; we won't be adding * a null terminator later. */ buffer = png_read_buffer(png_ptr, length, 2/*silent*/); if (buffer == NULL) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of memory"); return; } png_crc_read(png_ptr, buffer, length); if (png_crc_finish(png_ptr, 0) != 0) return; /* TODO: also check that the keyword contents match the spec! */ for (keyword_length = 0; keyword_length < length && buffer[keyword_length] != 0; ++keyword_length) /* Empty loop to find end of name */ ; if (keyword_length > 79 || keyword_length < 1) errmsg = "bad keyword"; /* zTXt must have some LZ data after the keyword, although it may expand to * zero bytes; we need a '\0' at the end of the keyword, the compression type * then the LZ data: */ else if (keyword_length + 3 > length) errmsg = "truncated"; else if (buffer[keyword_length+1] != PNG_COMPRESSION_TYPE_BASE) errmsg = "unknown compression type"; else { png_alloc_size_t uncompressed_length = PNG_SIZE_MAX; /* TODO: at present png_decompress_chunk imposes a single application * level memory limit, this should be split to different values for iCCP * and text chunks. */ if (png_decompress_chunk(png_ptr, length, keyword_length+2, &uncompressed_length, 1/*terminate*/) == Z_STREAM_END) { png_text text; if (png_ptr->read_buffer == NULL) errmsg="Read failure in png_handle_zTXt"; else { /* It worked; png_ptr->read_buffer now looks like a tEXt chunk * except for the extra compression type byte and the fact that * it isn't necessarily '\0' terminated. */ buffer = png_ptr->read_buffer; buffer[uncompressed_length+(keyword_length+2)] = 0; text.compression = PNG_TEXT_COMPRESSION_zTXt; text.key = (png_charp)buffer; text.text = (png_charp)(buffer + keyword_length+2); text.text_length = uncompressed_length; text.itxt_length = 0; text.lang = NULL; text.lang_key = NULL; if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0) errmsg = "insufficient memory"; } } else errmsg = png_ptr->zstream.msg; } if (errmsg != NULL) png_chunk_benign_error(png_ptr, errmsg); } #endif #ifdef PNG_READ_iTXt_SUPPORTED /* Note: this does not correctly handle chunks that are > 64K under DOS */ void /* PRIVATE */ png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) { png_const_charp errmsg = NULL; png_bytep buffer; png_uint_32 prefix_length; png_debug(1, "in png_handle_iTXt"); #ifdef PNG_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_cache_max != 0) { if (png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); return; } if (--png_ptr->user_chunk_cache_max == 1) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "no space in chunk cache"); return; } } #endif if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) png_chunk_error(png_ptr, "missing IHDR"); if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) png_ptr->mode |= PNG_AFTER_IDAT; buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/); if (buffer == NULL) { png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "out of memory"); return; } png_crc_read(png_ptr, buffer, length); if (png_crc_finish(png_ptr, 0) != 0) return; /* First the keyword. */ for (prefix_length=0; prefix_length < length && buffer[prefix_length] != 0; ++prefix_length) /* Empty loop */ ; /* Perform a basic check on the keyword length here. */ if (prefix_length > 79 || prefix_length < 1) errmsg = "bad keyword"; /* Expect keyword, compression flag, compression type, language, translated * keyword (both may be empty but are 0 terminated) then the text, which may * be empty. */ else if (prefix_length + 5 > length) errmsg = "truncated"; else if (buffer[prefix_length+1] == 0 || (buffer[prefix_length+1] == 1 && buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE)) { int compressed = buffer[prefix_length+1] != 0; png_uint_32 language_offset, translated_keyword_offset; png_alloc_size_t uncompressed_length = 0; /* Now the language tag */ prefix_length += 3; language_offset = prefix_length; for (; prefix_length < length && buffer[prefix_length] != 0; ++prefix_length) /* Empty loop */ ; /* WARNING: the length may be invalid here, this is checked below. */ translated_keyword_offset = ++prefix_length; for (; prefix_length < length && buffer[prefix_length] != 0; ++prefix_length) /* Empty loop */ ; /* prefix_length should now be at the trailing '\0' of the translated * keyword, but it may already be over the end. None of this arithmetic * can overflow because chunks are at most 2^31 bytes long, but on 16-bit * systems the available allocation may overflow. */ ++prefix_length; if (compressed == 0 && prefix_length <= length) uncompressed_length = length - prefix_length; else if (compressed != 0 && prefix_length < length) { uncompressed_length = PNG_SIZE_MAX; /* TODO: at present png_decompress_chunk imposes a single application * level memory limit, this should be split to different values for * iCCP and text chunks. */ if (png_decompress_chunk(png_ptr, length, prefix_length, &uncompressed_length, 1/*terminate*/) == Z_STREAM_END) buffer = png_ptr->read_buffer; else errmsg = png_ptr->zstream.msg; } else errmsg = "truncated"; if (errmsg == NULL) { png_text text; buffer[uncompressed_length+prefix_length] = 0; if (compressed == 0) text.compression = PNG_ITXT_COMPRESSION_NONE; else text.compression = PNG_ITXT_COMPRESSION_zTXt; text.key = (png_charp)buffer; text.lang = (png_charp)buffer + language_offset; text.lang_key = (png_charp)buffer + translated_keyword_offset; text.text = (png_charp)buffer + prefix_length; text.text_length = 0; text.itxt_length = uncompressed_length; if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0) errmsg = "insufficient memory"; } } else errmsg = "bad compression info"; if (errmsg != NULL) png_chunk_benign_error(png_ptr, errmsg); } #endif #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED /* Utility function for png_handle_unknown; set up png_ptr::unknown_chunk */ static int png_cache_unknown_chunk(png_structrp png_ptr, png_uint_32 length) { png_alloc_size_t limit = PNG_SIZE_MAX; if (png_ptr->unknown_chunk.data != NULL) { png_free(png_ptr, png_ptr->unknown_chunk.data); png_ptr->unknown_chunk.data = NULL; } # ifdef PNG_SET_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_malloc_max > 0 && png_ptr->user_chunk_malloc_max < limit) limit = png_ptr->user_chunk_malloc_max; # elif PNG_USER_CHUNK_MALLOC_MAX > 0 if (PNG_USER_CHUNK_MALLOC_MAX < limit) limit = PNG_USER_CHUNK_MALLOC_MAX; # endif if (length <= limit) { PNG_CSTRING_FROM_CHUNK(png_ptr->unknown_chunk.name, png_ptr->chunk_name); /* The following is safe because of the PNG_SIZE_MAX init above */ png_ptr->unknown_chunk.size = (size_t)length/*SAFE*/; /* 'mode' is a flag array, only the bottom four bits matter here */ png_ptr->unknown_chunk.location = (png_byte)png_ptr->mode/*SAFE*/; if (length == 0) png_ptr->unknown_chunk.data = NULL; else { /* Do a 'warn' here - it is handled below. */ png_ptr->unknown_chunk.data = png_voidcast(png_bytep, png_malloc_warn(png_ptr, length)); } } if (png_ptr->unknown_chunk.data == NULL && length > 0) { /* This is benign because we clean up correctly */ png_crc_finish(png_ptr, length); png_chunk_benign_error(png_ptr, "unknown chunk exceeds memory limits"); return 0; } else { if (length > 0) png_crc_read(png_ptr, png_ptr->unknown_chunk.data, length); png_crc_finish(png_ptr, 0); return 1; } } #endif /* READ_UNKNOWN_CHUNKS */ /* Handle an unknown, or known but disabled, chunk */ void /* PRIVATE */ png_handle_unknown(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length, int keep) { int handled = 0; /* the chunk was handled */ png_debug(1, "in png_handle_unknown"); #ifdef PNG_READ_UNKNOWN_CHUNKS_SUPPORTED /* NOTE: this code is based on the code in libpng-1.4.12 except for fixing * the bug which meant that setting a non-default behavior for a specific * chunk would be ignored (the default was always used unless a user * callback was installed). * * 'keep' is the value from the png_chunk_unknown_handling, the setting for * this specific chunk_name, if PNG_HANDLE_AS_UNKNOWN_SUPPORTED, if not it * will always be PNG_HANDLE_CHUNK_AS_DEFAULT and it needs to be set here. * This is just an optimization to avoid multiple calls to the lookup * function. */ # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED keep = png_chunk_unknown_handling(png_ptr, png_ptr->chunk_name); # endif # endif /* One of the following methods will read the chunk or skip it (at least one * of these is always defined because this is the only way to switch on * PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) */ # ifdef PNG_READ_USER_CHUNKS_SUPPORTED /* The user callback takes precedence over the chunk keep value, but the * keep value is still required to validate a save of a critical chunk. */ if (png_ptr->read_user_chunk_fn != NULL) { if (png_cache_unknown_chunk(png_ptr, length) != 0) { /* Callback to user unknown chunk handler */ int ret = (*(png_ptr->read_user_chunk_fn))(png_ptr, &png_ptr->unknown_chunk); /* ret is: * negative: An error occurred; png_chunk_error will be called. * zero: The chunk was not handled, the chunk will be discarded * unless png_set_keep_unknown_chunks has been used to set * a 'keep' behavior for this particular chunk, in which * case that will be used. A critical chunk will cause an * error at this point unless it is to be saved. * positive: The chunk was handled, libpng will ignore/discard it. */ if (ret < 0) png_chunk_error(png_ptr, "error in user chunk"); else if (ret == 0) { /* If the keep value is 'default' or 'never' override it, but * still error out on critical chunks unless the keep value is * 'always' While this is weird it is the behavior in 1.4.12. * A possible improvement would be to obey the value set for the * chunk, but this would be an API change that would probably * damage some applications. * * The png_app_warning below catches the case that matters, where * the application has not set specific save or ignore for this * chunk or global save or ignore. */ if (keep < PNG_HANDLE_CHUNK_IF_SAFE) { # ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED if (png_ptr->unknown_default < PNG_HANDLE_CHUNK_IF_SAFE) { png_chunk_warning(png_ptr, "Saving unknown chunk:"); png_app_warning(png_ptr, "forcing save of an unhandled chunk;" " please call png_set_keep_unknown_chunks"); /* with keep = PNG_HANDLE_CHUNK_IF_SAFE */ } # endif keep = PNG_HANDLE_CHUNK_IF_SAFE; } } else /* chunk was handled */ { handled = 1; /* Critical chunks can be safely discarded at this point. */ keep = PNG_HANDLE_CHUNK_NEVER; } } else keep = PNG_HANDLE_CHUNK_NEVER; /* insufficient memory */ } else /* Use the SAVE_UNKNOWN_CHUNKS code or skip the chunk */ # endif /* READ_USER_CHUNKS */ # ifdef PNG_SAVE_UNKNOWN_CHUNKS_SUPPORTED { /* keep is currently just the per-chunk setting, if there was no * setting change it to the global default now (not that this may * still be AS_DEFAULT) then obtain the cache of the chunk if required, * if not simply skip the chunk. */ if (keep == PNG_HANDLE_CHUNK_AS_DEFAULT) keep = png_ptr->unknown_default; if (keep == PNG_HANDLE_CHUNK_ALWAYS || (keep == PNG_HANDLE_CHUNK_IF_SAFE && PNG_CHUNK_ANCILLARY(png_ptr->chunk_name))) { if (png_cache_unknown_chunk(png_ptr, length) == 0) keep = PNG_HANDLE_CHUNK_NEVER; } else png_crc_finish(png_ptr, length); } # else # ifndef PNG_READ_USER_CHUNKS_SUPPORTED # error no method to support READ_UNKNOWN_CHUNKS # endif { /* If here there is no read callback pointer set and no support is * compiled in to just save the unknown chunks, so simply skip this * chunk. If 'keep' is something other than AS_DEFAULT or NEVER then * the app has erroneously asked for unknown chunk saving when there * is no support. */ if (keep > PNG_HANDLE_CHUNK_NEVER) png_app_error(png_ptr, "no unknown chunk support available"); png_crc_finish(png_ptr, length); } # endif # ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED /* Now store the chunk in the chunk list if appropriate, and if the limits * permit it. */ if (keep == PNG_HANDLE_CHUNK_ALWAYS || (keep == PNG_HANDLE_CHUNK_IF_SAFE && PNG_CHUNK_ANCILLARY(png_ptr->chunk_name))) { # ifdef PNG_USER_LIMITS_SUPPORTED switch (png_ptr->user_chunk_cache_max) { case 2: png_ptr->user_chunk_cache_max = 1; png_chunk_benign_error(png_ptr, "no space in chunk cache"); /* FALLTHROUGH */ case 1: /* NOTE: prior to 1.6.0 this case resulted in an unknown critical * chunk being skipped, now there will be a hard error below. */ break; default: /* not at limit */ --(png_ptr->user_chunk_cache_max); /* FALLTHROUGH */ case 0: /* no limit */ # endif /* USER_LIMITS */ /* Here when the limit isn't reached or when limits are compiled * out; store the chunk. */ png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1); handled = 1; # ifdef PNG_USER_LIMITS_SUPPORTED break; } # endif } # else /* no store support: the chunk must be handled by the user callback */ PNG_UNUSED(info_ptr) # endif /* Regardless of the error handling below the cached data (if any) can be * freed now. Notice that the data is not freed if there is a png_error, but * it will be freed by destroy_read_struct. */ if (png_ptr->unknown_chunk.data != NULL) png_free(png_ptr, png_ptr->unknown_chunk.data); png_ptr->unknown_chunk.data = NULL; #else /* !PNG_READ_UNKNOWN_CHUNKS_SUPPORTED */ /* There is no support to read an unknown chunk, so just skip it. */ png_crc_finish(png_ptr, length); PNG_UNUSED(info_ptr) PNG_UNUSED(keep) #endif /* !READ_UNKNOWN_CHUNKS */ /* Check for unhandled critical chunks */ if (handled == 0 && PNG_CHUNK_CRITICAL(png_ptr->chunk_name)) png_chunk_error(png_ptr, "unhandled critical chunk"); } /* This function is called to verify that a chunk name is valid. * This function can't have the "critical chunk check" incorporated * into it, since in the future we will need to be able to call user * functions to handle unknown critical chunks after we check that * the chunk name itself is valid. */ /* Bit hacking: the test for an invalid byte in the 4 byte chunk name is: * * ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97)) */ void /* PRIVATE */ png_check_chunk_name(png_const_structrp png_ptr, const png_uint_32 chunk_name) { int i; png_uint_32 cn=chunk_name; png_debug(1, "in png_check_chunk_name"); for (i=1; i<=4; ++i) { int c = cn & 0xff; if (c < 65 || c > 122 || (c > 90 && c < 97)) png_chunk_error(png_ptr, "invalid chunk type"); cn >>= 8; } } void /* PRIVATE */ png_check_chunk_length(png_const_structrp png_ptr, const png_uint_32 length) { png_alloc_size_t limit = PNG_UINT_31_MAX; # ifdef PNG_SET_USER_LIMITS_SUPPORTED if (png_ptr->user_chunk_malloc_max > 0 && png_ptr->user_chunk_malloc_max < limit) limit = png_ptr->user_chunk_malloc_max; # elif PNG_USER_CHUNK_MALLOC_MAX > 0 if (PNG_USER_CHUNK_MALLOC_MAX < limit) limit = PNG_USER_CHUNK_MALLOC_MAX; # endif if (png_ptr->chunk_name == png_IDAT) { png_alloc_size_t idat_limit = PNG_UINT_31_MAX; size_t row_factor = (size_t)png_ptr->width * (size_t)png_ptr->channels * (png_ptr->bit_depth > 8? 2: 1) + 1 + (png_ptr->interlaced? 6: 0); if (png_ptr->height > PNG_UINT_32_MAX/row_factor) idat_limit = PNG_UINT_31_MAX; else idat_limit = png_ptr->height * row_factor; row_factor = row_factor > 32566? 32566 : row_factor; idat_limit += 6 + 5*(idat_limit/row_factor+1); /* zlib+deflate overhead */ idat_limit=idat_limit < PNG_UINT_31_MAX? idat_limit : PNG_UINT_31_MAX; limit = limit < idat_limit? idat_limit : limit; } if (length > limit) { png_debug2(0," length = %lu, limit = %lu", (unsigned long)length,(unsigned long)limit); png_chunk_error(png_ptr, "chunk data is too large"); } } /* Combines the row recently read in with the existing pixels in the row. This * routine takes care of alpha and transparency if requested. This routine also * handles the two methods of progressive display of interlaced images, * depending on the 'display' value; if 'display' is true then the whole row * (dp) is filled from the start by replicating the available pixels. If * 'display' is false only those pixels present in the pass are filled in. */ void /* PRIVATE */ png_combine_row(png_const_structrp png_ptr, png_bytep dp, int display) { unsigned int pixel_depth = png_ptr->transformed_pixel_depth; png_const_bytep sp = png_ptr->row_buf + 1; png_alloc_size_t row_width = png_ptr->width; unsigned int pass = png_ptr->pass; png_bytep end_ptr = 0; png_byte end_byte = 0; unsigned int end_mask; png_debug(1, "in png_combine_row"); /* Added in 1.5.6: it should not be possible to enter this routine until at * least one row has been read from the PNG data and transformed. */ if (pixel_depth == 0) png_error(png_ptr, "internal row logic error"); /* Added in 1.5.4: the pixel depth should match the information returned by * any call to png_read_update_info at this point. Do not continue if we got * this wrong. */ if (png_ptr->info_rowbytes != 0 && png_ptr->info_rowbytes != PNG_ROWBYTES(pixel_depth, row_width)) png_error(png_ptr, "internal row size calculation error"); /* Don't expect this to ever happen: */ if (row_width == 0) png_error(png_ptr, "internal row width error"); /* Preserve the last byte in cases where only part of it will be overwritten, * the multiply below may overflow, we don't care because ANSI-C guarantees * we get the low bits. */ end_mask = (pixel_depth * row_width) & 7; if (end_mask != 0) { /* end_ptr == NULL is a flag to say do nothing */ end_ptr = dp + PNG_ROWBYTES(pixel_depth, row_width) - 1; end_byte = *end_ptr; # ifdef PNG_READ_PACKSWAP_SUPPORTED if ((png_ptr->transformations & PNG_PACKSWAP) != 0) /* little-endian byte */ end_mask = (unsigned int)(0xff << end_mask); else /* big-endian byte */ # endif end_mask = 0xff >> end_mask; /* end_mask is now the bits to *keep* from the destination row */ } /* For non-interlaced images this reduces to a memcpy(). A memcpy() * will also happen if interlacing isn't supported or if the application * does not call png_set_interlace_handling(). In the latter cases the * caller just gets a sequence of the unexpanded rows from each interlace * pass. */ #ifdef PNG_READ_INTERLACING_SUPPORTED if (png_ptr->interlaced != 0 && (png_ptr->transformations & PNG_INTERLACE) != 0 && pass < 6 && (display == 0 || /* The following copies everything for 'display' on passes 0, 2 and 4. */ (display == 1 && (pass & 1) != 0))) { /* Narrow images may have no bits in a pass; the caller should handle * this, but this test is cheap: */ if (row_width <= PNG_PASS_START_COL(pass)) return; if (pixel_depth < 8) { /* For pixel depths up to 4 bpp the 8-pixel mask can be expanded to fit * into 32 bits, then a single loop over the bytes using the four byte * values in the 32-bit mask can be used. For the 'display' option the * expanded mask may also not require any masking within a byte. To * make this work the PACKSWAP option must be taken into account - it * simply requires the pixels to be reversed in each byte. * * The 'regular' case requires a mask for each of the first 6 passes, * the 'display' case does a copy for the even passes in the range * 0..6. This has already been handled in the test above. * * The masks are arranged as four bytes with the first byte to use in * the lowest bits (little-endian) regardless of the order (PACKSWAP or * not) of the pixels in each byte. * * NOTE: the whole of this logic depends on the caller of this function * only calling it on rows appropriate to the pass. This function only * understands the 'x' logic; the 'y' logic is handled by the caller. * * The following defines allow generation of compile time constant bit * masks for each pixel depth and each possibility of swapped or not * swapped bytes. Pass 'p' is in the range 0..6; 'x', a pixel index, * is in the range 0..7; and the result is 1 if the pixel is to be * copied in the pass, 0 if not. 'S' is for the sparkle method, 'B' * for the block method. * * With some compilers a compile time expression of the general form: * * (shift >= 32) ? (a >> (shift-32)) : (b >> shift) * * Produces warnings with values of 'shift' in the range 33 to 63 * because the right hand side of the ?: expression is evaluated by * the compiler even though it isn't used. Microsoft Visual C (various * versions) and the Intel C compiler are known to do this. To avoid * this the following macros are used in 1.5.6. This is a temporary * solution to avoid destabilizing the code during the release process. */ # if PNG_USE_COMPILE_TIME_MASKS # define PNG_LSR(x,s) ((x)>>((s) & 0x1f)) # define PNG_LSL(x,s) ((x)<<((s) & 0x1f)) # else # define PNG_LSR(x,s) ((x)>>(s)) # define PNG_LSL(x,s) ((x)<<(s)) # endif # define S_COPY(p,x) (((p)<4 ? PNG_LSR(0x80088822,(3-(p))*8+(7-(x))) :\ PNG_LSR(0xaa55ff00,(7-(p))*8+(7-(x)))) & 1) # define B_COPY(p,x) (((p)<4 ? PNG_LSR(0xff0fff33,(3-(p))*8+(7-(x))) :\ PNG_LSR(0xff55ff00,(7-(p))*8+(7-(x)))) & 1) /* Return a mask for pass 'p' pixel 'x' at depth 'd'. The mask is * little endian - the first pixel is at bit 0 - however the extra * parameter 's' can be set to cause the mask position to be swapped * within each byte, to match the PNG format. This is done by XOR of * the shift with 7, 6 or 4 for bit depths 1, 2 and 4. */ # define PIXEL_MASK(p,x,d,s) \ (PNG_LSL(((PNG_LSL(1U,(d)))-1),(((x)*(d))^((s)?8-(d):0)))) /* Hence generate the appropriate 'block' or 'sparkle' pixel copy mask. */ # define S_MASKx(p,x,d,s) (S_COPY(p,x)?PIXEL_MASK(p,x,d,s):0) # define B_MASKx(p,x,d,s) (B_COPY(p,x)?PIXEL_MASK(p,x,d,s):0) /* Combine 8 of these to get the full mask. For the 1-bpp and 2-bpp * cases the result needs replicating, for the 4-bpp case the above * generates a full 32 bits. */ # define MASK_EXPAND(m,d) ((m)*((d)==1?0x01010101:((d)==2?0x00010001:1))) # define S_MASK(p,d,s) MASK_EXPAND(S_MASKx(p,0,d,s) + S_MASKx(p,1,d,s) +\ S_MASKx(p,2,d,s) + S_MASKx(p,3,d,s) + S_MASKx(p,4,d,s) +\ S_MASKx(p,5,d,s) + S_MASKx(p,6,d,s) + S_MASKx(p,7,d,s), d) # define B_MASK(p,d,s) MASK_EXPAND(B_MASKx(p,0,d,s) + B_MASKx(p,1,d,s) +\ B_MASKx(p,2,d,s) + B_MASKx(p,3,d,s) + B_MASKx(p,4,d,s) +\ B_MASKx(p,5,d,s) + B_MASKx(p,6,d,s) + B_MASKx(p,7,d,s), d) #if PNG_USE_COMPILE_TIME_MASKS /* Utility macros to construct all the masks for a depth/swap * combination. The 's' parameter says whether the format is PNG * (big endian bytes) or not. Only the three odd-numbered passes are * required for the display/block algorithm. */ # define S_MASKS(d,s) { S_MASK(0,d,s), S_MASK(1,d,s), S_MASK(2,d,s),\ S_MASK(3,d,s), S_MASK(4,d,s), S_MASK(5,d,s) } # define B_MASKS(d,s) { B_MASK(1,d,s), B_MASK(3,d,s), B_MASK(5,d,s) } # define DEPTH_INDEX(d) ((d)==1?0:((d)==2?1:2)) /* Hence the pre-compiled masks indexed by PACKSWAP (or not), depth and * then pass: */ static PNG_CONST png_uint_32 row_mask[2/*PACKSWAP*/][3/*depth*/][6] = { /* Little-endian byte masks for PACKSWAP */ { S_MASKS(1,0), S_MASKS(2,0), S_MASKS(4,0) }, /* Normal (big-endian byte) masks - PNG format */ { S_MASKS(1,1), S_MASKS(2,1), S_MASKS(4,1) } }; /* display_mask has only three entries for the odd passes, so index by * pass>>1. */ static PNG_CONST png_uint_32 display_mask[2][3][3] = { /* Little-endian byte masks for PACKSWAP */ { B_MASKS(1,0), B_MASKS(2,0), B_MASKS(4,0) }, /* Normal (big-endian byte) masks - PNG format */ { B_MASKS(1,1), B_MASKS(2,1), B_MASKS(4,1) } }; # define MASK(pass,depth,display,png)\ ((display)?display_mask[png][DEPTH_INDEX(depth)][pass>>1]:\ row_mask[png][DEPTH_INDEX(depth)][pass]) #else /* !PNG_USE_COMPILE_TIME_MASKS */ /* This is the runtime alternative: it seems unlikely that this will * ever be either smaller or faster than the compile time approach. */ # define MASK(pass,depth,display,png)\ ((display)?B_MASK(pass,depth,png):S_MASK(pass,depth,png)) #endif /* !USE_COMPILE_TIME_MASKS */ /* Use the appropriate mask to copy the required bits. In some cases * the byte mask will be 0 or 0xff; optimize these cases. row_width is * the number of pixels, but the code copies bytes, so it is necessary * to special case the end. */ png_uint_32 pixels_per_byte = 8 / pixel_depth; png_uint_32 mask; # ifdef PNG_READ_PACKSWAP_SUPPORTED if ((png_ptr->transformations & PNG_PACKSWAP) != 0) mask = MASK(pass, pixel_depth, display, 0); else # endif mask = MASK(pass, pixel_depth, display, 1); for (;;) { png_uint_32 m; /* It doesn't matter in the following if png_uint_32 has more than * 32 bits because the high bits always match those in m<<24; it is, * however, essential to use OR here, not +, because of this. */ m = mask; mask = (m >> 8) | (m << 24); /* rotate right to good compilers */ m &= 0xff; if (m != 0) /* something to copy */ { if (m != 0xff) *dp = (png_byte)((*dp & ~m) | (*sp & m)); else *dp = *sp; } /* NOTE: this may overwrite the last byte with garbage if the image * is not an exact number of bytes wide; libpng has always done * this. */ if (row_width <= pixels_per_byte) break; /* May need to restore part of the last byte */ row_width -= pixels_per_byte; ++dp; ++sp; } } else /* pixel_depth >= 8 */ { unsigned int bytes_to_copy, bytes_to_jump; /* Validate the depth - it must be a multiple of 8 */ if (pixel_depth & 7) png_error(png_ptr, "invalid user transform pixel depth"); pixel_depth >>= 3; /* now in bytes */ row_width *= pixel_depth; /* Regardless of pass number the Adam 7 interlace always results in a * fixed number of pixels to copy then to skip. There may be a * different number of pixels to skip at the start though. */ { unsigned int offset = PNG_PASS_START_COL(pass) * pixel_depth; row_width -= offset; dp += offset; sp += offset; } /* Work out the bytes to copy. */ if (display != 0) { /* When doing the 'block' algorithm the pixel in the pass gets * replicated to adjacent pixels. This is why the even (0,2,4,6) * passes are skipped above - the entire expanded row is copied. */ bytes_to_copy = (1<<((6-pass)>>1)) * pixel_depth; /* But don't allow this number to exceed the actual row width. */ if (bytes_to_copy > row_width) bytes_to_copy = (unsigned int)/*SAFE*/row_width; } else /* normal row; Adam7 only ever gives us one pixel to copy. */ bytes_to_copy = pixel_depth; /* In Adam7 there is a constant offset between where the pixels go. */ bytes_to_jump = PNG_PASS_COL_OFFSET(pass) * pixel_depth; /* And simply copy these bytes. Some optimization is possible here, * depending on the value of 'bytes_to_copy'. Special case the low * byte counts, which we know to be frequent. * * Notice that these cases all 'return' rather than 'break' - this * avoids an unnecessary test on whether to restore the last byte * below. */ switch (bytes_to_copy) { case 1: for (;;) { *dp = *sp; if (row_width <= bytes_to_jump) return; dp += bytes_to_jump; sp += bytes_to_jump; row_width -= bytes_to_jump; } case 2: /* There is a possibility of a partial copy at the end here; this * slows the code down somewhat. */ do { dp[0] = sp[0]; dp[1] = sp[1]; if (row_width <= bytes_to_jump) return; sp += bytes_to_jump; dp += bytes_to_jump; row_width -= bytes_to_jump; } while (row_width > 1); /* And there can only be one byte left at this point: */ *dp = *sp; return; case 3: /* This can only be the RGB case, so each copy is exactly one * pixel and it is not necessary to check for a partial copy. */ for (;;) { dp[0] = sp[0]; dp[1] = sp[1]; dp[2] = sp[2]; if (row_width <= bytes_to_jump) return; sp += bytes_to_jump; dp += bytes_to_jump; row_width -= bytes_to_jump; } default: #if PNG_ALIGN_TYPE != PNG_ALIGN_NONE /* Check for double byte alignment and, if possible, use a * 16-bit copy. Don't attempt this for narrow images - ones that * are less than an interlace panel wide. Don't attempt it for * wide bytes_to_copy either - use the memcpy there. */ if (bytes_to_copy < 16 /*else use memcpy*/ && png_isaligned(dp, png_uint_16) && png_isaligned(sp, png_uint_16) && bytes_to_copy % (sizeof (png_uint_16)) == 0 && bytes_to_jump % (sizeof (png_uint_16)) == 0) { /* Everything is aligned for png_uint_16 copies, but try for * png_uint_32 first. */ if (png_isaligned(dp, png_uint_32) && png_isaligned(sp, png_uint_32) && bytes_to_copy % (sizeof (png_uint_32)) == 0 && bytes_to_jump % (sizeof (png_uint_32)) == 0) { png_uint_32p dp32 = png_aligncast(png_uint_32p,dp); png_const_uint_32p sp32 = png_aligncastconst( png_const_uint_32p, sp); size_t skip = (bytes_to_jump-bytes_to_copy) / (sizeof (png_uint_32)); do { size_t c = bytes_to_copy; do { *dp32++ = *sp32++; c -= (sizeof (png_uint_32)); } while (c > 0); if (row_width <= bytes_to_jump) return; dp32 += skip; sp32 += skip; row_width -= bytes_to_jump; } while (bytes_to_copy <= row_width); /* Get to here when the row_width truncates the final copy. * There will be 1-3 bytes left to copy, so don't try the * 16-bit loop below. */ dp = (png_bytep)dp32; sp = (png_const_bytep)sp32; do *dp++ = *sp++; while (--row_width > 0); return; } /* Else do it in 16-bit quantities, but only if the size is * not too large. */ else { png_uint_16p dp16 = png_aligncast(png_uint_16p, dp); png_const_uint_16p sp16 = png_aligncastconst( png_const_uint_16p, sp); size_t skip = (bytes_to_jump-bytes_to_copy) / (sizeof (png_uint_16)); do { size_t c = bytes_to_copy; do { *dp16++ = *sp16++; c -= (sizeof (png_uint_16)); } while (c > 0); if (row_width <= bytes_to_jump) return; dp16 += skip; sp16 += skip; row_width -= bytes_to_jump; } while (bytes_to_copy <= row_width); /* End of row - 1 byte left, bytes_to_copy > row_width: */ dp = (png_bytep)dp16; sp = (png_const_bytep)sp16; do *dp++ = *sp++; while (--row_width > 0); return; } } #endif /* ALIGN_TYPE code */ /* The true default - use a memcpy: */ for (;;) { memcpy(dp, sp, bytes_to_copy); if (row_width <= bytes_to_jump) return; sp += bytes_to_jump; dp += bytes_to_jump; row_width -= bytes_to_jump; if (bytes_to_copy > row_width) bytes_to_copy = (unsigned int)/*SAFE*/row_width; } } /* NOT REACHED*/ } /* pixel_depth >= 8 */ /* Here if pixel_depth < 8 to check 'end_ptr' below. */ } else #endif /* READ_INTERLACING */ /* If here then the switch above wasn't used so just memcpy the whole row * from the temporary row buffer (notice that this overwrites the end of the * destination row if it is a partial byte.) */ memcpy(dp, sp, PNG_ROWBYTES(pixel_depth, row_width)); /* Restore the overwritten bits from the last byte if necessary. */ if (end_ptr != NULL) *end_ptr = (png_byte)((end_byte & end_mask) | (*end_ptr & ~end_mask)); } #ifdef PNG_READ_INTERLACING_SUPPORTED void /* PRIVATE */ png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass, png_uint_32 transformations /* Because these may affect the byte layout */) { /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Offset to next interlace block */ static PNG_CONST unsigned int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; png_debug(1, "in png_do_read_interlace"); if (row != NULL && row_info != NULL) { png_uint_32 final_width; final_width = row_info->width * png_pass_inc[pass]; switch (row_info->pixel_depth) { case 1: { png_bytep sp = row + (size_t)((row_info->width - 1) >> 3); png_bytep dp = row + (size_t)((final_width - 1) >> 3); unsigned int sshift, dshift; unsigned int s_start, s_end; int s_inc; int jstop = (int)png_pass_inc[pass]; png_byte v; png_uint_32 i; int j; #ifdef PNG_READ_PACKSWAP_SUPPORTED if ((transformations & PNG_PACKSWAP) != 0) { sshift = ((row_info->width + 7) & 0x07); dshift = ((final_width + 7) & 0x07); s_start = 7; s_end = 0; s_inc = -1; } else #endif { sshift = 7 - ((row_info->width + 7) & 0x07); dshift = 7 - ((final_width + 7) & 0x07); s_start = 0; s_end = 7; s_inc = 1; } for (i = 0; i < row_info->width; i++) { v = (png_byte)((*sp >> sshift) & 0x01); for (j = 0; j < jstop; j++) { unsigned int tmp = *dp & (0x7f7f >> (7 - dshift)); tmp |= (unsigned int)(v << dshift); *dp = (png_byte)(tmp & 0xff); if (dshift == s_end) { dshift = s_start; dp--; } else dshift = (unsigned int)((int)dshift + s_inc); } if (sshift == s_end) { sshift = s_start; sp--; } else sshift = (unsigned int)((int)sshift + s_inc); } break; } case 2: { png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2); png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2); unsigned int sshift, dshift; unsigned int s_start, s_end; int s_inc; int jstop = (int)png_pass_inc[pass]; png_uint_32 i; #ifdef PNG_READ_PACKSWAP_SUPPORTED if ((transformations & PNG_PACKSWAP) != 0) { sshift = (((row_info->width + 3) & 0x03) << 1); dshift = (((final_width + 3) & 0x03) << 1); s_start = 6; s_end = 0; s_inc = -2; } else #endif { sshift = ((3 - ((row_info->width + 3) & 0x03)) << 1); dshift = ((3 - ((final_width + 3) & 0x03)) << 1); s_start = 0; s_end = 6; s_inc = 2; } for (i = 0; i < row_info->width; i++) { png_byte v; int j; v = (png_byte)((*sp >> sshift) & 0x03); for (j = 0; j < jstop; j++) { unsigned int tmp = *dp & (0x3f3f >> (6 - dshift)); tmp |= (unsigned int)(v << dshift); *dp = (png_byte)(tmp & 0xff); if (dshift == s_end) { dshift = s_start; dp--; } else dshift = (unsigned int)((int)dshift + s_inc); } if (sshift == s_end) { sshift = s_start; sp--; } else sshift = (unsigned int)((int)sshift + s_inc); } break; } case 4: { png_bytep sp = row + (size_t)((row_info->width - 1) >> 1); png_bytep dp = row + (size_t)((final_width - 1) >> 1); unsigned int sshift, dshift; unsigned int s_start, s_end; int s_inc; png_uint_32 i; int jstop = (int)png_pass_inc[pass]; #ifdef PNG_READ_PACKSWAP_SUPPORTED if ((transformations & PNG_PACKSWAP) != 0) { sshift = (((row_info->width + 1) & 0x01) << 2); dshift = (((final_width + 1) & 0x01) << 2); s_start = 4; s_end = 0; s_inc = -4; } else #endif { sshift = ((1 - ((row_info->width + 1) & 0x01)) << 2); dshift = ((1 - ((final_width + 1) & 0x01)) << 2); s_start = 0; s_end = 4; s_inc = 4; } for (i = 0; i < row_info->width; i++) { png_byte v = (png_byte)((*sp >> sshift) & 0x0f); int j; for (j = 0; j < jstop; j++) { unsigned int tmp = *dp & (0xf0f >> (4 - dshift)); tmp |= (unsigned int)(v << dshift); *dp = (png_byte)(tmp & 0xff); if (dshift == s_end) { dshift = s_start; dp--; } else dshift = (unsigned int)((int)dshift + s_inc); } if (sshift == s_end) { sshift = s_start; sp--; } else sshift = (unsigned int)((int)sshift + s_inc); } break; } default: { size_t pixel_bytes = (row_info->pixel_depth >> 3); png_bytep sp = row + (size_t)(row_info->width - 1) * pixel_bytes; png_bytep dp = row + (size_t)(final_width - 1) * pixel_bytes; int jstop = (int)png_pass_inc[pass]; png_uint_32 i; for (i = 0; i < row_info->width; i++) { png_byte v[8]; /* SAFE; pixel_depth does not exceed 64 */ int j; memcpy(v, sp, pixel_bytes); for (j = 0; j < jstop; j++) { memcpy(dp, v, pixel_bytes); dp -= pixel_bytes; } sp -= pixel_bytes; } break; } } row_info->width = final_width; row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth, final_width); } #ifndef PNG_READ_PACKSWAP_SUPPORTED PNG_UNUSED(transformations) /* Silence compiler warning */ #endif } #endif /* READ_INTERLACING */ static void png_read_filter_row_sub(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { size_t i; size_t istop = row_info->rowbytes; unsigned int bpp = (row_info->pixel_depth + 7) >> 3; png_bytep rp = row + bpp; PNG_UNUSED(prev_row) for (i = bpp; i < istop; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*(rp-bpp))) & 0xff); rp++; } } static void png_read_filter_row_up(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { size_t i; size_t istop = row_info->rowbytes; png_bytep rp = row; png_const_bytep pp = prev_row; for (i = 0; i < istop; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); rp++; } } static void png_read_filter_row_avg(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { size_t i; png_bytep rp = row; png_const_bytep pp = prev_row; unsigned int bpp = (row_info->pixel_depth + 7) >> 3; size_t istop = row_info->rowbytes - bpp; for (i = 0; i < bpp; i++) { *rp = (png_byte)(((int)(*rp) + ((int)(*pp++) / 2 )) & 0xff); rp++; } for (i = 0; i < istop; i++) { *rp = (png_byte)(((int)(*rp) + (int)(*pp++ + *(rp-bpp)) / 2 ) & 0xff); rp++; } } static void png_read_filter_row_paeth_1byte_pixel(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { png_bytep rp_end = row + row_info->rowbytes; int a, c; /* First pixel/byte */ c = *prev_row++; a = *row + c; *row++ = (png_byte)a; /* Remainder */ while (row < rp_end) { int b, pa, pb, pc, p; a &= 0xff; /* From previous iteration or start */ b = *prev_row++; p = b - c; pc = a - c; #ifdef PNG_USE_ABS pa = abs(p); pb = abs(pc); pc = abs(p + pc); #else pa = p < 0 ? -p : p; pb = pc < 0 ? -pc : pc; pc = (p + pc) < 0 ? -(p + pc) : p + pc; #endif /* Find the best predictor, the least of pa, pb, pc favoring the earlier * ones in the case of a tie. */ if (pb < pa) { pa = pb; a = b; } if (pc < pa) a = c; /* Calculate the current pixel in a, and move the previous row pixel to c * for the next time round the loop */ c = b; a += *row; *row++ = (png_byte)a; } } static void png_read_filter_row_paeth_multibyte_pixel(png_row_infop row_info, png_bytep row, png_const_bytep prev_row) { unsigned int bpp = (row_info->pixel_depth + 7) >> 3; png_bytep rp_end = row + bpp; /* Process the first pixel in the row completely (this is the same as 'up' * because there is only one candidate predictor for the first row). */ while (row < rp_end) { int a = *row + *prev_row++; *row++ = (png_byte)a; } /* Remainder */ rp_end = rp_end + (row_info->rowbytes - bpp); while (row < rp_end) { int a, b, c, pa, pb, pc, p; c = *(prev_row - bpp); a = *(row - bpp); b = *prev_row++; p = b - c; pc = a - c; #ifdef PNG_USE_ABS pa = abs(p); pb = abs(pc); pc = abs(p + pc); #else pa = p < 0 ? -p : p; pb = pc < 0 ? -pc : pc; pc = (p + pc) < 0 ? -(p + pc) : p + pc; #endif if (pb < pa) { pa = pb; a = b; } if (pc < pa) a = c; a += *row; *row++ = (png_byte)a; } } static void png_init_filter_functions(png_structrp pp) /* This function is called once for every PNG image (except for PNG images * that only use PNG_FILTER_VALUE_NONE for all rows) to set the * implementations required to reverse the filtering of PNG rows. Reversing * the filter is the first transformation performed on the row data. It is * performed in place, therefore an implementation can be selected based on * the image pixel format. If the implementation depends on image width then * take care to ensure that it works correctly if the image is interlaced - * interlacing causes the actual row width to vary. */ { unsigned int bpp = (pp->pixel_depth + 7) >> 3; pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub; pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up; pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg; if (bpp == 1) pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = png_read_filter_row_paeth_1byte_pixel; else pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = png_read_filter_row_paeth_multibyte_pixel; #ifdef PNG_FILTER_OPTIMIZATIONS /* To use this define PNG_FILTER_OPTIMIZATIONS as the name of a function to * call to install hardware optimizations for the above functions; simply * replace whatever elements of the pp->read_filter[] array with a hardware * specific (or, for that matter, generic) optimization. * * To see an example of this examine what configure.ac does when * --enable-arm-neon is specified on the command line. */ PNG_FILTER_OPTIMIZATIONS(pp, bpp); #endif } void /* PRIVATE */ png_read_filter_row(png_structrp pp, png_row_infop row_info, png_bytep row, png_const_bytep prev_row, int filter) { /* OPTIMIZATION: DO NOT MODIFY THIS FUNCTION, instead #define * PNG_FILTER_OPTIMIZATIONS to a function that overrides the generic * implementations. See png_init_filter_functions above. */ if (filter > PNG_FILTER_VALUE_NONE && filter < PNG_FILTER_VALUE_LAST) { if (pp->read_filter[0] == NULL) png_init_filter_functions(pp); pp->read_filter[filter-1](row_info, row, prev_row); } } #ifdef PNG_SEQUENTIAL_READ_SUPPORTED void /* PRIVATE */ png_read_IDAT_data(png_structrp png_ptr, png_bytep output, png_alloc_size_t avail_out) { /* Loop reading IDATs and decompressing the result into output[avail_out] */ png_ptr->zstream.next_out = output; png_ptr->zstream.avail_out = 0; /* safety: set below */ if (output == NULL) avail_out = 0; do { int ret; png_byte tmpbuf[PNG_INFLATE_BUF_SIZE]; if (png_ptr->zstream.avail_in == 0) { uInt avail_in; png_bytep buffer; while (png_ptr->idat_size == 0) { png_crc_finish(png_ptr, 0); png_ptr->idat_size = png_read_chunk_header(png_ptr); /* This is an error even in the 'check' case because the code just * consumed a non-IDAT header. */ if (png_ptr->chunk_name != png_IDAT) png_error(png_ptr, "Not enough image data"); } avail_in = png_ptr->IDAT_read_size; if (avail_in > png_ptr->idat_size) avail_in = (uInt)png_ptr->idat_size; /* A PNG with a gradually increasing IDAT size will defeat this attempt * to minimize memory usage by causing lots of re-allocs, but * realistically doing IDAT_read_size re-allocs is not likely to be a * big problem. */ buffer = png_read_buffer(png_ptr, avail_in, 0/*error*/); png_crc_read(png_ptr, buffer, avail_in); png_ptr->idat_size -= avail_in; png_ptr->zstream.next_in = buffer; png_ptr->zstream.avail_in = avail_in; } /* And set up the output side. */ if (output != NULL) /* standard read */ { uInt out = ZLIB_IO_MAX; if (out > avail_out) out = (uInt)avail_out; avail_out -= out; png_ptr->zstream.avail_out = out; } else /* after last row, checking for end */ { png_ptr->zstream.next_out = tmpbuf; png_ptr->zstream.avail_out = (sizeof tmpbuf); } /* Use NO_FLUSH; this gives zlib the maximum opportunity to optimize the * process. If the LZ stream is truncated the sequential reader will * terminally damage the stream, above, by reading the chunk header of the * following chunk (it then exits with png_error). * * TODO: deal more elegantly with truncated IDAT lists. */ ret = PNG_INFLATE(png_ptr, Z_NO_FLUSH); /* Take the unconsumed output back. */ if (output != NULL) avail_out += png_ptr->zstream.avail_out; else /* avail_out counts the extra bytes */ avail_out += (sizeof tmpbuf) - png_ptr->zstream.avail_out; png_ptr->zstream.avail_out = 0; if (ret == Z_STREAM_END) { /* Do this for safety; we won't read any more into this row. */ png_ptr->zstream.next_out = NULL; png_ptr->mode |= PNG_AFTER_IDAT; png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED; if (png_ptr->zstream.avail_in > 0 || png_ptr->idat_size > 0) png_chunk_benign_error(png_ptr, "Extra compressed data"); break; } if (ret != Z_OK) { png_zstream_error(png_ptr, ret); if (output != NULL) png_chunk_error(png_ptr, png_ptr->zstream.msg); else /* checking */ { png_chunk_benign_error(png_ptr, png_ptr->zstream.msg); return; } } } while (avail_out > 0); if (avail_out > 0) { /* The stream ended before the image; this is the same as too few IDATs so * should be handled the same way. */ if (output != NULL) png_error(png_ptr, "Not enough image data"); else /* the deflate stream contained extra data */ png_chunk_benign_error(png_ptr, "Too much image data"); } } void /* PRIVATE */ png_read_finish_IDAT(png_structrp png_ptr) { /* We don't need any more data and the stream should have ended, however the * LZ end code may actually not have been processed. In this case we must * read it otherwise stray unread IDAT data or, more likely, an IDAT chunk * may still remain to be consumed. */ if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0) { /* The NULL causes png_read_IDAT_data to swallow any remaining bytes in * the compressed stream, but the stream may be damaged too, so even after * this call we may need to terminate the zstream ownership. */ png_read_IDAT_data(png_ptr, NULL, 0); png_ptr->zstream.next_out = NULL; /* safety */ /* Now clear everything out for safety; the following may not have been * done. */ if ((png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED) == 0) { png_ptr->mode |= PNG_AFTER_IDAT; png_ptr->flags |= PNG_FLAG_ZSTREAM_ENDED; } } /* If the zstream has not been released do it now *and* terminate the reading * of the final IDAT chunk. */ if (png_ptr->zowner == png_IDAT) { /* Always do this; the pointers otherwise point into the read buffer. */ png_ptr->zstream.next_in = NULL; png_ptr->zstream.avail_in = 0; /* Now we no longer own the zstream. */ png_ptr->zowner = 0; /* The slightly weird semantics of the sequential IDAT reading is that we * are always in or at the end of an IDAT chunk, so we always need to do a * crc_finish here. If idat_size is non-zero we also need to read the * spurious bytes at the end of the chunk now. */ (void)png_crc_finish(png_ptr, png_ptr->idat_size); } } void /* PRIVATE */ png_read_finish_row(png_structrp png_ptr) { /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; png_debug(1, "in png_read_finish_row"); png_ptr->row_number++; if (png_ptr->row_number < png_ptr->num_rows) return; if (png_ptr->interlaced != 0) { png_ptr->row_number = 0; /* TO DO: don't do this if prev_row isn't needed (requires * read-ahead of the next row's filter byte. */ memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1); do { png_ptr->pass++; if (png_ptr->pass >= 7) break; png_ptr->iwidth = (png_ptr->width + png_pass_inc[png_ptr->pass] - 1 - png_pass_start[png_ptr->pass]) / png_pass_inc[png_ptr->pass]; if ((png_ptr->transformations & PNG_INTERLACE) == 0) { png_ptr->num_rows = (png_ptr->height + png_pass_yinc[png_ptr->pass] - 1 - png_pass_ystart[png_ptr->pass]) / png_pass_yinc[png_ptr->pass]; } else /* if (png_ptr->transformations & PNG_INTERLACE) */ break; /* libpng deinterlacing sees every row */ } while (png_ptr->num_rows == 0 || png_ptr->iwidth == 0); if (png_ptr->pass < 7) return; } /* Here after at the end of the last row of the last pass. */ png_read_finish_IDAT(png_ptr); } #endif /* SEQUENTIAL_READ */ void /* PRIVATE */ png_read_start_row(png_structrp png_ptr) { /* Arrays to facilitate easy interlacing - use pass (0 - 6) as index */ /* Start of interlace block */ static PNG_CONST png_byte png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0}; /* Offset to next interlace block */ static PNG_CONST png_byte png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1}; /* Start of interlace block in the y direction */ static PNG_CONST png_byte png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1}; /* Offset to next interlace block in the y direction */ static PNG_CONST png_byte png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2}; unsigned int max_pixel_depth; size_t row_bytes; png_debug(1, "in png_read_start_row"); #ifdef PNG_READ_TRANSFORMS_SUPPORTED png_init_read_transformations(png_ptr); #endif if (png_ptr->interlaced != 0) { if ((png_ptr->transformations & PNG_INTERLACE) == 0) png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 - png_pass_ystart[0]) / png_pass_yinc[0]; else png_ptr->num_rows = png_ptr->height; png_ptr->iwidth = (png_ptr->width + png_pass_inc[png_ptr->pass] - 1 - png_pass_start[png_ptr->pass]) / png_pass_inc[png_ptr->pass]; } else { png_ptr->num_rows = png_ptr->height; png_ptr->iwidth = png_ptr->width; } max_pixel_depth = (unsigned int)png_ptr->pixel_depth; /* WARNING: * png_read_transform_info (pngrtran.c) performs a simpler set of * calculations to calculate the final pixel depth, then * png_do_read_transforms actually does the transforms. This means that the * code which effectively calculates this value is actually repeated in three * separate places. They must all match. Innocent changes to the order of * transformations can and will break libpng in a way that causes memory * overwrites. * * TODO: fix this. */ #ifdef PNG_READ_PACK_SUPPORTED if ((png_ptr->transformations & PNG_PACK) != 0 && png_ptr->bit_depth < 8) max_pixel_depth = 8; #endif #ifdef PNG_READ_EXPAND_SUPPORTED if ((png_ptr->transformations & PNG_EXPAND) != 0) { if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if (png_ptr->num_trans != 0) max_pixel_depth = 32; else max_pixel_depth = 24; } else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) { if (max_pixel_depth < 8) max_pixel_depth = 8; if (png_ptr->num_trans != 0) max_pixel_depth *= 2; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB) { if (png_ptr->num_trans != 0) { max_pixel_depth *= 4; max_pixel_depth /= 3; } } } #endif #ifdef PNG_READ_EXPAND_16_SUPPORTED if ((png_ptr->transformations & PNG_EXPAND_16) != 0) { # ifdef PNG_READ_EXPAND_SUPPORTED /* In fact it is an error if it isn't supported, but checking is * the safe way. */ if ((png_ptr->transformations & PNG_EXPAND) != 0) { if (png_ptr->bit_depth < 16) max_pixel_depth *= 2; } else # endif png_ptr->transformations &= ~PNG_EXPAND_16; } #endif #ifdef PNG_READ_FILLER_SUPPORTED if ((png_ptr->transformations & (PNG_FILLER)) != 0) { if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY) { if (max_pixel_depth <= 8) max_pixel_depth = 16; else max_pixel_depth = 32; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB || png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) { if (max_pixel_depth <= 32) max_pixel_depth = 32; else max_pixel_depth = 64; } } #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED if ((png_ptr->transformations & PNG_GRAY_TO_RGB) != 0) { if ( #ifdef PNG_READ_EXPAND_SUPPORTED (png_ptr->num_trans != 0 && (png_ptr->transformations & PNG_EXPAND) != 0) || #endif #ifdef PNG_READ_FILLER_SUPPORTED (png_ptr->transformations & (PNG_FILLER)) != 0 || #endif png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { if (max_pixel_depth <= 16) max_pixel_depth = 32; else max_pixel_depth = 64; } else { if (max_pixel_depth <= 8) { if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA) max_pixel_depth = 32; else max_pixel_depth = 24; } else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA) max_pixel_depth = 64; else max_pixel_depth = 48; } } #endif #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \ defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) if ((png_ptr->transformations & PNG_USER_TRANSFORM) != 0) { unsigned int user_pixel_depth = png_ptr->user_transform_depth * png_ptr->user_transform_channels; if (user_pixel_depth > max_pixel_depth) max_pixel_depth = user_pixel_depth; } #endif /* This value is stored in png_struct and double checked in the row read * code. */ png_ptr->maximum_pixel_depth = (png_byte)max_pixel_depth; png_ptr->transformed_pixel_depth = 0; /* calculated on demand */ /* Align the width on the next larger 8 pixels. Mainly used * for interlacing */ row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7)); /* Calculate the maximum bytes needed, adding a byte and a pixel * for safety's sake */ row_bytes = PNG_ROWBYTES(max_pixel_depth, row_bytes) + 1 + ((max_pixel_depth + 7) >> 3U); #ifdef PNG_MAX_MALLOC_64K if (row_bytes > (png_uint_32)65536L) png_error(png_ptr, "This image requires a row greater than 64KB"); #endif if (row_bytes + 48 > png_ptr->old_big_row_buf_size) { png_free(png_ptr, png_ptr->big_row_buf); png_free(png_ptr, png_ptr->big_prev_row); if (png_ptr->interlaced != 0) png_ptr->big_row_buf = (png_bytep)png_calloc(png_ptr, row_bytes + 48); else png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes + 48); png_ptr->big_prev_row = (png_bytep)png_malloc(png_ptr, row_bytes + 48); #ifdef PNG_ALIGNED_MEMORY_SUPPORTED /* Use 16-byte aligned memory for row_buf with at least 16 bytes * of padding before and after row_buf; treat prev_row similarly. * NOTE: the alignment is to the start of the pixels, one beyond the start * of the buffer, because of the filter byte. Prior to libpng 1.5.6 this * was incorrect; the filter byte was aligned, which had the exact * opposite effect of that intended. */ { png_bytep temp = png_ptr->big_row_buf + 32; int extra = (int)((temp - (png_bytep)0) & 0x0f); png_ptr->row_buf = temp - extra - 1/*filter byte*/; temp = png_ptr->big_prev_row + 32; extra = (int)((temp - (png_bytep)0) & 0x0f); png_ptr->prev_row = temp - extra - 1/*filter byte*/; } #else /* Use 31 bytes of padding before and 17 bytes after row_buf. */ png_ptr->row_buf = png_ptr->big_row_buf + 31; png_ptr->prev_row = png_ptr->big_prev_row + 31; #endif png_ptr->old_big_row_buf_size = row_bytes + 48; } #ifdef PNG_MAX_MALLOC_64K if (png_ptr->rowbytes > 65535) png_error(png_ptr, "This image requires a row greater than 64KB"); #endif if (png_ptr->rowbytes > (PNG_SIZE_MAX - 1)) png_error(png_ptr, "Row has too many bytes to allocate in memory"); memset(png_ptr->prev_row, 0, png_ptr->rowbytes + 1); png_debug1(3, "width = %u,", png_ptr->width); png_debug1(3, "height = %u,", png_ptr->height); png_debug1(3, "iwidth = %u,", png_ptr->iwidth); png_debug1(3, "num_rows = %u,", png_ptr->num_rows); png_debug1(3, "rowbytes = %lu,", (unsigned long)png_ptr->rowbytes); png_debug1(3, "irowbytes = %lu", (unsigned long)PNG_ROWBYTES(png_ptr->pixel_depth, png_ptr->iwidth) + 1); /* The sequential reader needs a buffer for IDAT, but the progressive reader * does not, so free the read buffer now regardless; the sequential reader * reallocates it on demand. */ if (png_ptr->read_buffer != NULL) { png_bytep buffer = png_ptr->read_buffer; png_ptr->read_buffer_size = 0; png_ptr->read_buffer = NULL; png_free(png_ptr, buffer); } /* Finally claim the zstream for the inflate of the IDAT data, use the bits * value from the stream (note that this will result in a fatal error if the * IDAT stream has a bogus deflate header window_bits value, but this should * not be happening any longer!) */ if (png_inflate_claim(png_ptr, png_IDAT) != Z_OK) png_error(png_ptr, png_ptr->zstream.msg); png_ptr->flags |= PNG_FLAG_ROW_INIT; } #endif /* READ */
./CrossVul/dataset_final_sorted/CWE-369/c/good_225_0
crossvul-cpp_data_good_3308_0
// imagew-gif.c // Part of ImageWorsener, Copyright (c) 2011 by Jason Summers. // For more information, see the readme.txt file. // This is a self-contained GIF image decoder. // It supports a single image only, so it does not support animated GIFs, // or any GIF where the main image is constructed from multiple sub-images. #include "imagew-config.h" #include <stdlib.h> #include <string.h> #define IW_INCLUDE_UTIL_FUNCTIONS #include "imagew.h" struct iwgifrcontext { struct iw_iodescr *iodescr; struct iw_context *ctx; struct iw_image *img; struct iw_csdescr csdescr; int page; // Page to read. 1=first int screen_width, screen_height; // Same as .img->width, .img->height int image_width, image_height; int image_left, image_top; int include_screen; // Do we paint the image onto the "screen", or just extract it? int screen_initialized; int pages_seen; int interlaced; int bytes_per_pixel; int has_transparency; int has_bg_color; int bg_color_index; int trans_color_index; size_t pixels_set; // Number of pixels decoded so far size_t total_npixels; // Total number of pixels in the "image" (not the "screen") iw_byte **row_pointers; struct iw_palette colortable; // A buffer used when reading the GIF file. // The largest block we need to read is a 256-color palette. iw_byte rbuf[768]; }; static int iwgif_read(struct iwgifrcontext *rctx, iw_byte *buf, size_t buflen) { int ret; size_t bytesread = 0; ret = (*rctx->iodescr->read_fn)(rctx->ctx,rctx->iodescr, buf,buflen,&bytesread); if(!ret || bytesread!=buflen) { return 0; } return 1; } static int iwgif_read_file_header(struct iwgifrcontext *rctx) { if(!iwgif_read(rctx,rctx->rbuf,6)) return 0; if(rctx->rbuf[0]!='G' || rctx->rbuf[1]!='I' || rctx->rbuf[2]!='F') { iw_set_error(rctx->ctx,"Not a GIF file"); return 0; } return 1; } static int iwgif_read_screen_descriptor(struct iwgifrcontext *rctx) { int has_global_ct; int global_ct_size; int aspect_ratio_code; // The screen descriptor is always 7 bytes in size. if(!iwgif_read(rctx,rctx->rbuf,7)) return 0; rctx->screen_width = (int)iw_get_ui16le(&rctx->rbuf[0]); rctx->screen_height = (int)iw_get_ui16le(&rctx->rbuf[2]); // screen_width and _height may be updated in iwgif_init_screen(). has_global_ct = (int)((rctx->rbuf[4]>>7)&0x01); if(has_global_ct) { // Size of global color table global_ct_size = (int)(rctx->rbuf[4]&0x07); rctx->colortable.num_entries = 1<<(1+global_ct_size); // Background color rctx->bg_color_index = (int)rctx->rbuf[5]; if(rctx->bg_color_index < rctx->colortable.num_entries) rctx->has_bg_color = 1; } aspect_ratio_code = (int)rctx->rbuf[6]; if(aspect_ratio_code!=0) { // [aspect ratio = (pixel width)/(pixel height)] rctx->img->density_code = IW_DENSITY_UNITS_UNKNOWN; rctx->img->density_x = 64000.0/(double)(aspect_ratio_code + 15); rctx->img->density_y = 1000.0; } return 1; } // Read a global or local palette into memory. // ct->num_entries must be set by caller static int iwgif_read_color_table(struct iwgifrcontext *rctx, struct iw_palette *ct) { int i; if(ct->num_entries<1) return 1; if(!iwgif_read(rctx,rctx->rbuf,3*ct->num_entries)) return 0; for(i=0;i<ct->num_entries;i++) { ct->entry[i].r = rctx->rbuf[3*i+0]; ct->entry[i].g = rctx->rbuf[3*i+1]; ct->entry[i].b = rctx->rbuf[3*i+2]; } return 1; } static int iwgif_skip_subblocks(struct iwgifrcontext *rctx) { iw_byte subblock_size; while(1) { // Read the subblock size if(!iwgif_read(rctx,rctx->rbuf,1)) return 0; subblock_size = rctx->rbuf[0]; // A size of 0 marks the end of the subblocks. if(subblock_size==0) return 1; // Read the subblock's data if(!iwgif_read(rctx,rctx->rbuf,(size_t)subblock_size)) return 0; } } // We need transparency information, so we have to process graphic control // extensions. static int iwgif_read_graphic_control_ext(struct iwgifrcontext *rctx) { int retval; // Read 6 bytes: // The first is the subblock size, which must be 4. // The last is the block terminator. // The middle 4 contain the actual data. if(!iwgif_read(rctx,rctx->rbuf,6)) goto done; if(rctx->rbuf[0]!=4) goto done; if(rctx->rbuf[5]!=0) goto done; rctx->has_transparency = (int)((rctx->rbuf[1])&0x01); if(rctx->has_transparency) { rctx->trans_color_index = (int)rctx->rbuf[4]; } retval=1; done: return retval; } static int iwgif_read_extension(struct iwgifrcontext *rctx) { int retval=0; iw_byte ext_type; if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; ext_type=rctx->rbuf[0]; switch(ext_type) { case 0xf9: if(rctx->page == rctx->pages_seen+1) { if(!iwgif_read_graphic_control_ext(rctx)) goto done; } else { // This extension's scope does not include the image we're // processing, so ignore it. if(!iwgif_skip_subblocks(rctx)) goto done; } break; default: if(!iwgif_skip_subblocks(rctx)) goto done; } retval=1; done: return retval; } // Set the (rctx->pixels_set + offset)th pixel in the logical image to the // color represented by palette entry #coloridx. static void iwgif_record_pixel(struct iwgifrcontext *rctx, unsigned int coloridx, int offset) { struct iw_image *img; unsigned int r,g,b,a; size_t pixnum; size_t xi,yi; // position in image coordinates size_t xs,ys; // position in screen coordinates iw_byte *ptr; img = rctx->img; // Figure out which pixel to set. pixnum = rctx->pixels_set + offset; xi = pixnum%rctx->image_width; yi = pixnum/rctx->image_width; xs = rctx->image_left + xi; ys = rctx->image_top + yi; // Make sure the coordinate is within the image, and on the screen. if(yi>=(size_t)rctx->image_height) return; if(xs>=(size_t)rctx->screen_width) return; if(ys>=(size_t)rctx->screen_height) return; // Because of how we de-interlace, it's not obvious whether the Y coordinate // is on the screen. The easiest way is to check if the row pointer is NULL. if(rctx->row_pointers[yi]==NULL) return; // Figure out what color to set the pixel to. if(coloridx<(unsigned int)rctx->colortable.num_entries) { r=rctx->colortable.entry[coloridx].r; g=rctx->colortable.entry[coloridx].g; b=rctx->colortable.entry[coloridx].b; a=rctx->colortable.entry[coloridx].a; } else { return; // Illegal palette index } // Set the pixel. ptr = &rctx->row_pointers[yi][rctx->bytes_per_pixel*xi]; ptr[0]=r; ptr[1]=g; ptr[2]=b; if(img->imgtype==IW_IMGTYPE_RGBA) { ptr[3]=a; } } //////////////////////////////////////////////////////// // LZW decoder //////////////////////////////////////////////////////// struct lzw_tableentry { iw_uint16 parent; // pointer to previous table entry (if not a root code) iw_uint16 length; iw_byte firstchar; iw_byte lastchar; }; struct lzwdeccontext { unsigned int root_codesize; unsigned int current_codesize; int eoi_flag; unsigned int oldcode; unsigned int pending_code; unsigned int bits_in_pending_code; unsigned int num_root_codes; int ncodes_since_clear; unsigned int clear_code; unsigned int eoi_code; unsigned int last_code_added; unsigned int ct_used; // Number of items used in the code table struct lzw_tableentry ct[4096]; // Code table }; static void lzw_init(struct lzwdeccontext *d, unsigned int root_codesize) { unsigned int i; iw_zeromem(d,sizeof(struct lzwdeccontext)); d->root_codesize = root_codesize; d->num_root_codes = 1<<d->root_codesize; d->clear_code = d->num_root_codes; d->eoi_code = d->num_root_codes+1; for(i=0;i<d->num_root_codes;i++) { d->ct[i].parent = 0; d->ct[i].length = 1; d->ct[i].lastchar = (iw_byte)i; d->ct[i].firstchar = (iw_byte)i; } } static void lzw_clear(struct lzwdeccontext *d) { d->ct_used = d->num_root_codes+2; d->current_codesize = d->root_codesize+1; d->ncodes_since_clear=0; d->oldcode=0; } // Decode an LZW code to one or more pixels, and record it in the image. static void lzw_emit_code(struct iwgifrcontext *rctx, struct lzwdeccontext *d, unsigned int first_code) { unsigned int code; code = first_code; // An LZW code may decode to more than one pixel. Note that the pixels for // an LZW code are decoded in reverse order (right to left). while(1) { iwgif_record_pixel(rctx, (unsigned int)d->ct[code].lastchar, (int)(d->ct[code].length-1)); if(d->ct[code].length<=1) break; // The codes are structured as a "forest" (multiple trees). // Go to the parent code, which will have a length 1 less than this one. code = (unsigned int)d->ct[code].parent; } // Track the total number of pixels decoded in this image. rctx->pixels_set += d->ct[first_code].length; } // Add a code to the dictionary. // Sets d->last_code_added to the position where it was added. // Returns 1 if successful, 0 if table is full. static int lzw_add_to_dict(struct lzwdeccontext *d, unsigned int oldcode, iw_byte val) { static const unsigned int last_code_of_size[] = { // The first 3 values are unused. 0,0,0,7,15,31,63,127,255,511,1023,2047,4095 }; unsigned int newpos; if(d->ct_used>=4096) { d->last_code_added = 0; return 0; } newpos = d->ct_used; d->ct_used++; d->ct[newpos].parent = (iw_uint16)oldcode; d->ct[newpos].length = d->ct[oldcode].length + 1; d->ct[newpos].firstchar = d->ct[oldcode].firstchar; d->ct[newpos].lastchar = val; // If we've used the last code of this size, we need to increase the codesize. if(newpos == last_code_of_size[d->current_codesize]) { if(d->current_codesize<12) { d->current_codesize++; } } d->last_code_added = newpos; return 1; } // Process a single LZW code that was read from the input stream. static int lzw_process_code(struct iwgifrcontext *rctx, struct lzwdeccontext *d, unsigned int code) { if(code==d->eoi_code) { d->eoi_flag=1; return 1; } if(code==d->clear_code) { lzw_clear(d); return 1; } d->ncodes_since_clear++; if(d->ncodes_since_clear==1) { // Special case for the first code. lzw_emit_code(rctx,d,code); d->oldcode = code; return 1; } // Is code in code table? if(code < d->ct_used) { // Yes, code is in table. lzw_emit_code(rctx,d,code); // Let k = the first character of the translation of the code. // Add <oldcode>k to the dictionary. lzw_add_to_dict(d,d->oldcode,d->ct[code].firstchar); } else { // No, code is not in table. if(d->oldcode>=d->ct_used) { iw_set_error(rctx->ctx,"GIF decoding error"); return 0; } // Let k = the first char of the translation of oldcode. // Add <oldcode>k to the dictionary. if(lzw_add_to_dict(d,d->oldcode,d->ct[d->oldcode].firstchar)) { // Write <oldcode>k to the output stream. lzw_emit_code(rctx,d,d->last_code_added); } } d->oldcode = code; return 1; } // Decode as much as possible of the provided LZW-encoded data. // Any unfinished business is recorded, to be continued the next time // this function is called. static int lzw_process_bytes(struct iwgifrcontext *rctx, struct lzwdeccontext *d, iw_byte *data, size_t data_size) { size_t i; int b; int retval=0; for(i=0;i<data_size;i++) { // Look at the bits one at a time. for(b=0;b<8;b++) { if(d->eoi_flag) { // Stop if we've seen an EOI (end of image) code. retval=1; goto done; } if(data[i]&(1<<b)) d->pending_code |= 1<<d->bits_in_pending_code; d->bits_in_pending_code++; // When we get enough bits to form a complete LZW code, process it. if(d->bits_in_pending_code >= d->current_codesize) { if(!lzw_process_code(rctx,d,d->pending_code)) goto done; d->pending_code=0; d->bits_in_pending_code=0; } } } retval=1; done: return retval; } //////////////////////////////////////////////////////// // Allocate and set up the global "screen". static int iwgif_init_screen(struct iwgifrcontext *rctx) { struct iw_image *img; int bg_visible=0; int retval=0; if(rctx->screen_initialized) return 1; rctx->screen_initialized = 1; img = rctx->img; if(!rctx->include_screen) { // If ->include_screen is disabled, pretend the screen is the same size as // the GIF image, and pretend the GIF image is positioned at (0,0). rctx->screen_width = rctx->image_width; rctx->screen_height = rctx->image_height; rctx->image_left = 0; rctx->image_top = 0; } img->width = rctx->screen_width; img->height = rctx->screen_height; if(!iw_check_image_dimensions(rctx->ctx,img->width,img->height)) { return 0; } if(rctx->image_left>0 || rctx->image_top>0 || (rctx->image_left+rctx->image_width < rctx->screen_width) || (rctx->image_top+rctx->image_height < rctx->screen_height) ) { // Image does not cover the entire "screen". We'll make the exposed // regions of the screen transparent, so set a flag to let us know we // need an image type that supports transparency. bg_visible = 1; } // Allocate IW image if(rctx->has_transparency || bg_visible) { rctx->bytes_per_pixel=4; img->imgtype = IW_IMGTYPE_RGBA; } else { rctx->bytes_per_pixel=3; img->imgtype = IW_IMGTYPE_RGB; } img->bit_depth = 8; img->bpr = rctx->bytes_per_pixel * img->width; img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx, img->bpr, img->height); if(!img->pixels) goto done; // Start by clearing the screen to black, or transparent black. iw_zeromem(img->pixels,img->bpr*img->height); retval=1; done: return retval; } // Make an array of pointers into the global screen, which point to the // start of each row in the local image. This will be useful for // de-interlacing. static int iwgif_make_row_pointers(struct iwgifrcontext *rctx) { struct iw_image *img; int pass; int startrow, rowskip; int rowcount; int row; if(rctx->row_pointers) iw_free(rctx->ctx,rctx->row_pointers); rctx->row_pointers = (iw_byte**)iw_malloc(rctx->ctx, sizeof(iw_byte*)*rctx->image_height); if(!rctx->row_pointers) return 0; img = rctx->img; if(rctx->interlaced) { // Image is interlaced. Rearrange the row pointers, so that it will be // de-interlaced as it is decoded. rowcount=0; for(pass=1;pass<=4;pass++) { if(pass==1) { startrow=0; rowskip=8; } else if(pass==2) { startrow=4; rowskip=8; } else if(pass==3) { startrow=2; rowskip=4; } else { startrow=1; rowskip=2; } for(row=startrow;row<rctx->image_height;row+=rowskip) { if(rctx->image_top+row < rctx->screen_height) { rctx->row_pointers[rowcount] = &img->pixels[(rctx->image_top+row)*img->bpr + (rctx->image_left)*rctx->bytes_per_pixel]; } else { rctx->row_pointers[rowcount] = NULL; } rowcount++; } } } else { // Image is not interlaced. for(row=0;row<rctx->image_height;row++) { if(rctx->image_top+row < rctx->screen_height) { rctx->row_pointers[row] = &img->pixels[(rctx->image_top+row)*img->bpr + (rctx->image_left)*rctx->bytes_per_pixel]; } else { rctx->row_pointers[row] = NULL; } } } return 1; } static int iwgif_skip_image(struct iwgifrcontext *rctx) { int has_local_ct; int local_ct_size; int ct_num_entries; int retval=0; // Read image header information if(!iwgif_read(rctx,rctx->rbuf,9)) goto done; has_local_ct = (int)((rctx->rbuf[8]>>7)&0x01); if(has_local_ct) { local_ct_size = (int)(rctx->rbuf[8]&0x07); ct_num_entries = 1<<(1+local_ct_size); } // Skip the local color table if(has_local_ct) { if(!iwgif_read(rctx,rctx->rbuf,3*ct_num_entries)) goto done; } // Skip the LZW code size if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; // Skip the image pixels if(!iwgif_skip_subblocks(rctx)) goto done; // Reset anything that might have been set by a graphic control extension. // Their scope is the first image that follows them. rctx->has_transparency = 0; retval=1; done: return retval; } static int iwgif_read_image(struct iwgifrcontext *rctx) { int retval=0; struct lzwdeccontext d; size_t subblocksize; int has_local_ct; int local_ct_size; unsigned int root_codesize; // Read image header information if(!iwgif_read(rctx,rctx->rbuf,9)) goto done; rctx->image_left = (int)iw_get_ui16le(&rctx->rbuf[0]); rctx->image_top = (int)iw_get_ui16le(&rctx->rbuf[2]); // image_left and _top may be updated in iwgif_init_screen(). rctx->image_width = (int)iw_get_ui16le(&rctx->rbuf[4]); rctx->image_height = (int)iw_get_ui16le(&rctx->rbuf[6]); if(rctx->image_width<1 || rctx->image_height<1) { iw_set_error(rctx->ctx, "Invalid image dimensions"); goto done; } rctx->interlaced = (int)((rctx->rbuf[8]>>6)&0x01); has_local_ct = (int)((rctx->rbuf[8]>>7)&0x01); if(has_local_ct) { local_ct_size = (int)(rctx->rbuf[8]&0x07); rctx->colortable.num_entries = 1<<(1+local_ct_size); } if(has_local_ct) { // We only support one image, so we don't need to keep both a global and a // local color table. If an image has both, the local table will overwrite // the global one. if(!iwgif_read_color_table(rctx,&rctx->colortable)) goto done; } // Make the transparent color transparent. if(rctx->has_transparency) { rctx->colortable.entry[rctx->trans_color_index].a = 0; } // Read LZW code size if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; root_codesize = (unsigned int)rctx->rbuf[0]; // The spec does not allow the "minimum code size" to be less than 2. // Sizes >=12 are impossible to support. // There's no reason for the size to be larger than 8, but the spec // does not seem to forbid it. if(root_codesize<2 || root_codesize>11) { iw_set_error(rctx->ctx,"Invalid LZW minimum code size"); goto done; } // The creation of the global "screen" was deferred until now, to wait until // we know whether the image has transparency. // (And if !rctx->include_screen, to wait until we know the size of the image.) if(!iwgif_init_screen(rctx)) goto done; rctx->total_npixels = (size_t)rctx->image_width * (size_t)rctx->image_height; if(!iwgif_make_row_pointers(rctx)) goto done; lzw_init(&d,root_codesize); lzw_clear(&d); while(1) { // Read size of next subblock if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; subblocksize = (size_t)rctx->rbuf[0]; if(subblocksize==0) break; // Read next subblock if(!iwgif_read(rctx,rctx->rbuf,subblocksize)) goto done; if(!lzw_process_bytes(rctx,&d,rctx->rbuf,subblocksize)) goto done; if(d.eoi_flag) break; // Stop if we reached the end of the image. We don't care if we've read an // EOI code or not. if(rctx->pixels_set >= rctx->total_npixels) break; } retval=1; done: return retval; } static int iwgif_read_main(struct iwgifrcontext *rctx) { int retval=0; int i; int image_found=0; // Make all colors opaque by default. for(i=0;i<256;i++) { rctx->colortable.entry[i].a=255; } if(!iwgif_read_file_header(rctx)) goto done; if(!iwgif_read_screen_descriptor(rctx)) goto done; // Read global color table if(!iwgif_read_color_table(rctx,&rctx->colortable)) goto done; // Tell IW the background color. if(rctx->has_bg_color) { iw_set_input_bkgd_label(rctx->ctx, ((double)rctx->colortable.entry[rctx->bg_color_index].r)/255.0, ((double)rctx->colortable.entry[rctx->bg_color_index].g)/255.0, ((double)rctx->colortable.entry[rctx->bg_color_index].b)/255.0); } // The remainder of the file consists of blocks whose type is indicated by // their initial byte. while(!image_found) { // Read block type if(!iwgif_read(rctx,rctx->rbuf,1)) goto done; switch(rctx->rbuf[0]) { case 0x21: // extension if(!iwgif_read_extension(rctx)) goto done; break; case 0x2c: // image rctx->pages_seen++; if(rctx->page == rctx->pages_seen) { if(!iwgif_read_image(rctx)) goto done; image_found=1; } else { if(!iwgif_skip_image(rctx)) goto done; } break; case 0x3b: // file trailer // We stop after we decode an image, so if we ever see a file // trailer, something's wrong. if(rctx->pages_seen==0) iw_set_error(rctx->ctx,"No image in file"); else iw_set_error(rctx->ctx,"Image not found"); goto done; default: iw_set_error(rctx->ctx,"Invalid or unsupported GIF file"); goto done; } } retval=1; done: return retval; } IW_IMPL(int) iw_read_gif_file(struct iw_context *ctx, struct iw_iodescr *iodescr) { struct iw_image img; struct iwgifrcontext *rctx = NULL; int retval=0; iw_zeromem(&img,sizeof(struct iw_image)); rctx = iw_mallocz(ctx,sizeof(struct iwgifrcontext)); if(!rctx) goto done; rctx->ctx = ctx; rctx->iodescr = iodescr; rctx->img = &img; // Assume GIF images are sRGB. iw_make_srgb_csdescr_2(&rctx->csdescr); rctx->page = iw_get_value(ctx,IW_VAL_PAGE_TO_READ); if(rctx->page<1) rctx->page = 1; rctx->include_screen = iw_get_value(ctx,IW_VAL_INCLUDE_SCREEN); if(!iwgif_read_main(rctx)) goto done; iw_set_input_image(ctx, &img); iw_set_input_colorspace(ctx,&rctx->csdescr); retval = 1; done: if(!retval) { iw_set_error(ctx,"Failed to read GIF file"); } if(rctx) { if(rctx->row_pointers) iw_free(ctx,rctx->row_pointers); iw_free(ctx,rctx); } return retval; }
./CrossVul/dataset_final_sorted/CWE-369/c/good_3308_0
crossvul-cpp_data_bad_258_0
/* * MOV, 3GP, MP4 muxer * Copyright (c) 2003 Thomas Raivio * Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org> * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com> * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdint.h> #include <inttypes.h> #include "movenc.h" #include "avformat.h" #include "avio_internal.h" #include "riff.h" #include "avio.h" #include "isom.h" #include "avc.h" #include "libavcodec/ac3_parser_internal.h" #include "libavcodec/dnxhddata.h" #include "libavcodec/flac.h" #include "libavcodec/get_bits.h" #include "libavcodec/internal.h" #include "libavcodec/put_bits.h" #include "libavcodec/vc1_common.h" #include "libavcodec/raw.h" #include "internal.h" #include "libavutil/avstring.h" #include "libavutil/intfloat.h" #include "libavutil/mathematics.h" #include "libavutil/libm.h" #include "libavutil/opt.h" #include "libavutil/dict.h" #include "libavutil/pixdesc.h" #include "libavutil/stereo3d.h" #include "libavutil/timecode.h" #include "libavutil/color_utils.h" #include "hevc.h" #include "rtpenc.h" #include "mov_chan.h" #include "vpcc.h" static const AVOption options[] = { { "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 }, { "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, { "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" }, FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags), { "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM}, { "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM}, { "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM }, { "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"}, { "empty_hdlr_name", "write zero-length name string in hdlr atoms within mdia and minf atoms", offsetof(MOVMuxContext, empty_hdlr_name), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { NULL }, }; #define MOV_CLASS(flavor)\ static const AVClass flavor ## _muxer_class = {\ .class_name = #flavor " muxer",\ .item_name = av_default_item_name,\ .option = options,\ .version = LIBAVUTIL_VERSION_INT,\ }; static int get_moov_size(AVFormatContext *s); static int utf8len(const uint8_t *b) { int len = 0; int val; while (*b) { GET_UTF8(val, *b++, return -1;) len++; } return len; } //FIXME support 64 bit variant with wide placeholders static int64_t update_size(AVIOContext *pb, int64_t pos) { int64_t curpos = avio_tell(pb); avio_seek(pb, pos, SEEK_SET); avio_wb32(pb, curpos - pos); /* rewrite size */ avio_seek(pb, curpos, SEEK_SET); return curpos - pos; } static int co64_required(const MOVTrack *track) { if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX) return 1; return 0; } static int is_cover_image(const AVStream *st) { /* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS * is encoded as sparse video track */ return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC; } static int rtp_hinting_needed(const AVStream *st) { /* Add hint tracks for each real audio and video stream */ if (is_cover_image(st)) return 0; return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO; } /* Chunk offset atom */ static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track) { int i; int mode64 = co64_required(track); // use 32 bit size variant if possible int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ if (mode64) ffio_wfourcc(pb, "co64"); else ffio_wfourcc(pb, "stco"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->chunkCount); /* entry count */ for (i = 0; i < track->entry; i++) { if (!track->cluster[i].chunkNum) continue; if (mode64 == 1) avio_wb64(pb, track->cluster[i].pos + track->data_offset); else avio_wb32(pb, track->cluster[i].pos + track->data_offset); } return update_size(pb, pos); } /* Sample size atom */ static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track) { int equalChunks = 1; int i, j, entries = 0, tst = -1, oldtst = -1; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsz"); avio_wb32(pb, 0); /* version & flags */ for (i = 0; i < track->entry; i++) { tst = track->cluster[i].size / track->cluster[i].entries; if (oldtst != -1 && tst != oldtst) equalChunks = 0; oldtst = tst; entries += track->cluster[i].entries; } if (equalChunks && track->entry) { int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0; sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0 avio_wb32(pb, sSize); // sample size avio_wb32(pb, entries); // sample count } else { avio_wb32(pb, 0); // sample size avio_wb32(pb, entries); // sample count for (i = 0; i < track->entry; i++) { for (j = 0; j < track->cluster[i].entries; j++) { avio_wb32(pb, track->cluster[i].size / track->cluster[i].entries); } } } return update_size(pb, pos); } /* Sample to chunk atom */ static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track) { int index = 0, oldval = -1, i; int64_t entryPos, curpos; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsc"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->chunkCount); // entry count for (i = 0; i < track->entry; i++) { if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) { avio_wb32(pb, track->cluster[i].chunkNum); // first chunk avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk avio_wb32(pb, 0x1); // sample description index oldval = track->cluster[i].samples_in_chunk; index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sync sample atom */ static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag) { int64_t curpos, entryPos; int i, index = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps"); avio_wb32(pb, 0); // version & flags entryPos = avio_tell(pb); avio_wb32(pb, track->entry); // entry count for (i = 0; i < track->entry; i++) { if (track->cluster[i].flags & flag) { avio_wb32(pb, i + 1); index++; } } curpos = avio_tell(pb); avio_seek(pb, entryPos, SEEK_SET); avio_wb32(pb, index); // rewrite size avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } /* Sample dependency atom */ static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track) { int i; uint8_t leading, dependent, reference, redundancy; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "sdtp"); avio_wb32(pb, 0); // version & flags for (i = 0; i < track->entry; i++) { dependent = MOV_SAMPLE_DEPENDENCY_YES; leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN; if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) { reference = MOV_SAMPLE_DEPENDENCY_NO; } if (track->cluster[i].flags & MOV_SYNC_SAMPLE) { dependent = MOV_SAMPLE_DEPENDENCY_NO; } avio_w8(pb, (leading << 6) | (dependent << 4) | (reference << 2) | redundancy); } return update_size(pb, pos); } static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x11); /* size */ if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr"); else ffio_wfourcc(pb, "damr"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */ avio_w8(pb, 0x00); /* Mode change period (no restriction) */ avio_w8(pb, 0x01); /* Frames per sample */ return 0x11; } static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track) { GetBitContext gbc; PutBitContext pbc; uint8_t buf[3]; int fscod, bsid, bsmod, acmod, lfeon, frmsizecod; if (track->vos_len < 7) return -1; avio_wb32(pb, 11); ffio_wfourcc(pb, "dac3"); init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8); fscod = get_bits(&gbc, 2); frmsizecod = get_bits(&gbc, 6); bsid = get_bits(&gbc, 5); bsmod = get_bits(&gbc, 3); acmod = get_bits(&gbc, 3); if (acmod == 2) { skip_bits(&gbc, 2); // dsurmod } else { if ((acmod & 1) && acmod != 1) skip_bits(&gbc, 2); // cmixlev if (acmod & 4) skip_bits(&gbc, 2); // surmixlev } lfeon = get_bits1(&gbc); init_put_bits(&pbc, buf, sizeof(buf)); put_bits(&pbc, 2, fscod); put_bits(&pbc, 5, bsid); put_bits(&pbc, 3, bsmod); put_bits(&pbc, 3, acmod); put_bits(&pbc, 1, lfeon); put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code put_bits(&pbc, 5, 0); // reserved flush_put_bits(&pbc); avio_write(pb, buf, sizeof(buf)); return 11; } struct eac3_info { AVPacket pkt; uint8_t ec3_done; uint8_t num_blocks; /* Layout of the EC3SpecificBox */ /* maximum bitrate */ uint16_t data_rate; /* number of independent substreams */ uint8_t num_ind_sub; struct { /* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */ uint8_t fscod; /* bit stream identification 5 bits */ uint8_t bsid; /* one bit reserved */ /* audio service mixing (not supported yet) 1 bit */ /* bit stream mode 3 bits */ uint8_t bsmod; /* audio coding mode 3 bits */ uint8_t acmod; /* sub woofer on 1 bit */ uint8_t lfeon; /* 3 bits reserved */ /* number of dependent substreams associated with this substream 4 bits */ uint8_t num_dep_sub; /* channel locations of the dependent substream(s), if any, 9 bits */ uint16_t chan_loc; /* if there is no dependent substream, then one bit reserved instead */ } substream[1]; /* TODO: support 8 independent substreams */ }; #if CONFIG_AC3_PARSER static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track) { AC3HeaderInfo *hdr = NULL; struct eac3_info *info; int num_blocks, ret; if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info)))) return AVERROR(ENOMEM); info = track->eac3_priv; if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) { /* drop the packets until we see a good one */ if (!track->entry) { av_log(mov->fc, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n"); ret = 0; } else ret = AVERROR_INVALIDDATA; goto end; } info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000); num_blocks = hdr->num_blocks; if (!info->ec3_done) { /* AC-3 substream must be the first one */ if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) { ret = AVERROR(EINVAL); goto end; } /* this should always be the case, given that our AC-3 parser * concatenates dependent frames to their independent parent */ if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) { /* substream ids must be incremental */ if (hdr->substreamid > info->num_ind_sub + 1) { ret = AVERROR(EINVAL); goto end; } if (hdr->substreamid == info->num_ind_sub + 1) { //info->num_ind_sub++; avpriv_request_sample(mov->fc, "Multiple independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } else if (hdr->substreamid < info->num_ind_sub || hdr->substreamid == 0 && info->substream[0].bsid) { info->ec3_done = 1; goto concatenate; } } else { if (hdr->substreamid != 0) { avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams"); ret = AVERROR_PATCHWELCOME; goto end; } } /* fill the info needed for the "dec3" atom */ info->substream[hdr->substreamid].fscod = hdr->sr_code; info->substream[hdr->substreamid].bsid = hdr->bitstream_id; info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode; info->substream[hdr->substreamid].acmod = hdr->channel_mode; info->substream[hdr->substreamid].lfeon = hdr->lfe_on; /* Parse dependent substream(s), if any */ if (pkt->size != hdr->frame_size) { int cumul_size = hdr->frame_size; int parent = hdr->substreamid; while (cumul_size != pkt->size) { GetBitContext gbc; int i; ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size); if (ret < 0) goto end; if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) { ret = AVERROR(EINVAL); goto end; } info->substream[parent].num_dep_sub++; ret /= 8; /* header is parsed up to lfeon, but custom channel map may be needed */ init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret); /* skip bsid */ skip_bits(&gbc, 5); /* skip volume control params */ for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) { skip_bits(&gbc, 5); // skip dialog normalization if (get_bits1(&gbc)) { skip_bits(&gbc, 8); // skip compression gain word } } /* get the dependent stream channel map, if exists */ if (get_bits1(&gbc)) info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f; else info->substream[parent].chan_loc |= hdr->channel_mode; cumul_size += hdr->frame_size; } } } concatenate: if (!info->num_blocks && num_blocks == 6) { ret = pkt->size; goto end; } else if (info->num_blocks + num_blocks > 6) { ret = AVERROR_INVALIDDATA; goto end; } if (!info->num_blocks) { ret = av_packet_ref(&info->pkt, pkt); if (!ret) info->num_blocks = num_blocks; goto end; } else { if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0) goto end; memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size); info->num_blocks += num_blocks; info->pkt.duration += pkt->duration; if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0) goto end; if (info->num_blocks != 6) goto end; av_packet_unref(pkt); av_packet_move_ref(pkt, &info->pkt); info->num_blocks = 0; } ret = pkt->size; end: av_free(hdr); return ret; } #endif static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track) { PutBitContext pbc; uint8_t *buf; struct eac3_info *info; int size, i; if (!track->eac3_priv) return AVERROR(EINVAL); info = track->eac3_priv; size = 2 + 4 * (info->num_ind_sub + 1); buf = av_malloc(size); if (!buf) { size = AVERROR(ENOMEM); goto end; } init_put_bits(&pbc, buf, size); put_bits(&pbc, 13, info->data_rate); put_bits(&pbc, 3, info->num_ind_sub); for (i = 0; i <= info->num_ind_sub; i++) { put_bits(&pbc, 2, info->substream[i].fscod); put_bits(&pbc, 5, info->substream[i].bsid); put_bits(&pbc, 1, 0); /* reserved */ put_bits(&pbc, 1, 0); /* asvc */ put_bits(&pbc, 3, info->substream[i].bsmod); put_bits(&pbc, 3, info->substream[i].acmod); put_bits(&pbc, 1, info->substream[i].lfeon); put_bits(&pbc, 5, 0); /* reserved */ put_bits(&pbc, 4, info->substream[i].num_dep_sub); if (!info->substream[i].num_dep_sub) { put_bits(&pbc, 1, 0); /* reserved */ size--; } else { put_bits(&pbc, 9, info->substream[i].chan_loc); } } flush_put_bits(&pbc); avio_wb32(pb, size + 8); ffio_wfourcc(pb, "dec3"); avio_write(pb, buf, size); av_free(buf); end: av_packet_unref(&info->pkt); av_freep(&track->eac3_priv); return size; } /** * This function writes extradata "as is". * Extradata must be formatted like a valid atom (with size and tag). */ static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track) { avio_write(pb, track->par->extradata, track->par->extradata_size); return track->par->extradata_size; } static int mov_write_enda_tag(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 1); /* little endian */ return 10; } static int mov_write_enda_tag_be(AVIOContext *pb) { avio_wb32(pb, 10); ffio_wfourcc(pb, "enda"); avio_wb16(pb, 0); /* big endian */ return 10; } static void put_descr(AVIOContext *pb, int tag, unsigned int size) { int i = 3; avio_w8(pb, tag); for (; i > 0; i--) avio_w8(pb, (size >> (7 * i)) | 0x80); avio_w8(pb, size & 0x7F); } static unsigned compute_avg_bitrate(MOVTrack *track) { uint64_t size = 0; int i; if (!track->track_duration) return 0; for (i = 0; i < track->entry; i++) size += track->cluster[i].size; return size * 8 * track->timescale / track->track_duration; } static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic { AVCPBProperties *props; int64_t pos = avio_tell(pb); int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0; unsigned avg_bitrate; avio_wb32(pb, 0); // size ffio_wfourcc(pb, "esds"); avio_wb32(pb, 0); // Version // ES descriptor put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1); avio_wb16(pb, track->track_id); avio_w8(pb, 0x00); // flags (= no flags) // DecoderConfig descriptor put_descr(pb, 0x04, 13 + decoder_specific_info_len); // Object type indication if ((track->par->codec_id == AV_CODEC_ID_MP2 || track->par->codec_id == AV_CODEC_ID_MP3) && track->par->sample_rate > 24000) avio_w8(pb, 0x6B); // 11172-3 else avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id)); // the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio) // plus 1 bit to indicate upstream and 1 bit set to 1 (reserved) if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream) else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_w8(pb, 0x15); // flags (= Audiostream) else avio_w8(pb, 0x11); // flags (= Visualstream) props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB avg_bitrate = compute_avg_bitrate(track); avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window) avio_wb32(pb, avg_bitrate); if (track->vos_len) { // DecoderSpecific info descriptor put_descr(pb, 0x05, track->vos_len); avio_write(pb, track->vos_data, track->vos_len); } // SL descriptor put_descr(pb, 0x06, 1); avio_w8(pb, 0x02); return update_size(pb, pos); } static int mov_pcm_le_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24LE || codec_id == AV_CODEC_ID_PCM_S32LE || codec_id == AV_CODEC_ID_PCM_F32LE || codec_id == AV_CODEC_ID_PCM_F64LE; } static int mov_pcm_be_gt16(enum AVCodecID codec_id) { return codec_id == AV_CODEC_ID_PCM_S24BE || codec_id == AV_CODEC_ID_PCM_S32BE || codec_id == AV_CODEC_ID_PCM_F32BE || codec_id == AV_CODEC_ID_PCM_F64BE; } static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); avio_wl32(pb, track->tag); // store it byteswapped track->par->codec_tag = av_bswap16(track->tag >> 16); if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0) return ret; return update_size(pb, pos); } static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int ret; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "wfex"); if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0) return ret; return update_size(pb, pos); } static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dfLa"); avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ /* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */ if (track->par->extradata_size != FLAC_STREAMINFO_SIZE) return AVERROR_INVALIDDATA; /* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */ avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */ avio_wb24(pb, track->par->extradata_size); /* Length */ avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */ return update_size(pb, pos); } static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "dOps"); avio_w8(pb, 0); /* Version */ if (track->par->extradata_size < 19) { av_log(pb, AV_LOG_ERROR, "invalid extradata size\n"); return AVERROR_INVALIDDATA; } /* extradata contains an Ogg OpusHead, other than byte-ordering and OpusHead's preceeding magic/version, OpusSpecificBox is currently identical. */ avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */ avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */ avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */ avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */ /* Write the rest of the header out without byte-swapping. */ avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18); return update_size(pb, pos); } static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { uint32_t layout_tag, bitmap; int64_t pos = avio_tell(pb); layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id, track->par->channel_layout, &bitmap); if (!layout_tag) { av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to " "lack of channel information\n"); return 0; } if (track->multichannel_as_mono) return 0; avio_wb32(pb, 0); // Size ffio_wfourcc(pb, "chan"); // Type avio_w8(pb, 0); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, layout_tag); // mChannelLayoutTag avio_wb32(pb, bitmap); // mChannelBitmap avio_wb32(pb, 0); // mNumberChannelDescriptions return update_size(pb, pos); } static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "wave"); if (track->par->codec_id != AV_CODEC_ID_QDM2) { avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "frma"); avio_wl32(pb, track->tag); } if (track->par->codec_id == AV_CODEC_ID_AAC) { /* useless atom needed by mplayer, ipod, not needed by quicktime */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0); mov_write_esds_tag(pb, track); } else if (mov_pcm_le_gt16(track->par->codec_id)) { mov_write_enda_tag(pb); } else if (mov_pcm_be_gt16(track->par->codec_id)) { mov_write_enda_tag_be(pb); } else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) { mov_write_amr_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_AC3) { mov_write_ac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_EAC3) { mov_write_eac3_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_QDM2) { mov_write_extradata_tag(pb, track); } else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { mov_write_ms_tag(s, pb, track); } avio_wb32(pb, 8); /* size */ avio_wb32(pb, 0); /* null tag */ return update_size(pb, pos); } static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf) { uint8_t *unescaped; const uint8_t *start, *next, *end = track->vos_data + track->vos_len; int unescaped_size, seq_found = 0; int level = 0, interlace = 0; int packet_seq = track->vc1_info.packet_seq; int packet_entry = track->vc1_info.packet_entry; int slices = track->vc1_info.slices; PutBitContext pbc; if (track->start_dts == AV_NOPTS_VALUE) { /* No packets written yet, vc1_info isn't authoritative yet. */ /* Assume inline sequence and entry headers. */ packet_seq = packet_entry = 1; av_log(NULL, AV_LOG_WARNING, "moov atom written before any packets, unable to write correct " "dvc1 atom. Set the delay_moov flag to fix this.\n"); } unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE); if (!unescaped) return AVERROR(ENOMEM); start = find_next_marker(track->vos_data, end); for (next = start; next < end; start = next) { GetBitContext gb; int size; next = find_next_marker(start + 4, end); size = next - start - 4; if (size <= 0) continue; unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped); init_get_bits(&gb, unescaped, 8 * unescaped_size); if (AV_RB32(start) == VC1_CODE_SEQHDR) { int profile = get_bits(&gb, 2); if (profile != PROFILE_ADVANCED) { av_free(unescaped); return AVERROR(ENOSYS); } seq_found = 1; level = get_bits(&gb, 3); /* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag, * width, height */ skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12); skip_bits(&gb, 1); /* broadcast */ interlace = get_bits1(&gb); skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */ } } if (!seq_found) { av_free(unescaped); return AVERROR(ENOSYS); } init_put_bits(&pbc, buf, 7); /* VC1DecSpecStruc */ put_bits(&pbc, 4, 12); /* profile - advanced */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* reserved */ /* VC1AdvDecSpecStruc */ put_bits(&pbc, 3, level); put_bits(&pbc, 1, 0); /* cbr */ put_bits(&pbc, 6, 0); /* reserved */ put_bits(&pbc, 1, !interlace); /* no interlace */ put_bits(&pbc, 1, !packet_seq); /* no multiple seq */ put_bits(&pbc, 1, !packet_entry); /* no multiple entry */ put_bits(&pbc, 1, !slices); /* no slice code */ put_bits(&pbc, 1, 0); /* no bframe */ put_bits(&pbc, 1, 0); /* reserved */ /* framerate */ if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0) put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den); else put_bits32(&pbc, 0xffffffff); flush_put_bits(&pbc); av_free(unescaped); return 0; } static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track) { uint8_t buf[7] = { 0 }; int ret; if ((ret = mov_write_dvc1_structs(track, buf)) < 0) return ret; avio_wb32(pb, track->vos_len + 8 + sizeof(buf)); ffio_wfourcc(pb, "dvc1"); avio_write(pb, buf, sizeof(buf)); avio_write(pb, track->vos_data, track->vos_len); return 0; } static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, track->vos_len + 8); ffio_wfourcc(pb, "glbl"); avio_write(pb, track->vos_data, track->vos_len); return 8 + track->vos_len; } /** * Compute flags for 'lpcm' tag. * See CoreAudioTypes and AudioStreamBasicDescription at Apple. */ static int mov_get_lpcm_flags(enum AVCodecID codec_id) { switch (codec_id) { case AV_CODEC_ID_PCM_F32BE: case AV_CODEC_ID_PCM_F64BE: return 11; case AV_CODEC_ID_PCM_F32LE: case AV_CODEC_ID_PCM_F64LE: return 9; case AV_CODEC_ID_PCM_U8: return 10; case AV_CODEC_ID_PCM_S16BE: case AV_CODEC_ID_PCM_S24BE: case AV_CODEC_ID_PCM_S32BE: return 14; case AV_CODEC_ID_PCM_S8: case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S24LE: case AV_CODEC_ID_PCM_S32LE: return 12; default: return 0; } } static int get_cluster_duration(MOVTrack *track, int cluster_idx) { int64_t next_dts; if (cluster_idx >= track->entry) return 0; if (cluster_idx + 1 == track->entry) next_dts = track->track_duration + track->start_dts; else next_dts = track->cluster[cluster_idx + 1].dts; next_dts -= track->cluster[cluster_idx].dts; av_assert0(next_dts >= 0); av_assert0(next_dts <= INT_MAX); return next_dts; } static int get_samples_per_packet(MOVTrack *track) { int i, first_duration; // return track->par->frame_size; /* use 1 for raw PCM */ if (!track->audio_vbr) return 1; /* check to see if duration is constant for all clusters */ if (!track->entry) return 0; first_duration = get_cluster_duration(track, 0); for (i = 1; i < track->entry; i++) { if (get_cluster_duration(track, i) != first_duration) return 0; } return first_duration; } static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int version = 0; uint32_t tag = track->tag; if (track->mode == MODE_MOV) { if (track->timescale > UINT16_MAX) { if (mov_get_lpcm_flags(track->par->codec_id)) tag = AV_RL32("lpcm"); version = 2; } else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id) || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2) { version = 1; } } avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "enca"); } else { avio_wl32(pb, tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */ /* SoundDescription */ avio_wb16(pb, version); /* Version */ avio_wb16(pb, 0); /* Revision level */ avio_wb32(pb, 0); /* Reserved */ if (version == 2) { avio_wb16(pb, 3); avio_wb16(pb, 16); avio_wb16(pb, 0xfffe); avio_wb16(pb, 0); avio_wb32(pb, 0x00010000); avio_wb32(pb, 72); avio_wb64(pb, av_double2int(track->par->sample_rate)); avio_wb32(pb, track->par->channels); avio_wb32(pb, 0x7F000000); avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id)); avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id)); avio_wb32(pb, track->sample_size); avio_wb32(pb, get_samples_per_packet(track)); } else { if (track->mode == MODE_MOV) { avio_wb16(pb, track->par->channels); if (track->par->codec_id == AV_CODEC_ID_PCM_U8 || track->par->codec_id == AV_CODEC_ID_PCM_S8) avio_wb16(pb, 8); /* bits per sample */ else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726) avio_wb16(pb, track->par->bits_per_coded_sample); else avio_wb16(pb, 16); avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */ } else { /* reserved for mp4/3gp */ if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { avio_wb16(pb, track->par->channels); } else { avio_wb16(pb, 2); } if (track->par->codec_id == AV_CODEC_ID_FLAC) { avio_wb16(pb, track->par->bits_per_raw_sample); } else { avio_wb16(pb, 16); } avio_wb16(pb, 0); } avio_wb16(pb, 0); /* packet size (= 0) */ if (track->par->codec_id == AV_CODEC_ID_OPUS) avio_wb16(pb, 48000); else avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ? track->par->sample_rate : 0); avio_wb16(pb, 0); /* Reserved */ } if (version == 1) { /* SoundDescription V1 extended info */ if (mov_pcm_le_gt16(track->par->codec_id) || mov_pcm_be_gt16(track->par->codec_id)) avio_wb32(pb, 1); /* must be 1 for uncompressed formats */ else avio_wb32(pb, track->par->frame_size); /* Samples per packet */ avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */ avio_wb32(pb, track->sample_size); /* Bytes per frame */ avio_wb32(pb, 2); /* Bytes per sample */ } if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_AAC || track->par->codec_id == AV_CODEC_ID_AC3 || track->par->codec_id == AV_CODEC_ID_EAC3 || track->par->codec_id == AV_CODEC_ID_AMR_NB || track->par->codec_id == AV_CODEC_ID_ALAC || track->par->codec_id == AV_CODEC_ID_ADPCM_MS || track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || track->par->codec_id == AV_CODEC_ID_QDM2 || (mov_pcm_le_gt16(track->par->codec_id) && version==1) || (mov_pcm_be_gt16(track->par->codec_id) && version==1))) mov_write_wave_tag(s, pb, track); else if (track->tag == MKTAG('m','p','4','a')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) mov_write_amr_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_AC3) mov_write_ac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_EAC3) mov_write_eac3_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_ALAC) mov_write_extradata_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) mov_write_wfex_tag(s, pb, track); else if (track->par->codec_id == AV_CODEC_ID_FLAC) mov_write_dfla_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_OPUS) mov_write_dops_tag(pb, track); else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_chan_tag(s, pb, track); if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } return update_size(pb, pos); } static int mov_write_d263_tag(AVIOContext *pb) { avio_wb32(pb, 0xf); /* size */ ffio_wfourcc(pb, "d263"); ffio_wfourcc(pb, "FFMP"); avio_w8(pb, 0); /* decoder version */ /* FIXME use AVCodecContext level/profile, when encoder will set values */ avio_w8(pb, 0xa); /* level */ avio_w8(pb, 0); /* profile */ return 0xf; } static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "avcC"); ff_isom_write_avcc(pb, track->vos_data, track->vos_len); return update_size(pb, pos); } static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "vpcC"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); /* flags */ ff_isom_write_vpcc(s, pb, track->par); return update_size(pb, pos); } static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "hvcC"); if (track->tag == MKTAG('h','v','c','1')) ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1); else ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0); return update_size(pb, pos); } /* also used by all avid codecs (dv, imx, meridien) and their variants */ static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track) { int i; int interlaced; int cid; int display_width = track->par->width; if (track->vos_data && track->vos_len > 0x29) { if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) { /* looks like a DNxHD bit stream */ interlaced = (track->vos_data[5] & 2); cid = AV_RB32(track->vos_data + 0x28); } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n"); return 0; } } else { av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n"); return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "ACLR"); ffio_wfourcc(pb, "0001"); if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */ track->par->color_range == AVCOL_RANGE_UNSPECIFIED) { avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */ } else { /* Full range (0-255) */ avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */ } avio_wb32(pb, 0); /* unknown */ if (track->tag == MKTAG('A','V','d','h')) { avio_wb32(pb, 32); ffio_wfourcc(pb, "ADHR"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 0); /* unknown */ return 0; } avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "APRG"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 120); /* size */ ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "ARES"); ffio_wfourcc(pb, "0001"); avio_wb32(pb, cid); /* dnxhd cid, some id ? */ if ( track->par->sample_aspect_ratio.num > 0 && track->par->sample_aspect_ratio.den > 0) display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den; avio_wb32(pb, display_width); /* values below are based on samples created with quicktime and avid codecs */ if (interlaced) { avio_wb32(pb, track->par->height / 2); avio_wb32(pb, 2); /* unknown */ avio_wb32(pb, 0); /* unknown */ avio_wb32(pb, 4); /* unknown */ } else { avio_wb32(pb, track->par->height); avio_wb32(pb, 1); /* unknown */ avio_wb32(pb, 0); /* unknown */ if (track->par->height == 1080) avio_wb32(pb, 5); /* unknown */ else avio_wb32(pb, 6); /* unknown */ } /* padding */ for (i = 0; i < 10; i++) avio_wb64(pb, 0); return 0; } static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 12); ffio_wfourcc(pb, "DpxE"); if (track->par->extradata_size >= 12 && !memcmp(&track->par->extradata[4], "DpxE", 4)) { avio_wb32(pb, track->par->extradata[11]); } else { avio_wb32(pb, 1); } return 0; } static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (track->par->width == 720) { /* SD */ if (track->par->height == 480) { /* NTSC */ if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n'); else tag = MKTAG('d','v','c',' '); }else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p'); else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p'); else tag = MKTAG('d','v','p','p'); } else if (track->par->height == 720) { /* HD 720 line */ if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q'); else tag = MKTAG('d','v','h','p'); } else if (track->par->height == 1080) { /* HD 1080 line */ if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5'); else tag = MKTAG('d','v','h','6'); } else { av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n"); return 0; } return tag; } static AVRational find_fps(AVFormatContext *s, AVStream *st) { AVRational rate = st->avg_frame_rate; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS rate = av_inv_q(st->codec->time_base); if (av_timecode_check_frame_rate(rate) < 0) { av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n", rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den); rate = st->avg_frame_rate; } FF_ENABLE_DEPRECATION_WARNINGS #endif return rate; } static int defined_frame_rate(AVFormatContext *s, AVStream *st) { AVRational rational_framerate = find_fps(s, st); int rate = 0; if (rational_framerate.den != 0) rate = av_q2d(rational_framerate); return rate; } static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('m', '2', 'v', '1'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','4'); else if (rate == 25) tag = MKTAG('x','d','v','5'); else if (rate == 30) tag = MKTAG('x','d','v','1'); else if (rate == 50) tag = MKTAG('x','d','v','a'); else if (rate == 60) tag = MKTAG('x','d','v','9'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','6'); else if (rate == 25) tag = MKTAG('x','d','v','7'); else if (rate == 30) tag = MKTAG('x','d','v','8'); } else { if (rate == 25) tag = MKTAG('x','d','v','3'); else if (rate == 30) tag = MKTAG('x','d','v','2'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','v','d'); else if (rate == 25) tag = MKTAG('x','d','v','e'); else if (rate == 30) tag = MKTAG('x','d','v','f'); } else { if (rate == 25) tag = MKTAG('x','d','v','c'); else if (rate == 30) tag = MKTAG('x','d','v','b'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','4'); else if (rate == 25) tag = MKTAG('x','d','5','5'); else if (rate == 30) tag = MKTAG('x','d','5','1'); else if (rate == 50) tag = MKTAG('x','d','5','a'); else if (rate == 60) tag = MKTAG('x','d','5','9'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('x','d','5','d'); else if (rate == 25) tag = MKTAG('x','d','5','e'); else if (rate == 30) tag = MKTAG('x','d','5','f'); } else { if (rate == 25) tag = MKTAG('x','d','5','c'); else if (rate == 30) tag = MKTAG('x','d','5','b'); } } } return tag; } static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(s, st); if (!tag) tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag if (track->par->format == AV_PIX_FMT_YUV420P10) { if (track->par->width == 960 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','p'); else if (rate == 25) tag = MKTAG('a','i','5','q'); else if (rate == 30) tag = MKTAG('a','i','5','p'); else if (rate == 50) tag = MKTAG('a','i','5','q'); else if (rate == 60) tag = MKTAG('a','i','5','p'); } } else if (track->par->width == 1440 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','5','3'); else if (rate == 25) tag = MKTAG('a','i','5','2'); else if (rate == 30) tag = MKTAG('a','i','5','3'); } else { if (rate == 50) tag = MKTAG('a','i','5','5'); else if (rate == 60) tag = MKTAG('a','i','5','6'); } } } else if (track->par->format == AV_PIX_FMT_YUV422P10) { if (track->par->width == 1280 && track->par->height == 720) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','p'); else if (rate == 25) tag = MKTAG('a','i','1','q'); else if (rate == 30) tag = MKTAG('a','i','1','p'); else if (rate == 50) tag = MKTAG('a','i','1','q'); else if (rate == 60) tag = MKTAG('a','i','1','p'); } } else if (track->par->width == 1920 && track->par->height == 1080) { if (!interlaced) { if (rate == 24) tag = MKTAG('a','i','1','3'); else if (rate == 25) tag = MKTAG('a','i','1','2'); else if (rate == 30) tag = MKTAG('a','i','1','3'); } else { if (rate == 25) tag = MKTAG('a','i','1','5'); else if (rate == 50) tag = MKTAG('a','i','1','5'); else if (rate == 60) tag = MKTAG('a','i','1','6'); } } else if ( track->par->width == 4096 && track->par->height == 2160 || track->par->width == 3840 && track->par->height == 2160 || track->par->width == 2048 && track->par->height == 1080) { tag = MKTAG('a','i','v','x'); } } return tag; } static const struct { enum AVPixelFormat pix_fmt; uint32_t tag; unsigned bps; } mov_pix_fmt_tags[] = { { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 }, { AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 }, { AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 }, { AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 }, { AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 }, { AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 }, { AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 }, { AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 }, { AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 }, { AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 }, { AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 }, { AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 }, { AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 }, { AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 }, { AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 }, }; static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = MKTAG('A','V','d','n'); if (track->par->profile != FF_PROFILE_UNKNOWN && track->par->profile != FF_PROFILE_DNXHD) tag = MKTAG('A','V','d','h'); return tag; } static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; int i; enum AVPixelFormat pix_fmt; for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) { if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) { tag = mov_pix_fmt_tags[i].tag; track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps; if (track->par->codec_tag == mov_pix_fmt_tags[i].tag) break; } } pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov, track->par->bits_per_coded_sample); if (tag == MKTAG('r','a','w',' ') && track->par->format != pix_fmt && track->par->format != AV_PIX_FMT_GRAY8 && track->par->format != AV_PIX_FMT_NONE) av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n", av_get_pix_fmt_name(track->par->format)); return tag; } static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag = track->par->codec_tag; if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL && (track->par->codec_id == AV_CODEC_ID_DVVIDEO || track->par->codec_id == AV_CODEC_ID_RAWVIDEO || track->par->codec_id == AV_CODEC_ID_H263 || track->par->codec_id == AV_CODEC_ID_H264 || track->par->codec_id == AV_CODEC_ID_DNXHD || track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO || av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio if (track->par->codec_id == AV_CODEC_ID_DVVIDEO) tag = mov_get_dv_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO) tag = mov_get_rawvideo_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO) tag = mov_get_mpeg2_xdcam_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_H264) tag = mov_get_h264_codec_tag(s, track); else if (track->par->codec_id == AV_CODEC_ID_DNXHD) tag = mov_get_dnxhd_codec_tag(s, track); else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id); if (tag) av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, " "the file may be unplayable!\n"); } } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id); if (!tag) { // if no mac fcc found, try with Microsoft tags int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id); if (ms_tag) { tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff)); av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, " "the file may be unplayable!\n"); } } } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id); } return tag; } static const AVCodecTag codec_cover_image_tags[] = { { AV_CODEC_ID_MJPEG, 0xD }, { AV_CODEC_ID_PNG, 0xE }, { AV_CODEC_ID_BMP, 0x1B }, { AV_CODEC_ID_NONE, 0 }, }; static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track) { int tag; if (is_cover_image(track->st)) return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id); if (track->mode == MODE_MP4 || track->mode == MODE_PSP) tag = track->par->codec_tag; else if (track->mode == MODE_ISM) tag = track->par->codec_tag; else if (track->mode == MODE_IPOD) { if (!av_match_ext(s->url, "m4a") && !av_match_ext(s->url, "m4v") && !av_match_ext(s->url, "m4b")) av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v " "Quicktime/Ipod might not play the file\n"); tag = track->par->codec_tag; } else if (track->mode & MODE_3GP) tag = track->par->codec_tag; else if (track->mode == MODE_F4V) tag = track->par->codec_tag; else tag = mov_get_codec_tag(s, track); return tag; } /** Write uuid atom. * Needed to make file play in iPods running newest firmware * goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1 */ static int mov_write_uuid_tag_ipod(AVIOContext *pb) { avio_wb32(pb, 28); ffio_wfourcc(pb, "uuid"); avio_wb32(pb, 0x6b6840f2); avio_wb32(pb, 0x5f244fc5); avio_wb32(pb, 0xba39a51b); avio_wb32(pb, 0xcf0323f3); avio_wb32(pb, 0x0); return 28; } static const uint16_t fiel_data[] = { 0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e }; static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order) { unsigned mov_field_order = 0; if (field_order < FF_ARRAY_ELEMS(fiel_data)) mov_field_order = fiel_data[field_order]; else return 0; avio_wb32(pb, 10); ffio_wfourcc(pb, "fiel"); avio_wb16(pb, mov_field_order); return 10; } static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wl32(pb, track->tag); // store it byteswapped avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_write_esds_tag(pb, track); else if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); return update_size(pb, pos); } static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d) { int8_t stereo_mode; if (stereo_3d->flags != 0) { av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags); return 0; } switch (stereo_3d->type) { case AV_STEREO3D_2D: stereo_mode = 0; break; case AV_STEREO3D_TOPBOTTOM: stereo_mode = 1; break; case AV_STEREO3D_SIDEBYSIDE: stereo_mode = 2; break; default: av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type)); return 0; } avio_wb32(pb, 13); /* size */ ffio_wfourcc(pb, "st3d"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_w8(pb, stereo_mode); return 13; } static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping) { int64_t sv3d_pos, svhd_pos, proj_pos; const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT; if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR && spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE && spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) { av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection); return 0; } sv3d_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sv3d"); svhd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "svhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_put_str(pb, metadata_source); update_size(pb, svhd_pos); proj_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "proj"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "prhd"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->yaw); avio_wb32(pb, spherical_mapping->pitch); avio_wb32(pb, spherical_mapping->roll); switch (spherical_mapping->projection) { case AV_SPHERICAL_EQUIRECTANGULAR: case AV_SPHERICAL_EQUIRECTANGULAR_TILE: avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "equi"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, spherical_mapping->bound_top); avio_wb32(pb, spherical_mapping->bound_bottom); avio_wb32(pb, spherical_mapping->bound_left); avio_wb32(pb, spherical_mapping->bound_right); break; case AV_SPHERICAL_CUBEMAP: avio_wb32(pb, 20); /* size */ ffio_wfourcc(pb, "cbmp"); avio_wb32(pb, 0); /* version = 0 & flags = 0 */ avio_wb32(pb, 0); /* layout */ avio_wb32(pb, spherical_mapping->padding); /* padding */ break; } update_size(pb, proj_pos); return update_size(pb, sv3d_pos); } static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 40); ffio_wfourcc(pb, "clap"); avio_wb32(pb, track->par->width); /* apertureWidth_N */ avio_wb32(pb, 1); /* apertureWidth_D (= 1) */ avio_wb32(pb, track->height); /* apertureHeight_N */ avio_wb32(pb, 1); /* apertureHeight_D (= 1) */ avio_wb32(pb, 0); /* horizOff_N (= 0) */ avio_wb32(pb, 1); /* horizOff_D (= 1) */ avio_wb32(pb, 0); /* vertOff_N (= 0) */ avio_wb32(pb, 1); /* vertOff_D (= 1) */ return 40; } static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track) { AVRational sar; av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num, track->par->sample_aspect_ratio.den, INT_MAX); avio_wb32(pb, 16); ffio_wfourcc(pb, "pasp"); avio_wb32(pb, sar.num); avio_wb32(pb, sar.den); return 16; } static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma) { uint32_t gama = 0; if (gamma <= 0.0) { gamma = avpriv_get_gamma_from_trc(track->par->color_trc); } av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma); if (gamma > 1e-6) { gama = (uint32_t)lrint((double)(1<<16) * gamma); av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama); av_assert0(track->mode == MODE_MOV); avio_wb32(pb, 12); ffio_wfourcc(pb, "gama"); avio_wb32(pb, gama); return 12; } else { av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n"); } return 0; } static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track) { // Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9 // Ref (MP4): ISO/IEC 14496-12:2012 if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED && track->par->color_trc == AVCOL_TRC_UNSPECIFIED && track->par->color_space == AVCOL_SPC_UNSPECIFIED) { if ((track->par->width >= 1920 && track->par->height >= 1080) || (track->par->width == 1280 && track->par->height == 720)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n"); track->par->color_primaries = AVCOL_PRI_BT709; } else if (track->par->width == 720 && track->height == 576) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n"); track->par->color_primaries = AVCOL_PRI_BT470BG; } else if (track->par->width == 720 && (track->height == 486 || track->height == 480)) { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n"); track->par->color_primaries = AVCOL_PRI_SMPTE170M; } else { av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n"); } switch (track->par->color_primaries) { case AVCOL_PRI_BT709: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_BT709; break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_BT470BG: track->par->color_trc = AVCOL_TRC_BT709; track->par->color_space = AVCOL_SPC_SMPTE170M; break; } } /* We should only ever be called by MOV or MP4. */ av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4); avio_wb32(pb, 18 + (track->mode == MODE_MP4)); ffio_wfourcc(pb, "colr"); if (track->mode == MODE_MP4) ffio_wfourcc(pb, "nclx"); else ffio_wfourcc(pb, "nclc"); switch (track->par->color_primaries) { case AVCOL_PRI_BT709: avio_wb16(pb, 1); break; case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break; case AVCOL_PRI_SMPTE170M: case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break; case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break; case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break; case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break; default: avio_wb16(pb, 2); } switch (track->par->color_trc) { case AVCOL_TRC_BT709: avio_wb16(pb, 1); break; case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break; case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break; case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break; default: avio_wb16(pb, 2); } switch (track->par->color_space) { case AVCOL_SPC_BT709: avio_wb16(pb, 1); break; case AVCOL_SPC_BT470BG: case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break; case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break; case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break; default: avio_wb16(pb, 2); } if (track->mode == MODE_MP4) { int full_range = track->par->color_range == AVCOL_RANGE_JPEG; avio_w8(pb, full_range << 7); return 19; } else { return 18; } } static void find_compressor(char * compressor_name, int len, MOVTrack *track) { AVDictionaryEntry *encoder; int xdcam_res = (track->par->width == 1280 && track->par->height == 720) || (track->par->width == 1440 && track->par->height == 1080) || (track->par->width == 1920 && track->par->height == 1080); if (track->mode == MODE_MOV && (encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) { av_strlcpy(compressor_name, encoder->value, 32); } else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) { int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; AVStream *st = track->st; int rate = defined_frame_rate(NULL, st); av_strlcatf(compressor_name, len, "XDCAM"); if (track->par->format == AV_PIX_FMT_YUV422P) { av_strlcatf(compressor_name, len, " HD422"); } else if(track->par->width == 1440) { av_strlcatf(compressor_name, len, " HD"); } else av_strlcatf(compressor_name, len, " EX"); av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p'); av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1)); } } static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); char compressor_name[32] = { 0 }; int avid = 0; int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422) || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422) || track->par->codec_id == AV_CODEC_ID_V308 || track->par->codec_id == AV_CODEC_ID_V408 || track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210); avio_wb32(pb, 0); /* size */ if (mov->encryption_scheme != MOV_ENC_NONE) { ffio_wfourcc(pb, "encv"); } else { avio_wl32(pb, track->tag); // store it byteswapped } avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ if (uncompressed_ycbcr) { avio_wb16(pb, 2); /* Codec stream version */ } else { avio_wb16(pb, 0); /* Codec stream version */ } avio_wb16(pb, 0); /* Codec stream revision (=0) */ if (track->mode == MODE_MOV) { ffio_wfourcc(pb, "FFMP"); /* Vendor */ if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) { avio_wb32(pb, 0); /* Temporal Quality */ avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/ } else { avio_wb32(pb, 0x200); /* Temporal Quality = normal */ avio_wb32(pb, 0x200); /* Spatial Quality = normal */ } } else { avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 0); /* Reserved */ } avio_wb16(pb, track->par->width); /* Video width */ avio_wb16(pb, track->height); /* Video height */ avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */ avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */ avio_wb32(pb, 0); /* Data size (= 0) */ avio_wb16(pb, 1); /* Frame count (= 1) */ /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */ find_compressor(compressor_name, 32, track); avio_w8(pb, strlen(compressor_name)); avio_write(pb, compressor_name, 31); if (track->mode == MODE_MOV && (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210)) avio_wb16(pb, 0x18); else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample) avio_wb16(pb, track->par->bits_per_coded_sample | (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0)); else avio_wb16(pb, 0x18); /* Reserved */ if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) { int pal_size = 1 << track->par->bits_per_coded_sample; int i; avio_wb16(pb, 0); /* Color table ID */ avio_wb32(pb, 0); /* Color table seed */ avio_wb16(pb, 0x8000); /* Color table flags */ avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */ for (i = 0; i < pal_size; i++) { uint32_t rgb = track->palette[i]; uint16_t r = (rgb >> 16) & 0xff; uint16_t g = (rgb >> 8) & 0xff; uint16_t b = rgb & 0xff; avio_wb16(pb, 0); avio_wb16(pb, (r << 8) | r); avio_wb16(pb, (g << 8) | g); avio_wb16(pb, (b << 8) | b); } } else avio_wb16(pb, 0xffff); /* Reserved */ if (track->tag == MKTAG('m','p','4','v')) mov_write_esds_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H263) mov_write_d263_tag(pb); else if (track->par->codec_id == AV_CODEC_ID_AVUI || track->par->codec_id == AV_CODEC_ID_SVQ3) { mov_write_extradata_tag(pb, track); avio_wb32(pb, 0); } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) { mov_write_avid_tag(pb, track); avid = 1; } else if (track->par->codec_id == AV_CODEC_ID_HEVC) mov_write_hvcc_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) { mov_write_avcc_tag(pb, track); if (track->mode == MODE_IPOD) mov_write_uuid_tag_ipod(pb); } else if (track->par->codec_id == AV_CODEC_ID_VP9) { mov_write_vpcc_tag(mov->fc, pb, track); } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0) mov_write_dvc1_tag(pb, track); else if (track->par->codec_id == AV_CODEC_ID_VP6F || track->par->codec_id == AV_CODEC_ID_VP6A) { /* Don't write any potential extradata here - the cropping * is signalled via the normal width/height fields. */ } else if (track->par->codec_id == AV_CODEC_ID_R10K) { if (track->par->codec_tag == MKTAG('R','1','0','k')) mov_write_dpxe_tag(pb, track); } else if (track->vos_len > 0) mov_write_glbl_tag(pb, track); if (track->par->codec_id != AV_CODEC_ID_H264 && track->par->codec_id != AV_CODEC_ID_MPEG4 && track->par->codec_id != AV_CODEC_ID_DNXHD) { int field_order = track->par->field_order; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN) field_order = track->st->codec->field_order; FF_ENABLE_DEPRECATION_WARNINGS #endif if (field_order != AV_FIELD_UNKNOWN) mov_write_fiel_tag(pb, track, field_order); } if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) { if (track->mode == MODE_MOV) mov_write_gama_tag(pb, track, mov->gamma); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n"); } if (mov->flags & FF_MOV_FLAG_WRITE_COLR) { if (track->mode == MODE_MOV || track->mode == MODE_MP4) mov_write_colr_tag(pb, track); else av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n"); } if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) { AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL); AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL); if (stereo_3d) mov_write_st3d_tag(pb, stereo_3d); if (spherical_mapping) mov_write_sv3d_tag(mov->fc, pb, spherical_mapping); } if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) { mov_write_pasp_tag(pb, track); } if (uncompressed_ycbcr){ mov_write_clap_tag(pb, track); } if (mov->encryption_scheme != MOV_ENC_NONE) { ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); } /* extra padding for avid stsd */ /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */ if (avid) avio_wb32(pb, 0); return update_size(pb, pos); } static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "rtp "); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb16(pb, 1); /* Hint track version */ avio_wb16(pb, 1); /* Highest compatible version */ avio_wb32(pb, track->max_packet_size); /* Max packet size */ avio_wb32(pb, 12); /* size */ ffio_wfourcc(pb, "tims"); avio_wb32(pb, track->timescale); return update_size(pb, pos); } static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name) { uint64_t str_size =strlen(reel_name); int64_t pos = avio_tell(pb); if (str_size >= UINT16_MAX){ av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size); avio_wb16(pb, 0); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "name"); /* Data format */ avio_wb16(pb, str_size); /* string size */ avio_wb16(pb, track->language); /* langcode */ avio_write(pb, reel_name, str_size); /* reel name */ return update_size(pb,pos); } static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); #if 1 int frame_duration; int nb_frames; AVDictionaryEntry *t = NULL; if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) { #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den); nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num); FF_ENABLE_DEPRECATION_WARNINGS #else av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n"); return AVERROR(EINVAL); #endif } else { frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den); nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num); } if (nb_frames > 255) { av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames); return AVERROR(EINVAL); } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ avio_wb32(pb, 0); /* Flags */ avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */ avio_wb32(pb, track->timescale); /* Timescale */ avio_wb32(pb, frame_duration); /* Frame duration */ avio_w8(pb, nb_frames); /* Number of frames */ avio_w8(pb, 0); /* Reserved */ t = av_dict_get(track->st->metadata, "reel_name", NULL, 0); if (t && utf8len(t->value) && track->mode != MODE_MP4) mov_write_source_reference_tag(pb, track, t->value); else avio_wb16(pb, 0); /* zero size */ #else avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); /* Data format */ avio_wb32(pb, 0); /* Reserved */ avio_wb32(pb, 1); /* Data reference index */ if (track->par->extradata_size) avio_write(pb, track->par->extradata, track->par->extradata_size); #endif return update_size(pb, pos); } static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* Reserved */ avio_wb16(pb, 0); /* Reserved */ avio_wb16(pb, 1); /* Data-reference index */ avio_wb32(pb, 0); /* Reserved */ return update_size(pb, pos); } static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stsd"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_video_tag(pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_audio_tag(s, pb, mov, track); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) mov_write_subtitle_tag(pb, track); else if (track->par->codec_tag == MKTAG('r','t','p',' ')) mov_write_rtp_tag(pb, track); else if (track->par->codec_tag == MKTAG('t','m','c','d')) mov_write_tmcd_tag(pb, track); else if (track->par->codec_tag == MKTAG('g','p','m','d')) mov_write_gpmd_tag(pb, track); return update_size(pb, pos); } static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; MOVStts *ctts_entries; uint32_t entries = 0; uint32_t atom_size; int i; ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */ if (!ctts_entries) return AVERROR(ENOMEM); ctts_entries[0].count = 1; ctts_entries[0].duration = track->cluster[0].cts; for (i = 1; i < track->entry; i++) { if (track->cluster[i].cts == ctts_entries[entries].duration) { ctts_entries[entries].count++; /* compress */ } else { entries++; ctts_entries[entries].duration = track->cluster[i].cts; ctts_entries[entries].count = 1; } } entries++; /* last one */ atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "ctts"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, ctts_entries[i].count); avio_wb32(pb, ctts_entries[i].duration); } av_free(ctts_entries); return atom_size; } /* Time to sample atom */ static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track) { MOVStts *stts_entries = NULL; uint32_t entries = -1; uint32_t atom_size; int i; if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) { stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */ if (!stts_entries) return AVERROR(ENOMEM); stts_entries[0].count = track->sample_count; stts_entries[0].duration = 1; entries = 1; } else { if (track->entry) { stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */ if (!stts_entries) return AVERROR(ENOMEM); } for (i = 0; i < track->entry; i++) { int duration = get_cluster_duration(track, i); if (i && duration == stts_entries[entries].duration) { stts_entries[entries].count++; /* compress */ } else { entries++; stts_entries[entries].duration = duration; stts_entries[entries].count = 1; } } entries++; /* last one */ } atom_size = 16 + (entries * 8); avio_wb32(pb, atom_size); /* size */ ffio_wfourcc(pb, "stts"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, entries); /* entry count */ for (i = 0; i < entries; i++) { avio_wb32(pb, stts_entries[i].count); avio_wb32(pb, stts_entries[i].duration); } av_free(stts_entries); return atom_size; } static int mov_write_dref_tag(AVIOContext *pb) { avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "dref"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, 1); /* entry count */ avio_wb32(pb, 0xc); /* size */ //FIXME add the alis and rsrc atom ffio_wfourcc(pb, "url "); avio_wb32(pb, 1); /* version & flags */ return 28; } static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track) { struct sgpd_entry { int count; int16_t roll_distance; int group_description_index; }; struct sgpd_entry *sgpd_entries = NULL; int entries = -1; int group = 0; int i, j; const int OPUS_SEEK_PREROLL_MS = 80; int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS, (AVRational){1, 1000}, (AVRational){1, 48000}); if (!track->entry) return 0; sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries)); if (!sgpd_entries) return AVERROR(ENOMEM); av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC); if (track->par->codec_id == AV_CODEC_ID_OPUS) { for (i = 0; i < track->entry; i++) { int roll_samples_remaining = roll_samples; int distance = 0; for (j = i - 1; j >= 0; j--) { roll_samples_remaining -= get_cluster_duration(track, j); distance++; if (roll_samples_remaining <= 0) break; } /* We don't have enough preceeding samples to compute a valid roll_distance here, so this sample can't be independently decoded. */ if (roll_samples_remaining > 0) distance = 0; /* Verify distance is a minimum of 2 (60ms) packets and a maximum of 32 (2.5ms) packets. */ av_assert0(distance == 0 || (distance >= 2 && distance <= 32)); if (i && distance == sgpd_entries[entries].roll_distance) { sgpd_entries[entries].count++; } else { entries++; sgpd_entries[entries].count = 1; sgpd_entries[entries].roll_distance = distance; sgpd_entries[entries].group_description_index = distance ? ++group : 0; } } } else { entries++; sgpd_entries[entries].count = track->sample_count; sgpd_entries[entries].roll_distance = 1; sgpd_entries[entries].group_description_index = ++group; } entries++; if (!group) { av_free(sgpd_entries); return 0; } /* Write sgpd tag */ avio_wb32(pb, 24 + (group * 2)); /* size */ ffio_wfourcc(pb, "sgpd"); avio_wb32(pb, 1 << 24); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, 2); /* default_length */ avio_wb32(pb, group); /* entry_count */ for (i = 0; i < entries; i++) { if (sgpd_entries[i].group_description_index) { avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */ } } /* Write sbgp tag */ avio_wb32(pb, 20 + (entries * 8)); /* size */ ffio_wfourcc(pb, "sbgp"); avio_wb32(pb, 0); /* fullbox */ ffio_wfourcc(pb, "roll"); avio_wb32(pb, entries); /* entry_count */ for (i = 0; i < entries; i++) { avio_wb32(pb, sgpd_entries[i].count); /* sample_count */ avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */ } av_free(sgpd_entries); return 0; } static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "stbl"); mov_write_stsd_tag(s, pb, mov, track); mov_write_stts_tag(pb, track); if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_tag == MKTAG('r','t','p',' ')) && track->has_keyframes && track->has_keyframes < track->entry) mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable) mov_write_sdtp_tag(pb, track); if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS) mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->flags & MOV_TRACK_CTTS && track->entry) { if ((ret = mov_write_ctts_tag(s, pb, track)) < 0) return ret; } mov_write_stsc_tag(pb, track); mov_write_stsz_tag(pb, track); mov_write_stco_tag(pb, track); if (track->cenc.aes_ctr) { ff_mov_cenc_write_stbl_atoms(&track->cenc, pb); } if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) { mov_preroll_write_stbl_atoms(pb, track); } return update_size(pb, pos); } static int mov_write_dinf_tag(AVIOContext *pb) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "dinf"); mov_write_dref_tag(pb); return update_size(pb, pos); } static int mov_write_nmhd_tag(AVIOContext *pb) { avio_wb32(pb, 12); ffio_wfourcc(pb, "nmhd"); avio_wb32(pb, 0); return 12; } static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); const char *font = "Lucida Grande"; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* text font */ avio_wb16(pb, 0); /* text face */ avio_wb16(pb, 12); /* text size */ avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */ avio_wb16(pb, 0x0000); /* text color (red) */ avio_wb16(pb, 0x0000); /* text color (green) */ avio_wb16(pb, 0x0000); /* text color (blue) */ avio_wb16(pb, 0xffff); /* background color (red) */ avio_wb16(pb, 0xffff); /* background color (green) */ avio_wb16(pb, 0xffff); /* background color (blue) */ avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */ avio_write(pb, font, strlen(font)); /* font name */ return update_size(pb, pos); } static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gmhd"); avio_wb32(pb, 0x18); /* gmin size */ ffio_wfourcc(pb, "gmin");/* generic media info */ avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0x40); /* graphics mode = */ avio_wb16(pb, 0x8000); /* opColor (r?) */ avio_wb16(pb, 0x8000); /* opColor (g?) */ avio_wb16(pb, 0x8000); /* opColor (b?) */ avio_wb16(pb, 0); /* balance */ avio_wb16(pb, 0); /* reserved */ /* * This special text atom is required for * Apple Quicktime chapters. The contents * don't appear to be documented, so the * bytes are copied verbatim. */ if (track->tag != MKTAG('c','6','0','8')) { avio_wb32(pb, 0x2C); /* size */ ffio_wfourcc(pb, "text"); avio_wb16(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x01); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00); avio_wb32(pb, 0x00004000); avio_wb16(pb, 0x0000); } if (track->par->codec_tag == MKTAG('t','m','c','d')) { int64_t tmcd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tmcd"); mov_write_tcmi_tag(pb, track); update_size(pb, tmcd_pos); } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { int64_t gpmd_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "gpmd"); avio_wb32(pb, 0); /* version */ update_size(pb, gpmd_pos); } return update_size(pb, pos); } static int mov_write_smhd_tag(AVIOContext *pb) { avio_wb32(pb, 16); /* size */ ffio_wfourcc(pb, "smhd"); avio_wb32(pb, 0); /* version & flags */ avio_wb16(pb, 0); /* reserved (balance, normally = 0) */ avio_wb16(pb, 0); /* reserved */ return 16; } static int mov_write_vmhd_tag(AVIOContext *pb) { avio_wb32(pb, 0x14); /* size (always 0x14) */ ffio_wfourcc(pb, "vmhd"); avio_wb32(pb, 0x01); /* version & flags */ avio_wb64(pb, 0); /* reserved (graphics mode = copy) */ return 0x14; } static int is_clcp_track(MOVTrack *track) { return track->tag == MKTAG('c','7','0','8') || track->tag == MKTAG('c','6','0','8'); } static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; const char *hdlr, *descr = NULL, *hdlr_type = NULL; int64_t pos = avio_tell(pb); hdlr = "dhlr"; hdlr_type = "url "; descr = "DataHandler"; if (track) { hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0"; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { hdlr_type = "vide"; descr = "VideoHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { hdlr_type = "soun"; descr = "SoundHandler"; } else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (is_clcp_track(track)) { hdlr_type = "clcp"; descr = "ClosedCaptionHandler"; } else { if (track->tag == MKTAG('t','x','3','g')) { hdlr_type = "sbtl"; } else if (track->tag == MKTAG('m','p','4','s')) { hdlr_type = "subp"; } else { hdlr_type = "text"; } descr = "SubtitleHandler"; } } else if (track->par->codec_tag == MKTAG('r','t','p',' ')) { hdlr_type = "hint"; descr = "HintHandler"; } else if (track->par->codec_tag == MKTAG('t','m','c','d')) { hdlr_type = "tmcd"; descr = "TimeCodeHandler"; } else if (track->par->codec_tag == MKTAG('g','p','m','d')) { hdlr_type = "meta"; descr = "GoPro MET"; // GoPro Metadata } else { av_log(s, AV_LOG_WARNING, "Unknown hldr_type for %s, writing dummy values\n", av_fourcc2str(track->par->codec_tag)); } if (track->st) { // hdlr.name is used by some players to identify the content title // of the track. So if an alternate handler description is // specified, use it. AVDictionaryEntry *t; t = av_dict_get(track->st->metadata, "handler_name", NULL, 0); if (t && utf8len(t->value)) descr = t->value; } } if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */ descr = ""; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); /* Version & flags */ avio_write(pb, hdlr, 4); /* handler */ ffio_wfourcc(pb, hdlr_type); /* handler type */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ if (!track || track->mode == MODE_MOV) avio_w8(pb, strlen(descr)); /* pascal string */ avio_write(pb, descr, strlen(descr)); /* handler description */ if (track && track->mode != MODE_MOV) avio_w8(pb, 0); /* c string */ return update_size(pb, pos); } static int mov_write_hmhd_tag(AVIOContext *pb) { /* This atom must be present, but leaving the values at zero * seems harmless. */ avio_wb32(pb, 28); /* size */ ffio_wfourcc(pb, "hmhd"); avio_wb32(pb, 0); /* version, flags */ avio_wb16(pb, 0); /* maxPDUsize */ avio_wb16(pb, 0); /* avgPDUsize */ avio_wb32(pb, 0); /* maxbitrate */ avio_wb32(pb, 0); /* avgbitrate */ avio_wb32(pb, 0); /* reserved */ return 28; } static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "minf"); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) mov_write_vmhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) mov_write_smhd_tag(pb); else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) { mov_write_gmhd_tag(pb, track); } else { mov_write_nmhd_tag(pb); } } else if (track->tag == MKTAG('r','t','p',' ')) { mov_write_hmhd_tag(pb); } else if (track->tag == MKTAG('t','m','c','d')) { if (track->mode != MODE_MOV) mov_write_nmhd_tag(pb); else mov_write_gmhd_tag(pb, track); } else if (track->tag == MKTAG('g','p','m','d')) { mov_write_gmhd_tag(pb, track); } if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */ mov_write_hdlr_tag(s, pb, NULL); mov_write_dinf_tag(pb); if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int version = track->track_duration < INT32_MAX ? 0 : 1; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, "mdhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */ avio_wb16(pb, track->language); /* language */ avio_wb16(pb, 0); /* reserved (quality) */ if (version != 0 && track->mode == MODE_MOV) { av_log(NULL, AV_LOG_ERROR, "FATAL error, file duration too long for timebase, this file will not be\n" "playable with quicktime. Choose a different timebase or a different\n" "container format\n"); } return 32; } static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int ret; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "mdia"); mov_write_mdhd_tag(pb, mov, track); mov_write_hdlr_tag(s, pb, track); if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0) return ret; return update_size(pb, pos); } /* transformation matrix |a b u| |c d v| |tx ty w| */ static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c, int16_t d, int16_t tx, int16_t ty) { avio_wb32(pb, a << 16); /* 16.16 format */ avio_wb32(pb, b << 16); /* 16.16 format */ avio_wb32(pb, 0); /* u in 2.30 format */ avio_wb32(pb, c << 16); /* 16.16 format */ avio_wb32(pb, d << 16); /* 16.16 format */ avio_wb32(pb, 0); /* v in 2.30 format */ avio_wb32(pb, tx << 16); /* 16.16 format */ avio_wb32(pb, ty << 16); /* 16.16 format */ avio_wb32(pb, 1 << 30); /* w in 2.30 format */ } static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int flags = MOV_TKHD_FLAG_IN_MOVIE; int rotation = 0; int group = 0; uint32_t *display_matrix = NULL; int display_matrix_size, i; if (st) { if (mov->per_stream_grouping) group = st->index; else group = st->codecpar->codec_type; display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, &display_matrix_size); if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix)) display_matrix = NULL; } if (track->flags & MOV_TRACK_ENABLED) flags |= MOV_TKHD_FLAG_ENABLED; if (track->mode == MODE_ISM) version = 1; (version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */ ffio_wfourcc(pb, "tkhd"); avio_w8(pb, version); avio_wb24(pb, flags); if (version == 1) { avio_wb64(pb, track->time); avio_wb64(pb, track->time); } else { avio_wb32(pb, track->time); /* creation time */ avio_wb32(pb, track->time); /* modification time */ } avio_wb32(pb, track->track_id); /* track-id */ avio_wb32(pb, 0); /* reserved */ if (!track->entry && mov->mode == MODE_ISM) (version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff); else if (!track->entry) (version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0); else (version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration); avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb16(pb, 0); /* layer */ avio_wb16(pb, group); /* alternate group) */ /* Volume, only for audio */ if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) avio_wb16(pb, 0x0100); else avio_wb16(pb, 0); avio_wb16(pb, 0); /* reserved */ /* Matrix structure */ #if FF_API_OLD_ROTATE_API if (st && st->metadata) { AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0); rotation = (rot && rot->value) ? atoi(rot->value) : 0; } #endif if (display_matrix) { for (i = 0; i < 9; i++) avio_wb32(pb, display_matrix[i]); #if FF_API_OLD_ROTATE_API } else if (rotation == 90) { write_matrix(pb, 0, 1, -1, 0, track->par->height, 0); } else if (rotation == 180) { write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height); } else if (rotation == 270) { write_matrix(pb, 0, -1, 1, 0, 0, track->par->width); #endif } else { write_matrix(pb, 1, 0, 0, 1, 0, 0); } /* Track width and height, for visual only */ if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO || track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) { int64_t track_width_1616; if (track->mode == MODE_MOV) { track_width_1616 = track->par->width * 0x10000ULL; } else { track_width_1616 = av_rescale(st->sample_aspect_ratio.num, track->par->width * 0x10000LL, st->sample_aspect_ratio.den); if (!track_width_1616 || track->height != track->par->height || track_width_1616 > UINT32_MAX) track_width_1616 = track->par->width * 0x10000ULL; } if (track_width_1616 > UINT32_MAX) { av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n"); track_width_1616 = 0; } avio_wb32(pb, track_width_1616); if (track->height > 0xFFFF) { av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n"); avio_wb32(pb, 0); } else avio_wb32(pb, track->height * 0x10000U); } else { avio_wb32(pb, 0); avio_wb32(pb, 0); } return 0x5c; } static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track) { int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width, track->par->sample_aspect_ratio.den); int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tapt"); avio_wb32(pb, 20); ffio_wfourcc(pb, "clef"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "prof"); avio_wb32(pb, 0); avio_wb32(pb, width << 16); avio_wb32(pb, track->par->height << 16); avio_wb32(pb, 20); ffio_wfourcc(pb, "enof"); avio_wb32(pb, 0); avio_wb32(pb, track->par->width << 16); avio_wb32(pb, track->par->height << 16); return update_size(pb, pos); } // This box seems important for the psp playback ... without it the movie seems to hang static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE, track->timescale, AV_ROUND_UP); int version = duration < INT32_MAX ? 0 : 1; int entry_size, entry_count, size; int64_t delay, start_ct = track->start_cts; int64_t start_dts = track->start_dts; if (track->entry) { if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) { av_log(mov->fc, AV_LOG_DEBUG, "EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n", track->cluster[0].dts, track->cluster[0].cts, start_dts, start_ct, track->track_id); start_dts = track->cluster[0].dts; start_ct = track->cluster[0].cts; } } delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN); version |= delay < INT32_MAX ? 0 : 1; entry_size = (version == 1) ? 20 : 12; entry_count = 1 + (delay > 0); size = 24 + entry_count * entry_size; /* write the atom data */ avio_wb32(pb, size); ffio_wfourcc(pb, "edts"); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "elst"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ avio_wb32(pb, entry_count); if (delay > 0) { /* add an empty edit to delay presentation */ /* In the positive delay case, the delay includes the cts * offset, and the second edit list entry below trims out * the same amount from the actual content. This makes sure * that the offset last sample is included in the edit * list duration as well. */ if (version == 1) { avio_wb64(pb, delay); avio_wb64(pb, -1); } else { avio_wb32(pb, delay); avio_wb32(pb, -1); } avio_wb32(pb, 0x00010000); } else { /* Avoid accidentally ending up with start_ct = -1 which has got a * special meaning. Normally start_ct should end up positive or zero * here, but use FFMIN in case dts is a small positive integer * rounded to 0 when represented in MOV_TIMESCALE units. */ av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0); start_ct = -FFMIN(start_dts, 0); /* Note, this delay is calculated from the pts of the first sample, * ensuring that we don't reduce the duration for cases with * dts<0 pts=0. */ duration += delay; } /* For fragmented files, we don't know the full length yet. Setting * duration to 0 allows us to only specify the offset, including * the rest of the content (from all future fragments) without specifying * an explicit duration. */ if (mov->flags & FF_MOV_FLAG_FRAGMENT) duration = 0; /* duration */ if (version == 1) { avio_wb64(pb, duration); avio_wb64(pb, start_ct); } else { avio_wb32(pb, duration); avio_wb32(pb, start_ct); } avio_wb32(pb, 0x00010000); return size; } static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 20); // size ffio_wfourcc(pb, "tref"); avio_wb32(pb, 12); // size (subatom) avio_wl32(pb, track->tref_tag); avio_wb32(pb, track->tref_id); return 20; } // goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it) static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov) { avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x1c); // another size here! ffio_wfourcc(pb, "MTDT"); avio_wb32(pb, 0x00010012); avio_wb32(pb, 0x0a); avio_wb32(pb, 0x55c40000); avio_wb32(pb, 0x1); avio_wb32(pb, 0x0); return 0x34; } static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track) { AVFormatContext *ctx = track->rtp_ctx; char buf[1000] = ""; int len; ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track, NULL, NULL, 0, 0, ctx); av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id); len = strlen(buf); avio_wb32(pb, len + 24); ffio_wfourcc(pb, "udta"); avio_wb32(pb, len + 16); ffio_wfourcc(pb, "hnti"); avio_wb32(pb, len + 8); ffio_wfourcc(pb, "sdp "); avio_write(pb, buf, len); return len + 24; } static int mov_write_track_metadata(AVIOContext *pb, AVStream *st, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */ return update_size(pb, pos); } static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVStream *st) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; if (!st) return 0; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & (MODE_MP4|MODE_MOV)) mov_write_track_metadata(pb_buf, st, "name", "title"); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, AVStream *st) { int64_t pos = avio_tell(pb); int entry_backup = track->entry; int chunk_backup = track->chunkCount; int ret; /* If we want to have an empty moov, but some samples already have been * buffered (delay_moov), pretend that no samples have been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) track->chunkCount = track->entry = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "trak"); mov_write_tkhd_tag(pb, mov, track, st); av_assert2(mov->use_editlist >= 0); if (track->start_dts != AV_NOPTS_VALUE) { if (mov->use_editlist) mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track)) av_log(mov->fc, AV_LOG_WARNING, "Not writing any edit list even though one would have been required\n"); } if (track->tref_tag) mov_write_tref_tag(pb, track); if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0) return ret; if (track->mode == MODE_PSP) mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box if (track->tag == MKTAG('r','t','p',' ')) mov_write_udta_sdp(pb, track); if (track->mode == MODE_MOV) { if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio); if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) { mov_write_tapt_tag(pb, track); } } if (is_clcp_track(track) && st->sample_aspect_ratio.num) { mov_write_tapt_tag(pb, track); } } mov_write_track_udta_tag(pb, mov, st); track->entry = entry_backup; track->chunkCount = chunk_backup; return update_size(pb, pos); } static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov) { int i, has_audio = 0, has_video = 0; int64_t pos = avio_tell(pb); int audio_profile = mov->iods_audio_profile; int video_profile = mov->iods_video_profile; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO; has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO; } } if (audio_profile < 0) audio_profile = 0xFF - has_audio; if (video_profile < 0) video_profile = 0xFF - has_video; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "iods"); avio_wb32(pb, 0); /* version & flags */ put_descr(pb, 0x10, 7); avio_wb16(pb, 0x004f); avio_w8(pb, 0xff); avio_w8(pb, 0xff); avio_w8(pb, audio_profile); avio_w8(pb, video_profile); avio_w8(pb, 0xff); return update_size(pb, pos); } static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track) { avio_wb32(pb, 0x20); /* size */ ffio_wfourcc(pb, "trex"); avio_wb32(pb, 0); /* version & flags */ avio_wb32(pb, track->track_id); /* track ID */ avio_wb32(pb, 1); /* default sample description index */ avio_wb32(pb, 0); /* default sample duration */ avio_wb32(pb, 0); /* default sample size */ avio_wb32(pb, 0); /* default sample flags */ return 0; } static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0x0); /* size */ ffio_wfourcc(pb, "mvex"); for (i = 0; i < mov->nb_streams; i++) mov_write_trex_tag(pb, &mov->tracks[i]); return update_size(pb, pos); } static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov) { int max_track_id = 1, i; int64_t max_track_len = 0; int version; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) { int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration, MOV_TIMESCALE, mov->tracks[i].timescale, AV_ROUND_UP); if (max_track_len < max_track_len_temp) max_track_len = max_track_len_temp; if (max_track_id < mov->tracks[i].track_id) max_track_id = mov->tracks[i].track_id; } } /* If using delay_moov, make sure the output is the same as if no * samples had been written yet. */ if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { max_track_len = 0; max_track_id = 1; } version = max_track_len < UINT32_MAX ? 0 : 1; avio_wb32(pb, version == 1 ? 120 : 108); /* size */ ffio_wfourcc(pb, "mvhd"); avio_w8(pb, version); avio_wb24(pb, 0); /* flags */ if (version == 1) { avio_wb64(pb, mov->time); avio_wb64(pb, mov->time); } else { avio_wb32(pb, mov->time); /* creation time */ avio_wb32(pb, mov->time); /* modification time */ } avio_wb32(pb, MOV_TIMESCALE); (version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */ avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */ avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */ avio_wb16(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ avio_wb32(pb, 0); /* reserved */ /* Matrix structure */ write_matrix(pb, 1, 0, 0, 1, 0, 0); avio_wb32(pb, 0); /* reserved (preview time) */ avio_wb32(pb, 0); /* reserved (preview duration) */ avio_wb32(pb, 0); /* reserved (poster time) */ avio_wb32(pb, 0); /* reserved (selection time) */ avio_wb32(pb, 0); /* reserved (selection duration) */ avio_wb32(pb, 0); /* reserved (current time) */ avio_wb32(pb, max_track_id + 1); /* Next track id */ return 0x6c; } static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdir"); ffio_wfourcc(pb, "appl"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } /* helper function to write a data tag with the specified string as data */ static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style) { if (long_style) { int size = 16 + strlen(data); avio_wb32(pb, size); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 1); avio_wb32(pb, 0); avio_write(pb, data, strlen(data)); return size; } else { if (!lang) lang = ff_mov_iso639_to_lang("und", 1); avio_wb16(pb, strlen(data)); /* string length */ avio_wb16(pb, lang); avio_write(pb, data, strlen(data)); return strlen(data) + 4; } } static int mov_write_string_tag(AVIOContext *pb, const char *name, const char *value, int lang, int long_style) { int size = 0; if (value && value[0]) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, name); mov_write_string_data_tag(pb, value, lang, long_style); size = update_size(pb, pos); } return size; } static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s, const char *tag, int *lang) { int l, len, len2; AVDictionaryEntry *t, *t2 = NULL; char tag2[16]; *lang = 0; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return NULL; len = strlen(t->key); snprintf(tag2, sizeof(tag2), "%s-", tag); while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) { len2 = strlen(t2->key); if (len2 == len + 4 && !strcmp(t->value, t2->value) && (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) { *lang = l; return t; } } return t; } static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int long_style) { int lang; AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang); if (!t) return 0; return mov_write_string_tag(pb, name, t->value, lang, long_style); } /* iTunes bpm number */ static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0); int size = 0, tmpo = t ? atoi(t->value) : 0; if (tmpo) { size = 26; avio_wb32(pb, size); ffio_wfourcc(pb, "tmpo"); avio_wb32(pb, size-8); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); //type specifier avio_wb32(pb, 0); avio_wb16(pb, tmpo); // data } return size; } /* 3GPP TS 26.244 */ static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb) { int lang; int64_t pos = avio_tell(pb); double latitude, longitude, altitude; int32_t latitude_fix, longitude_fix, altitude_fix; AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang); const char *ptr, *place = ""; char *end; static const char *astronomical_body = "earth"; if (!t) return 0; ptr = t->value; longitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; latitude = strtod(ptr, &end); if (end == ptr) { av_log(s, AV_LOG_WARNING, "malformed location metadata\n"); return 0; } ptr = end; altitude = strtod(ptr, &end); /* If no altitude was present, the default 0 should be fine */ if (*end == '/') place = end + 1; latitude_fix = (int32_t) ((1 << 16) * latitude); longitude_fix = (int32_t) ((1 << 16) * longitude); altitude_fix = (int32_t) ((1 << 16) * altitude); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "loci"); /* type */ avio_wb32(pb, 0); /* version + flags */ avio_wb16(pb, lang); avio_write(pb, place, strlen(place) + 1); avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */ avio_wb32(pb, latitude_fix); avio_wb32(pb, longitude_fix); avio_wb32(pb, altitude_fix); avio_write(pb, astronomical_body, strlen(astronomical_body) + 1); avio_w8(pb, 0); /* additional notes, null terminated string */ return update_size(pb, pos); } /* iTunes track or disc number */ static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s, int disc) { AVDictionaryEntry *t = av_dict_get(s->metadata, disc ? "disc" : "track", NULL, 0); int size = 0, track = t ? atoi(t->value) : 0; if (track) { int tracks = 0; char *slash = strchr(t->value, '/'); if (slash) tracks = atoi(slash + 1); avio_wb32(pb, 32); /* size */ ffio_wfourcc(pb, disc ? "disk" : "trkn"); avio_wb32(pb, 24); /* size */ ffio_wfourcc(pb, "data"); avio_wb32(pb, 0); // 8 bytes empty avio_wb32(pb, 0); avio_wb16(pb, 0); // empty avio_wb16(pb, track); // track / disc number avio_wb16(pb, tracks); // total track / disc number avio_wb16(pb, 0); // empty size = 32; } return size; } static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb, const char *name, const char *tag, int len) { AVDictionaryEntry *t = NULL; uint8_t num; int size = 24 + len; if (len != 1 && len != 4) return -1; if (!(t = av_dict_get(s->metadata, tag, NULL, 0))) return 0; num = atoi(t->value); avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_wb32(pb, size - 8); ffio_wfourcc(pb, "data"); avio_wb32(pb, 0x15); avio_wb32(pb, 0); if (len==4) avio_wb32(pb, num); else avio_w8 (pb, num); return size; } static int mov_write_covr(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = 0; int i; for (i = 0; i < s->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (!is_cover_image(trk->st) || trk->cover_image.size <= 0) continue; if (!pos) { pos = avio_tell(pb); avio_wb32(pb, 0); ffio_wfourcc(pb, "covr"); } avio_wb32(pb, 16 + trk->cover_image.size); ffio_wfourcc(pb, "data"); avio_wb32(pb, trk->tag); avio_wb32(pb , 0); avio_write(pb, trk->cover_image.data, trk->cover_image.size); } return pos ? update_size(pb, pos) : 0; } /* iTunes meta data list */ static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); mov_write_string_metadata(s, pb, "\251nam", "title" , 1); mov_write_string_metadata(s, pb, "\251ART", "artist" , 1); mov_write_string_metadata(s, pb, "aART", "album_artist", 1); mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1); mov_write_string_metadata(s, pb, "\251alb", "album" , 1); mov_write_string_metadata(s, pb, "\251day", "date" , 1); if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) { if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1); } mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1); mov_write_string_metadata(s, pb, "\251gen", "genre" , 1); mov_write_string_metadata(s, pb, "cprt", "copyright", 1); mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1); mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1); mov_write_string_metadata(s, pb, "desc", "description",1); mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1); mov_write_string_metadata(s, pb, "tvsh", "show" , 1); mov_write_string_metadata(s, pb, "tven", "episode_id",1); mov_write_string_metadata(s, pb, "tvnn", "network" , 1); mov_write_string_metadata(s, pb, "keyw", "keywords" , 1); mov_write_int8_metadata (s, pb, "tves", "episode_sort",4); mov_write_int8_metadata (s, pb, "tvsn", "season_number",4); mov_write_int8_metadata (s, pb, "stik", "media_type",1); mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1); mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1); mov_write_int8_metadata (s, pb, "cpil", "compilation", 1); mov_write_covr(pb, s); mov_write_trkn_tag(pb, mov, s, 0); // track number mov_write_trkn_tag(pb, mov, s, 1); // disc number mov_write_tmpo_tag(pb, s); return update_size(pb, pos); } static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { avio_wb32(pb, 33); /* size */ ffio_wfourcc(pb, "hdlr"); avio_wb32(pb, 0); avio_wb32(pb, 0); ffio_wfourcc(pb, "mdta"); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_wb32(pb, 0); avio_w8(pb, 0); return 33; } static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int64_t curpos, entry_pos; int count = 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "keys"); avio_wb32(pb, 0); entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* entry count */ while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { avio_wb32(pb, strlen(t->key) + 8); ffio_wfourcc(pb, "mdta"); avio_write(pb, t->key, strlen(t->key)); count += 1; } curpos = avio_tell(pb); avio_seek(pb, entry_pos, SEEK_SET); avio_wb32(pb, count); // rewrite entry count avio_seek(pb, curpos, SEEK_SET); return update_size(pb, pos); } static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVDictionaryEntry *t = NULL; int64_t pos = avio_tell(pb); int count = 1; /* keys are 1-index based */ avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ilst"); while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) { int64_t entry_pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ avio_wb32(pb, count); /* key */ mov_write_string_data_tag(pb, t->value, 0, 1); update_size(pb, entry_pos); count += 1; } return update_size(pb, pos); } /* meta data tags */ static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int size = 0; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "meta"); avio_wb32(pb, 0); if (mov->flags & FF_MOV_FLAG_USE_MDTA) { mov_write_mdta_hdlr_tag(pb, mov, s); mov_write_mdta_keys_tag(pb, mov, s); mov_write_mdta_ilst_tag(pb, mov, s); } else { /* iTunes metadata tag */ mov_write_itunes_hdlr_tag(pb, mov, s); mov_write_ilst_tag(pb, mov, s); } size = update_size(pb, pos); return size; } static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb, const char *name, const char *key) { int len; AVDictionaryEntry *t; if (!(t = av_dict_get(s->metadata, key, NULL, 0))) return 0; len = strlen(t->value); if (len > 0) { int size = len + 8; avio_wb32(pb, size); ffio_wfourcc(pb, name); avio_write(pb, t->value, len); return size; } return 0; } static int ascii_to_wc(AVIOContext *pb, const uint8_t *b) { int val; while (*b) { GET_UTF8(val, *b++, return -1;) avio_wb16(pb, val); } avio_wb16(pb, 0x00); return 0; } static uint16_t language_code(const char *str) { return (((str[0] - 0x60) & 0x1F) << 10) + (((str[1] - 0x60) & 0x1F) << 5) + (( str[2] - 0x60) & 0x1F); } static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s, const char *tag, const char *str) { int64_t pos = avio_tell(pb); AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0); if (!t || !utf8len(t->value)) return 0; avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, tag); /* type */ avio_wb32(pb, 0); /* version + flags */ if (!strcmp(tag, "yrrc")) avio_wb16(pb, atoi(t->value)); else { avio_wb16(pb, language_code("eng")); /* language */ avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */ if (!strcmp(tag, "albm") && (t = av_dict_get(s->metadata, "track", NULL, 0))) avio_w8(pb, atoi(t->value)); } return update_size(pb, pos); } static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i, nb_chapters = FFMIN(s->nb_chapters, 255); avio_wb32(pb, 0); // size ffio_wfourcc(pb, "chpl"); avio_wb32(pb, 0x01000000); // version + flags avio_wb32(pb, 0); // unknown avio_w8(pb, nb_chapters); for (i = 0; i < nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000})); if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { int len = FFMIN(strlen(t->value), 255); avio_w8(pb, len); avio_write(pb, t->value, len); } else avio_w8(pb, 0); } return update_size(pb, pos); } static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { AVIOContext *pb_buf; int ret, size; uint8_t *buf; ret = avio_open_dyn_buf(&pb_buf); if (ret < 0) return ret; if (mov->mode & MODE_3GP) { mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist"); mov_write_3gp_udta_tag(pb_buf, s, "titl", "title"); mov_write_3gp_udta_tag(pb_buf, s, "auth", "author"); mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre"); mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment"); mov_write_3gp_udta_tag(pb_buf, s, "albm", "album"); mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright"); mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date"); mov_write_loci_tag(s, pb_buf); } else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4 mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0); mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0); mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0); mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0); mov_write_string_metadata(s, pb_buf, "\251day", "date", 0); mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0); // currently ignored by mov.c mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0); // add support for libquicktime, this atom is also actually read by mov.c mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0); mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0); mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0); mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0); mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0); mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0); mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0); mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp"); } else { /* iTunes meta data */ mov_write_meta_tag(pb_buf, mov, s); mov_write_loci_tag(s, pb_buf); } if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL)) mov_write_chpl_tag(pb_buf, s); if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) { avio_wb32(pb, size + 8); ffio_wfourcc(pb, "udta"); avio_write(pb, buf, size); } av_free(buf); return 0; } static void mov_write_psp_udta_tag(AVIOContext *pb, const char *str, const char *lang, int type) { int len = utf8len(str) + 1; if (len <= 0) return; avio_wb16(pb, len * 2 + 10); /* size */ avio_wb32(pb, type); /* type */ avio_wb16(pb, language_code(lang)); /* language */ avio_wb16(pb, 0x01); /* ? */ ascii_to_wc(pb, str); } static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s) { AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0); int64_t pos, pos2; if (title) { pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "USMT"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); pos2 = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "MTDT"); avio_wb16(pb, 4); // ? avio_wb16(pb, 0x0C); /* size */ avio_wb32(pb, 0x0B); /* type */ avio_wb16(pb, language_code("und")); /* language */ avio_wb16(pb, 0x0); /* ? */ avio_wb16(pb, 0x021C); /* data */ if (!(s->flags & AVFMT_FLAG_BITEXACT)) mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04); mov_write_psp_udta_tag(pb, title->value, "eng", 0x01); mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03); update_size(pb, pos2); return update_size(pb, pos); } return 0; } static void build_chunks(MOVTrack *trk) { int i; MOVIentry *chunk = &trk->cluster[0]; uint64_t chunkSize = chunk->size; chunk->chunkNum = 1; if (trk->chunkCount) return; trk->chunkCount = 1; for (i = 1; i<trk->entry; i++){ if (chunk->pos + chunkSize == trk->cluster[i].pos && chunkSize + trk->cluster[i].size < (1<<20)){ chunkSize += trk->cluster[i].size; chunk->samples_in_chunk += trk->cluster[i].entries; } else { trk->cluster[i].chunkNum = chunk->chunkNum+1; chunk=&trk->cluster[i]; chunkSize = chunk->size; trk->chunkCount++; } } } /** * Assign track ids. If option "use_stream_ids_as_track_ids" is set, * the stream ids are used as track ids. * * This assumes mov->tracks and s->streams are in the same order and * there are no gaps in either of them (so mov->tracks[n] refers to * s->streams[n]). * * As an exception, there can be more entries in * s->streams than in mov->tracks, in which case new track ids are * generated (starting after the largest found stream id). */ static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s) { int i; if (mov->track_ids_ok) return 0; if (mov->use_stream_ids_as_track_ids) { int next_generated_track_id = 0; for (i = 0; i < s->nb_streams; i++) { if (s->streams[i]->id > next_generated_track_id) next_generated_track_id = s->streams[i]->id; } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id; } } else { for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].track_id = i + 1; } } mov->track_ids_ok = 1; return 0; } static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int i; int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "moov"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) continue; mov->tracks[i].time = mov->time; if (mov->tracks[i].entry) build_chunks(&mov->tracks[i]); } if (mov->chapter_track) for (i = 0; i < s->nb_streams; i++) { mov->tracks[i].tref_tag = MKTAG('c','h','a','p'); mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->tag == MKTAG('r','t','p',' ')) { track->tref_tag = MKTAG('h','i','n','t'); track->tref_id = mov->tracks[track->src_track].track_id; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { int * fallback, size; fallback = (int*)av_stream_get_side_data(track->st, AV_PKT_DATA_FALLBACK_TRACK, &size); if (fallback != NULL && size == sizeof(int)) { if (*fallback >= 0 && *fallback < mov->nb_streams) { track->tref_tag = MKTAG('f','a','l','l'); track->tref_id = mov->tracks[*fallback].track_id; } } } } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('t','m','c','d')) { int src_trk = mov->tracks[i].src_track; mov->tracks[src_trk].tref_tag = mov->tracks[i].tag; mov->tracks[src_trk].tref_id = mov->tracks[i].track_id; //src_trk may have a different timescale than the tmcd track mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration, mov->tracks[i].timescale, mov->tracks[src_trk].timescale); } } mov_write_mvhd_tag(pb, mov); if (mov->mode != MODE_MOV && !mov->iods_skip) mov_write_iods_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL); if (ret < 0) return ret; } } if (mov->flags & FF_MOV_FLAG_FRAGMENT) mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */ if (mov->mode == MODE_PSP) mov_write_uuidusmt_tag(pb, s); else mov_write_udta_tag(pb, mov, s); return update_size(pb, pos); } static void param_write_int(AVIOContext *pb, const char *name, int value) { avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value); } static void param_write_string(AVIOContext *pb, const char *name, const char *value) { avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value); } static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len) { char buf[150]; len = FFMIN(sizeof(buf) / 2 - 1, len); ff_data_to_hex(buf, value, len, 0); buf[2 * len] = '\0'; avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf); } static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s) { int64_t pos = avio_tell(pb); int i; int64_t manifest_bit_rate = 0; AVCPBProperties *props = NULL; static const uint8_t uuid[] = { 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd, 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }; avio_wb32(pb, 0); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_wb32(pb, 0); avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n"); avio_printf(pb, "<head>\n"); if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT)) avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n", LIBAVFORMAT_IDENT); avio_printf(pb, "</head>\n"); avio_printf(pb, "<body>\n"); avio_printf(pb, "<switch>\n"); mov_setup_track_ids(mov, s); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; const char *type; int track_id = track->track_id; char track_name_buf[32] = { 0 }; AVStream *st = track->st; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) { type = "video"; } else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) { type = "audio"; } else { continue; } props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL); if (track->par->bit_rate) { manifest_bit_rate = track->par->bit_rate; } else if (props) { manifest_bit_rate = props->max_bitrate; } avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type, manifest_bit_rate); param_write_int(pb, "systemBitrate", manifest_bit_rate); param_write_int(pb, "trackID", track_id); param_write_string(pb, "systemLanguage", lang ? lang->value : "und"); /* Build track name piece by piece: */ /* 1. track type */ av_strlcat(track_name_buf, type, sizeof(track_name_buf)); /* 2. track language, if available */ if (lang) av_strlcatf(track_name_buf, sizeof(track_name_buf), "_%s", lang->value); /* 3. special type suffix */ /* "_cc" = closed captions, "_ad" = audio_description */ if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED) av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf)); else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED) av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf)); param_write_string(pb, "trackName", track_name_buf); if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->par->codec_id == AV_CODEC_ID_H264) { uint8_t *ptr; int size = track->par->extradata_size; if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr, &size)) { param_write_hex(pb, "CodecPrivateData", ptr ? ptr : track->par->extradata, size); av_free(ptr); } param_write_string(pb, "FourCC", "H264"); } else if (track->par->codec_id == AV_CODEC_ID_VC1) { param_write_string(pb, "FourCC", "WVC1"); param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); } param_write_int(pb, "MaxWidth", track->par->width); param_write_int(pb, "MaxHeight", track->par->height); param_write_int(pb, "DisplayWidth", track->par->width); param_write_int(pb, "DisplayHeight", track->par->height); } else { if (track->par->codec_id == AV_CODEC_ID_AAC) { switch (track->par->profile) { case FF_PROFILE_AAC_HE_V2: param_write_string(pb, "FourCC", "AACP"); break; case FF_PROFILE_AAC_HE: param_write_string(pb, "FourCC", "AACH"); break; default: param_write_string(pb, "FourCC", "AACL"); } } else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) { param_write_string(pb, "FourCC", "WMAP"); } param_write_hex(pb, "CodecPrivateData", track->par->extradata, track->par->extradata_size); param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id)); param_write_int(pb, "Channels", track->par->channels); param_write_int(pb, "SamplingRate", track->par->sample_rate); param_write_int(pb, "BitsPerSample", 16); param_write_int(pb, "PacketSize", track->par->block_align ? track->par->block_align : 4); } avio_printf(pb, "</%s>\n", type); } avio_printf(pb, "</switch>\n"); avio_printf(pb, "</body>\n"); avio_printf(pb, "</smil>\n"); return update_size(pb, pos); } static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 16); ffio_wfourcc(pb, "mfhd"); avio_wb32(pb, 0); avio_wb32(pb, mov->fragments); return 0; } static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry) { return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO : (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC); } static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET; if (!track->entry) { flags |= MOV_TFHD_DURATION_IS_EMPTY; } else { flags |= MOV_TFHD_DEFAULT_FLAGS; } if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET) flags &= ~MOV_TFHD_BASE_DATA_OFFSET; if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) { flags &= ~MOV_TFHD_BASE_DATA_OFFSET; flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF; } /* Don't set a default sample size, the silverlight player refuses * to play files with that set. Don't set a default sample duration, * WMP freaks out if it is set. Don't set a base data offset, PIFF * file format says it MUST NOT be set. */ if (track->mode == MODE_ISM) flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION | MOV_TFHD_BASE_DATA_OFFSET); avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfhd"); avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, track->track_id); /* track-id */ if (flags & MOV_TFHD_BASE_DATA_OFFSET) avio_wb64(pb, moof_offset); if (flags & MOV_TFHD_DEFAULT_DURATION) { track->default_duration = get_cluster_duration(track, 0); avio_wb32(pb, track->default_duration); } if (flags & MOV_TFHD_DEFAULT_SIZE) { track->default_size = track->entry ? track->cluster[0].size : 1; avio_wb32(pb, track->default_size); } else track->default_size = -1; if (flags & MOV_TFHD_DEFAULT_FLAGS) { /* Set the default flags based on the second sample, if available. * If the first sample is different, that can be signaled via a separate field. */ if (track->entry > 1) track->default_sample_flags = get_sample_flags(track, &track->cluster[1]); else track->default_sample_flags = track->par->codec_type == AVMEDIA_TYPE_VIDEO ? (MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) : MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO; avio_wb32(pb, track->default_sample_flags); } return update_size(pb, pos); } static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int moof_size, int first, int end) { int64_t pos = avio_tell(pb); uint32_t flags = MOV_TRUN_DATA_OFFSET; int i; for (i = first; i < end; i++) { if (get_cluster_duration(track, i) != track->default_duration) flags |= MOV_TRUN_SAMPLE_DURATION; if (track->cluster[i].size != track->default_size) flags |= MOV_TRUN_SAMPLE_SIZE; if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags) flags |= MOV_TRUN_SAMPLE_FLAGS; } if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 && get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags) flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS; if (track->flags & MOV_TRACK_CTTS) flags |= MOV_TRUN_SAMPLE_CTS; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "trun"); if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) avio_w8(pb, 1); /* version */ else avio_w8(pb, 0); /* version */ avio_wb24(pb, flags); avio_wb32(pb, end - first); /* sample count */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && !(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) && !mov->first_trun) avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */ else avio_wb32(pb, moof_size + 8 + track->data_offset + track->cluster[first].pos); /* data offset */ if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[first])); for (i = first; i < end; i++) { if (flags & MOV_TRUN_SAMPLE_DURATION) avio_wb32(pb, get_cluster_duration(track, i)); if (flags & MOV_TRUN_SAMPLE_SIZE) avio_wb32(pb, track->cluster[i].size); if (flags & MOV_TRUN_SAMPLE_FLAGS) avio_wb32(pb, get_sample_flags(track, &track->cluster[i])); if (flags & MOV_TRUN_SAMPLE_CTS) avio_wb32(pb, track->cluster[i].cts); } mov->first_trun = 0; return update_size(pb, pos); } static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); static const uint8_t uuid[] = { 0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6, 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2 }; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_wb64(pb, track->start_dts + track->frag_start + track->cluster[0].cts); avio_wb64(pb, track->end_pts - (track->cluster[0].dts + track->cluster[0].cts)); return update_size(pb, pos); } static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int entry) { int n = track->nb_frag_info - 1 - entry, i; int size = 8 + 16 + 4 + 1 + 16*n; static const uint8_t uuid[] = { 0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95, 0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f }; if (entry < 0) return 0; avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET); avio_wb32(pb, size); ffio_wfourcc(pb, "uuid"); avio_write(pb, uuid, sizeof(uuid)); avio_w8(pb, 1); avio_wb24(pb, 0); avio_w8(pb, n); for (i = 0; i < n; i++) { int index = entry + 1 + i; avio_wb64(pb, track->frag_info[index].time); avio_wb64(pb, track->frag_info[index].duration); } if (n < mov->ism_lookahead) { int free_size = 16 * (mov->ism_lookahead - n); avio_wb32(pb, free_size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, free_size - 8); } return 0; } static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; for (i = 0; i < mov->ism_lookahead; i++) { /* Update the tfrf tag for the last ism_lookahead fragments, * nb_frag_info - 1 is the next fragment to be written. */ mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i); } avio_seek(pb, pos, SEEK_SET); return 0; } static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks, int size) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; MOVFragmentInfo *info; if ((tracks >= 0 && i != tracks) || !track->entry) continue; track->nb_frag_info++; if (track->nb_frag_info >= track->frag_info_capacity) { unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT; if (av_reallocp_array(&track->frag_info, new_capacity, sizeof(*track->frag_info))) return AVERROR(ENOMEM); track->frag_info_capacity = new_capacity; } info = &track->frag_info[track->nb_frag_info - 1]; info->offset = avio_tell(pb); info->size = size; // Try to recreate the original pts for the first packet // from the fields we have stored info->time = track->start_dts + track->frag_start + track->cluster[0].cts; info->duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); // If the pts is less than zero, we will have trimmed // away parts of the media track using an edit list, // and the corresponding start presentation time is zero. if (info->time < 0) { info->duration += info->time; info->time = 0; } info->tfrf_offset = 0; mov_write_tfrf_tags(pb, mov, track); } return 0; } static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max) { int i; for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if ((tracks >= 0 && i != tracks) || !track->entry) continue; if (track->nb_frag_info > max) { memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info)); track->nb_frag_info = max; } } } static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "tfdt"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb64(pb, track->frag_start); return update_size(pb, pos); } static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track, int64_t moof_offset, int moof_size) { int64_t pos = avio_tell(pb); int i, start = 0; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "traf"); mov_write_tfhd_tag(pb, mov, track, moof_offset); if (mov->mode != MODE_ISM) mov_write_tfdt_tag(pb, track); for (i = 1; i < track->entry; i++) { if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) { mov_write_trun_tag(pb, mov, track, moof_size, start, i); start = i; } } mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry); if (mov->mode == MODE_ISM) { mov_write_tfxd_tag(pb, track); if (mov->ism_lookahead) { int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead; if (track->nb_frag_info > 0) { MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1]; if (!info->tfrf_offset) info->tfrf_offset = avio_tell(pb); } avio_wb32(pb, 8 + size); ffio_wfourcc(pb, "free"); for (i = 0; i < size; i++) avio_w8(pb, 0); } } return update_size(pb, pos); } static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov, int tracks, int moof_size) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "moof"); mov->first_trun = 1; mov_write_mfhd_tag(pb, mov); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; if (!track->entry) continue; mov_write_traf_tag(pb, mov, track, pos, moof_size); } return update_size(pb, pos); } static int mov_write_sidx_tag(AVIOContext *pb, MOVTrack *track, int ref_size, int total_sidx_size) { int64_t pos = avio_tell(pb), offset_pos, end_pos; int64_t presentation_time, duration, offset; int starts_with_SAP, i, entries; if (track->entry) { entries = 1; presentation_time = track->start_dts + track->frag_start + track->cluster[0].cts; duration = track->end_pts - (track->cluster[0].dts + track->cluster[0].cts); starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE; // pts<0 should be cut away using edts if (presentation_time < 0) { duration += presentation_time; presentation_time = 0; } } else { entries = track->nb_frag_info; if (entries <= 0) return 0; presentation_time = track->frag_info[0].time; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "sidx"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); /* reference_ID */ avio_wb32(pb, track->timescale); /* timescale */ avio_wb64(pb, presentation_time); /* earliest_presentation_time */ offset_pos = avio_tell(pb); avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */ avio_wb16(pb, 0); /* reserved */ avio_wb16(pb, entries); /* reference_count */ for (i = 0; i < entries; i++) { if (!track->entry) { if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) { av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n"); } duration = track->frag_info[i].duration; ref_size = track->frag_info[i].size; starts_with_SAP = 1; } avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */ avio_wb32(pb, duration); /* subsegment_duration */ avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */ } end_pos = avio_tell(pb); offset = pos + total_sidx_size - end_pos; avio_seek(pb, offset_pos, SEEK_SET); avio_wb64(pb, offset); avio_seek(pb, end_pos, SEEK_SET); return update_size(pb, pos); } static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov, int tracks, int ref_size) { int i, round, ret; AVIOContext *avio_buf; int total_size = 0; for (round = 0; round < 2; round++) { // First run one round to calculate the total size of all // sidx atoms. // This would be much simpler if we'd only write one sidx // atom, for the first track in the moof. if (round == 0) { if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; } else { avio_buf = pb; } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (tracks >= 0 && i != tracks) continue; // When writing a sidx for the full file, entry is 0, but // we want to include all tracks. ref_size is 0 in this case, // since we read it from frag_info instead. if (!track->entry && ref_size > 0) continue; total_size -= mov_write_sidx_tag(avio_buf, track, ref_size, total_size); } if (round == 0) total_size = ffio_close_null_buf(avio_buf); } return 0; } static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks) { int64_t pos = avio_tell(pb), pts_us, ntp_ts; MOVTrack *first_track; /* PRFT should be associated with at most one track. So, choosing only the * first track. */ if (tracks > 0) return 0; first_track = &(mov->tracks[0]); if (!first_track->entry) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n"); return 0; } if (first_track->cluster[0].pts == AV_NOPTS_VALUE) { av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n"); return 0; } if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) { ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time()); } else if (mov->write_prft == MOV_PRFT_SRC_PTS) { pts_us = av_rescale_q(first_track->cluster[0].pts, first_track->st->time_base, AV_TIME_BASE_Q); ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US); } else { av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n", mov->write_prft); return 0; } avio_wb32(pb, 0); // Size place holder ffio_wfourcc(pb, "prft"); // Type avio_w8(pb, 1); // Version avio_wb24(pb, 0); // Flags avio_wb32(pb, first_track->track_id); // reference track ID avio_wb64(pb, ntp_ts); // NTP time stamp avio_wb64(pb, first_track->cluster[0].pts); //media time return update_size(pb, pos); } static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks, int64_t mdat_size) { AVIOContext *avio_buf; int ret, moof_size; if ((ret = ffio_open_null_buf(&avio_buf)) < 0) return ret; mov_write_moof_tag_internal(avio_buf, mov, tracks, 0); moof_size = ffio_close_null_buf(avio_buf); if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size); if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB) mov_write_prft_tag(pb, mov, tracks); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX || !(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) || mov->ism_lookahead) { if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0) return ret; if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) && mov->flags & FF_MOV_FLAG_SKIP_TRAILER) { mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1); } } return mov_write_moof_tag_internal(pb, mov, tracks, moof_size); } static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "tfra"); avio_w8(pb, 1); /* version */ avio_wb24(pb, 0); avio_wb32(pb, track->track_id); avio_wb32(pb, 0); /* length of traf/trun/sample num */ avio_wb32(pb, track->nb_frag_info); for (i = 0; i < track->nb_frag_info; i++) { avio_wb64(pb, track->frag_info[i].time); avio_wb64(pb, track->frag_info[i].offset + track->data_offset); avio_w8(pb, 1); /* traf number */ avio_w8(pb, 1); /* trun number */ avio_w8(pb, 1); /* sample number */ } return update_size(pb, pos); } static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov) { int64_t pos = avio_tell(pb); int i; avio_wb32(pb, 0); /* size placeholder */ ffio_wfourcc(pb, "mfra"); /* An empty mfra atom is enough to indicate to the publishing point that * the stream has ended. */ if (mov->flags & FF_MOV_FLAG_ISML) return update_size(pb, pos); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->nb_frag_info) mov_write_tfra_tag(pb, track); } avio_wb32(pb, 16); ffio_wfourcc(pb, "mfro"); avio_wb32(pb, 0); /* version + flags */ avio_wb32(pb, avio_tell(pb) + 4 - pos); return update_size(pb, pos); } static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov) { avio_wb32(pb, 8); // placeholder for extended size field (64 bit) ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free"); mov->mdat_pos = avio_tell(pb); avio_wb32(pb, 0); /* size placeholder*/ ffio_wfourcc(pb, "mdat"); return 0; } /* TODO: This needs to be more general */ static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int64_t pos = avio_tell(pb); int has_h264 = 0, has_video = 0; int minor = 0x200; int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) has_video = 1; if (st->codecpar->codec_id == AV_CODEC_ID_H264) has_h264 = 1; } avio_wb32(pb, 0); /* size */ ffio_wfourcc(pb, "ftyp"); if (mov->major_brand && strlen(mov->major_brand) >= 4) ffio_wfourcc(pb, mov->major_brand); else if (mov->mode == MODE_3GP) { ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4"); minor = has_h264 ? 0x100 : 0x200; } else if (mov->mode & MODE_3G2) { ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a"); minor = has_h264 ? 0x20000 : 0x10000; } else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) ffio_wfourcc(pb, "iso4"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "isom"); else if (mov->mode == MODE_IPOD) ffio_wfourcc(pb, has_video ? "M4V ":"M4A "); else if (mov->mode == MODE_ISM) ffio_wfourcc(pb, "isml"); else if (mov->mode == MODE_F4V) ffio_wfourcc(pb, "f4v "); else ffio_wfourcc(pb, "qt "); avio_wb32(pb, minor); if (mov->mode == MODE_MOV) ffio_wfourcc(pb, "qt "); else if (mov->mode == MODE_ISM) { ffio_wfourcc(pb, "piff"); } else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) { ffio_wfourcc(pb, "isom"); ffio_wfourcc(pb, "iso2"); if (has_h264) ffio_wfourcc(pb, "avc1"); } // We add tfdt atoms when fragmenting, signal this with the iso6 compatible // brand. This is compatible with users that don't understand tfdt. if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM) ffio_wfourcc(pb, "iso6"); if (mov->mode == MODE_3GP) ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4"); else if (mov->mode & MODE_3G2) ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a"); else if (mov->mode == MODE_PSP) ffio_wfourcc(pb, "MSNV"); else if (mov->mode == MODE_MP4) ffio_wfourcc(pb, "mp41"); if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) ffio_wfourcc(pb, "dash"); return update_size(pb, pos); } static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s) { AVStream *video_st = s->streams[0]; AVCodecParameters *video_par = s->streams[0]->codecpar; AVCodecParameters *audio_par = s->streams[1]->codecpar; int audio_rate = audio_par->sample_rate; int64_t frame_rate = video_st->avg_frame_rate.den ? (video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den : 0; int audio_kbitrate = audio_par->bit_rate / 1000; int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate); if (frame_rate < 0 || frame_rate > INT32_MAX) { av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000); return AVERROR(EINVAL); } avio_wb32(pb, 0x94); /* size */ ffio_wfourcc(pb, "uuid"); ffio_wfourcc(pb, "PROF"); avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */ avio_wb32(pb, 0xbb88695c); avio_wb32(pb, 0xfac9c740); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x3); /* 3 sections ? */ avio_wb32(pb, 0x14); /* size */ ffio_wfourcc(pb, "FPRF"); avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x0); /* ? */ avio_wb32(pb, 0x2c); /* size */ ffio_wfourcc(pb, "APRF"); /* audio */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x2); /* TrackID */ ffio_wfourcc(pb, "mp4a"); avio_wb32(pb, 0x20f); avio_wb32(pb, 0x0); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_kbitrate); avio_wb32(pb, audio_rate); avio_wb32(pb, audio_par->channels); avio_wb32(pb, 0x34); /* size */ ffio_wfourcc(pb, "VPRF"); /* video */ avio_wb32(pb, 0x0); avio_wb32(pb, 0x1); /* TrackID */ if (video_par->codec_id == AV_CODEC_ID_H264) { ffio_wfourcc(pb, "avc1"); avio_wb16(pb, 0x014D); avio_wb16(pb, 0x0015); } else { ffio_wfourcc(pb, "mp4v"); avio_wb16(pb, 0x0000); avio_wb16(pb, 0x0103); } avio_wb32(pb, 0x0); avio_wb32(pb, video_kbitrate); avio_wb32(pb, video_kbitrate); avio_wb32(pb, frame_rate); avio_wb32(pb, frame_rate); avio_wb16(pb, video_par->width); avio_wb16(pb, video_par->height); avio_wb32(pb, 0x010001); /* ? */ return 0; } static int mov_write_identification(AVIOContext *pb, AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; mov_write_ftyp_tag(pb,s); if (mov->mode == MODE_PSP) { int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (is_cover_image(st)) continue; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) video_streams_nb++; else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) audio_streams_nb++; else other_streams_nb++; } if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) { av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n"); return AVERROR(EINVAL); } return mov_write_uuidprof_tag(pb, s); } return 0; } static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags) { uint32_t c = -1; int i, closed_gop = 0; for (i = 0; i < pkt->size - 4; i++) { c = (c << 8) + pkt->data[i]; if (c == 0x1b8) { // gop closed_gop = pkt->data[i + 4] >> 6 & 0x01; } else if (c == 0x100) { // pic int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6); if (!temp_ref || closed_gop) // I picture is not reordered *flags = MOV_SYNC_SAMPLE; else *flags = MOV_PARTIAL_SYNC_SAMPLE; break; } } return 0; } static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk) { const uint8_t *start, *next, *end = pkt->data + pkt->size; int seq = 0, entry = 0; int key = pkt->flags & AV_PKT_FLAG_KEY; start = find_next_marker(pkt->data, end); for (next = start; next < end; start = next) { next = find_next_marker(start + 4, end); switch (AV_RB32(start)) { case VC1_CODE_SEQHDR: seq = 1; break; case VC1_CODE_ENTRYPOINT: entry = 1; break; case VC1_CODE_SLICE: trk->vc1_info.slices = 1; break; } } if (!trk->entry && trk->vc1_info.first_packet_seen) trk->vc1_info.first_frag_written = 1; if (!trk->entry && !trk->vc1_info.first_frag_written) { /* First packet in first fragment */ trk->vc1_info.first_packet_seq = seq; trk->vc1_info.first_packet_entry = entry; trk->vc1_info.first_packet_seen = 1; } else if ((seq && !trk->vc1_info.packet_seq) || (entry && !trk->vc1_info.packet_entry)) { int i; for (i = 0; i < trk->entry; i++) trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE; trk->has_keyframes = 0; if (seq) trk->vc1_info.packet_seq = 1; if (entry) trk->vc1_info.packet_entry = 1; if (!trk->vc1_info.first_frag_written) { /* First fragment */ if ((!seq || trk->vc1_info.first_packet_seq) && (!entry || trk->vc1_info.first_packet_entry)) { /* First packet had the same headers as this one, readd the * sync sample flag. */ trk->cluster[0].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes = 1; } } } if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry) key = seq && entry; else if (trk->vc1_info.packet_seq) key = seq; else if (trk->vc1_info.packet_entry) key = entry; if (key) { trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE; trk->has_keyframes++; } } static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track) { MOVMuxContext *mov = s->priv_data; int ret, buf_size; uint8_t *buf; int i, offset; if (!track->mdat_buf) return 0; if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; offset = avio_tell(mov->mdat_buf); avio_write(mov->mdat_buf, buf, buf_size); av_free(buf); for (i = track->entries_flushed; i < track->entry; i++) track->cluster[i].pos += offset; track->entries_flushed = track->entry; return 0; } static int mov_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int i, first_track = -1; int64_t mdat_size = 0; int ret; int has_video = 0, starts_with_key = 0, first_video_track = 1; if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) return 0; // Try to fill in the duration of the last packet in each stream // from queued packets in the interleave queues. If the flushing // of fragments was triggered automatically by an AVPacket, we // already have reliable info for the end of that track, but other // tracks may need to be filled in. for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (!track->end_reliable) { AVPacket pkt; if (!ff_interleaved_peek(s, i, &pkt, 1)) { if (track->dts_shift != AV_NOPTS_VALUE) pkt.dts += track->dts_shift; track->track_duration = pkt.dts - track->start_dts; if (pkt.pts != AV_NOPTS_VALUE) track->end_pts = pkt.pts; else track->end_pts = pkt.dts; } } } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (track->entry <= 1) continue; // Sample durations are calculated as the diff of dts values, // but for the last sample in a fragment, we don't know the dts // of the first sample in the next fragment, so we have to rely // on what was set as duration in the AVPacket. Not all callers // set this though, so we might want to replace it with an // estimate if it currently is zero. if (get_cluster_duration(track, track->entry - 1) != 0) continue; // Use the duration (i.e. dts diff) of the second last sample for // the last one. This is a wild guess (and fatal if it turns out // to be too long), but probably the best we can do - having a zero // duration is bad as well. track->track_duration += get_cluster_duration(track, track->entry - 2); track->end_pts += get_cluster_duration(track, track->entry - 2); if (!mov->missing_duration_warned) { av_log(s, AV_LOG_WARNING, "Estimating the duration of the last packet in a " "fragment, consider setting the duration field in " "AVPacket instead.\n"); mov->missing_duration_warned = 1; } } if (!mov->moov_written) { int64_t pos = avio_tell(s->pb); uint8_t *buf; int buf_size, moov_size; for (i = 0; i < mov->nb_streams; i++) if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st)) break; /* Don't write the initial moov unless all tracks have data */ if (i < mov->nb_streams && !force) return 0; moov_size = get_moov_size(s); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = pos + moov_size + 8; avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER); if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov_write_identification(s->pb, s); if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) { if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); avio_flush(s->pb); mov->moov_written = 1; return 0; } buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; avio_wb32(s->pb, buf_size + 8); ffio_wfourcc(s->pb, "mdat"); avio_write(s->pb, buf, buf_size); av_free(buf); if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(s->pb); mov->moov_written = 1; mov->mdat_size = 0; for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].entry) mov->tracks[i].frag_start += mov->tracks[i].start_dts + mov->tracks[i].track_duration - mov->tracks[i].cluster[0].dts; mov->tracks[i].entry = 0; mov->tracks[i].end_reliable = 0; } avio_flush(s->pb); return 0; } if (mov->frag_interleave) { for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int ret; if ((ret = mov_flush_fragment_interleaving(s, track)) < 0) return ret; } if (!mov->mdat_buf) return 0; mdat_size = avio_tell(mov->mdat_buf); } for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave) track->data_offset = 0; else track->data_offset = mdat_size; if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) { has_video = 1; if (first_video_track) { if (track->entry) starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE; first_video_track = 0; } } if (!track->entry) continue; if (track->mdat_buf) mdat_size += avio_tell(track->mdat_buf); if (first_track < 0) first_track = i; } if (!mdat_size) return 0; avio_write_marker(s->pb, av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale), (has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); for (i = 0; i < mov->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; int buf_size, write_moof = 1, moof_tracks = -1; uint8_t *buf; int64_t duration = 0; if (track->entry) duration = track->start_dts + track->track_duration - track->cluster[0].dts; if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) { if (!track->mdat_buf) continue; mdat_size = avio_tell(track->mdat_buf); moof_tracks = i; } else { write_moof = i == first_track; } if (write_moof) { avio_flush(s->pb); mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size); mov->fragments++; avio_wb32(s->pb, mdat_size + 8); ffio_wfourcc(s->pb, "mdat"); } if (track->entry) track->frag_start += duration; track->entry = 0; track->entries_flushed = 0; track->end_reliable = 0; if (!mov->frag_interleave) { if (!track->mdat_buf) continue; buf_size = avio_close_dyn_buf(track->mdat_buf, &buf); track->mdat_buf = NULL; } else { if (!mov->mdat_buf) continue; buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf); mov->mdat_buf = NULL; } avio_write(s->pb, buf, buf_size); av_free(buf); } mov->mdat_size = 0; avio_flush(s->pb); return 0; } static int mov_auto_flush_fragment(AVFormatContext *s, int force) { MOVMuxContext *mov = s->priv_data; int had_moov = mov->moov_written; int ret = mov_flush_fragment(s, force); if (ret < 0) return ret; // If using delay_moov, the first flush only wrote the moov, // not the actual moof+mdat pair, thus flush once again. if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV) ret = mov_flush_fragment(s, force); return ret; } static int check_pkt(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; int64_t ref; uint64_t duration; if (trk->entry) { ref = trk->cluster[trk->entry - 1].dts; } else if ( trk->start_dts != AV_NOPTS_VALUE && !trk->frag_discont) { ref = trk->start_dts + trk->track_duration; } else ref = pkt->dts; // Skip tests for the first packet if (trk->dts_shift != AV_NOPTS_VALUE) { /* With negative CTS offsets we have set an offset to the DTS, * reverse this for the check. */ ref -= trk->dts_shift; } duration = pkt->dts - ref; if (pkt->dts < ref || duration >= INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n", duration, pkt->dts ); pkt->dts = ref + 1; pkt->pts = AV_NOPTS_VALUE; } if (pkt->duration < 0 || pkt->duration > INT_MAX) { av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration); return AVERROR(EINVAL); } return 0; } int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; unsigned int samples_in_chunk = 0; int size = pkt->size, ret = 0; uint8_t *reformatted_data = NULL; ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAGMENT) { int ret; if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) { if (mov->frag_interleave && mov->fragments > 0) { if (trk->entry - trk->entries_flushed >= mov->frag_interleave) { if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0) return ret; } } if (!trk->mdat_buf) { if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0) return ret; } pb = trk->mdat_buf; } else { if (!mov->mdat_buf) { if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0) return ret; } pb = mov->mdat_buf; } } if (par->codec_id == AV_CODEC_ID_AMR_NB) { /* We must find out how many AMR blocks there are in one packet */ static const uint16_t packed_size[16] = {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1}; int len = 0; while (len < size && samples_in_chunk < 100) { len += packed_size[(pkt->data[len] >> 3) & 0x0F]; samples_in_chunk++; } if (samples_in_chunk > 1) { av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n"); return -1; } } else if (par->codec_id == AV_CODEC_ID_ADPCM_MS || par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) { samples_in_chunk = trk->par->frame_size; } else if (trk->sample_size) samples_in_chunk = size / trk->sample_size; else samples_in_chunk = 1; if (samples_in_chunk < 1) { av_log(s, AV_LOG_ERROR, "fatal error, input packet contains no samples\n"); return AVERROR_PATCHWELCOME; } /* copy extradata if it exists */ if (trk->vos_len == 0 && par->extradata_size > 0 && !TAG_IS_AVCI(trk->tag) && (par->codec_id != AV_CODEC_ID_DNXHD)) { trk->vos_len = par->extradata_size; trk->vos_data = av_malloc(trk->vos_len); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, par->extradata, trk->vos_len); } if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return -1; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) { /* from x264 or from bytestream H.264 */ /* NAL reformatting needed */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data, &size); avio_write(pb, reformatted_data, size); } else { if (trk->cenc.aes_ctr) { size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size); if (size < 0) { ret = size; goto err; } } else { size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size); } } } else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 && (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) { /* extradata is Annex B, assume the bitstream is too and convert it */ if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) { ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL); avio_write(pb, reformatted_data, size); } else { size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL); } #if CONFIG_AC3_PARSER } else if (par->codec_id == AV_CODEC_ID_EAC3) { size = handle_eac3(mov, pkt, trk); if (size < 0) return size; else if (!size) goto end; avio_write(pb, pkt->data, size); #endif } else { if (trk->cenc.aes_ctr) { if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) { int nal_size_length = (par->extradata[4] & 0x3) + 1; ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size); } else { ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size); } if (ret) { goto err; } } else { avio_write(pb, pkt->data, size); } } if ((par->codec_id == AV_CODEC_ID_DNXHD || par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) { /* copy frame to create needed atoms */ trk->vos_len = size; trk->vos_data = av_malloc(size); if (!trk->vos_data) { ret = AVERROR(ENOMEM); goto err; } memcpy(trk->vos_data, pkt->data, size); } if (trk->entry >= trk->cluster_capacity) { unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE); if (av_reallocp_array(&trk->cluster, new_capacity, sizeof(*trk->cluster))) { ret = AVERROR(ENOMEM); goto err; } trk->cluster_capacity = new_capacity; } trk->cluster[trk->entry].pos = avio_tell(pb) - size; trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk; trk->cluster[trk->entry].chunkNum = 0; trk->cluster[trk->entry].size = size; trk->cluster[trk->entry].entries = samples_in_chunk; trk->cluster[trk->entry].dts = pkt->dts; trk->cluster[trk->entry].pts = pkt->pts; if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) { if (!trk->frag_discont) { /* First packet of a new fragment. We already wrote the duration * of the last packet of the previous fragment based on track_duration, * which might not exactly match our dts. Therefore adjust the dts * of this packet to be what the previous packets duration implies. */ trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration; /* We also may have written the pts and the corresponding duration * in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with * the next fragment. This means the cts of the first sample must * be the same in all fragments, unless end_pts was updated by * the packet causing the fragment to be written. */ if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) || mov->mode == MODE_ISM) pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts; } else { /* New fragment, but discontinuous from previous fragments. * Pretend the duration sum of the earlier fragments is * pkt->dts - trk->start_dts. */ trk->frag_start = pkt->dts - trk->start_dts; trk->end_pts = AV_NOPTS_VALUE; trk->frag_discont = 0; } } if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) { /* Not using edit lists and shifting the first track to start from zero. * If the other streams start from a later timestamp, we won't be able * to signal the difference in starting time without an edit list. * Thus move the timestamp for this first sample to 0, increasing * its duration instead. */ trk->cluster[trk->entry].dts = trk->start_dts = 0; } if (trk->start_dts == AV_NOPTS_VALUE) { trk->start_dts = pkt->dts; if (trk->frag_discont) { if (mov->use_editlist) { /* Pretend the whole stream started at pts=0, with earlier fragments * already written. If the stream started at pts=0, the duration sum * of earlier fragments would have been pkt->pts. */ trk->frag_start = pkt->pts; trk->start_dts = pkt->dts - pkt->pts; } else { /* Pretend the whole stream started at dts=0, with earlier fragments * already written, with a duration summing up to pkt->dts. */ trk->frag_start = pkt->dts; trk->start_dts = 0; } trk->frag_discont = 0; } else if (pkt->dts && mov->moov_written) av_log(s, AV_LOG_WARNING, "Track %d starts with a nonzero dts %"PRId64", while the moov " "already has been written. Set the delay_moov flag to handle " "this case.\n", pkt->stream_index, pkt->dts); } trk->track_duration = pkt->dts - trk->start_dts + pkt->duration; trk->last_sample_is_subtitle_end = 0; if (pkt->pts == AV_NOPTS_VALUE) { av_log(s, AV_LOG_WARNING, "pts has no value\n"); pkt->pts = pkt->dts; } if (pkt->dts != pkt->pts) trk->flags |= MOV_TRACK_CTTS; trk->cluster[trk->entry].cts = pkt->pts - pkt->dts; trk->cluster[trk->entry].flags = 0; if (trk->start_cts == AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; if (trk->end_pts == AV_NOPTS_VALUE) trk->end_pts = trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration; else trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts + trk->cluster[trk->entry].cts + pkt->duration); if (par->codec_id == AV_CODEC_ID_VC1) { mov_parse_vc1_frame(pkt, trk); } else if (pkt->flags & AV_PKT_FLAG_KEY) { if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO && trk->entry > 0) { // force sync sample for the first key frame mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags); if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE) trk->flags |= MOV_TRACK_STPS; } else { trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE; } if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE) trk->has_keyframes++; } if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) { trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE; trk->has_disposable++; } trk->entry++; trk->sample_count += samples_in_chunk; mov->mdat_size += size; if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry, reformatted_data, size); end: err: av_free(reformatted_data); return ret; } static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk = &mov->tracks[pkt->stream_index]; AVCodecParameters *par = trk->par; int64_t frag_duration = 0; int size = pkt->size; int ret = check_pkt(s, pkt); if (ret < 0) return ret; if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) { int i; for (i = 0; i < s->nb_streams; i++) mov->tracks[i].frag_discont = 1; mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT; } if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) { if (trk->dts_shift == AV_NOPTS_VALUE) trk->dts_shift = pkt->pts - pkt->dts; pkt->dts += trk->dts_shift; } if (trk->par->codec_id == AV_CODEC_ID_MP4ALS || trk->par->codec_id == AV_CODEC_ID_AAC || trk->par->codec_id == AV_CODEC_ID_FLAC) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!newextra) return AVERROR(ENOMEM); av_free(par->extradata); par->extradata = newextra; memcpy(par->extradata, side, side_size); par->extradata_size = side_size; if (!pkt->size) // Flush packet mov->need_rewrite_extradata = 1; } } if (!pkt->size) { if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) { trk->start_dts = pkt->dts; if (pkt->pts != AV_NOPTS_VALUE) trk->start_cts = pkt->pts - pkt->dts; else trk->start_cts = 0; } return 0; /* Discard 0 sized packets */ } if (trk->entry && pkt->stream_index < s->nb_streams) frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts, s->streams[pkt->stream_index]->time_base, AV_TIME_BASE_Q); if ((mov->max_fragment_duration && frag_duration >= mov->max_fragment_duration) || (mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) || (mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME && par->codec_type == AVMEDIA_TYPE_VIDEO && trk->entry && pkt->flags & AV_PKT_FLAG_KEY) || (mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) { if (frag_duration >= mov->min_fragment_duration) { // Set the duration of this track to line up with the next // sample in this track. This avoids relying on AVPacket // duration, but only helps for this particular track, not // for the other ones that are flushed at the same time. trk->track_duration = pkt->dts - trk->start_dts; if (pkt->pts != AV_NOPTS_VALUE) trk->end_pts = pkt->pts; else trk->end_pts = pkt->dts; trk->end_reliable = 1; mov_auto_flush_fragment(s, 0); } } return ff_mov_write_packet(s, pkt); } static int mov_write_subtitle_end_packet(AVFormatContext *s, int stream_index, int64_t dts) { AVPacket end; uint8_t data[2] = {0}; int ret; av_init_packet(&end); end.size = sizeof(data); end.data = data; end.pts = dts; end.dts = dts; end.duration = 0; end.stream_index = stream_index; ret = mov_write_single_packet(s, &end); av_packet_unref(&end); return ret; } static int mov_write_packet(AVFormatContext *s, AVPacket *pkt) { MOVMuxContext *mov = s->priv_data; MOVTrack *trk; if (!pkt) { mov_flush_fragment(s, 1); return 1; } trk = &mov->tracks[pkt->stream_index]; if (is_cover_image(trk->st)) { int ret; if (trk->st->nb_frames >= 1) { if (trk->st->nb_frames == 1) av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d," " ignoring.\n", pkt->stream_index); return 0; } if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0) return ret; return 0; } else { int i; if (!pkt->size) return mov_write_single_packet(s, pkt); /* Passthrough. */ /* * Subtitles require special handling. * * 1) For full complaince, every track must have a sample at * dts == 0, which is rarely true for subtitles. So, as soon * as we see any packet with dts > 0, write an empty subtitle * at dts == 0 for any subtitle track with no samples in it. * * 2) For each subtitle track, check if the current packet's * dts is past the duration of the last subtitle sample. If * so, we now need to write an end sample for that subtitle. * * This must be done conditionally to allow for subtitles that * immediately replace each other, in which case an end sample * is not needed, and is, in fact, actively harmful. * * 3) See mov_write_trailer for how the final end sample is * handled. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; int ret; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && trk->track_duration < pkt->dts && (trk->entry == 0 || !trk->last_sample_is_subtitle_end)) { ret = mov_write_subtitle_end_packet(s, i, trk->track_duration); if (ret < 0) return ret; trk->last_sample_is_subtitle_end = 1; } } if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) { AVPacket *opkt = pkt; int reshuffle_ret, ret; if (trk->is_unaligned_qt_rgb) { int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16; int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2; reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride); if (reshuffle_ret < 0) return reshuffle_ret; } else reshuffle_ret = 0; if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) { ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette); if (ret < 0) goto fail; if (ret) trk->pal_done++; } else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO && (trk->par->format == AV_PIX_FMT_GRAY8 || trk->par->format == AV_PIX_FMT_MONOBLACK)) { for (i = 0; i < pkt->size; i++) pkt->data[i] = ~pkt->data[i]; } if (reshuffle_ret) { ret = mov_write_single_packet(s, pkt); fail: if (reshuffle_ret) av_packet_free(&pkt); return ret; } } return mov_write_single_packet(s, pkt); } } // QuickTime chapters involve an additional text track with the chapter names // as samples, and a tref pointing from the other tracks to the chapter one. static int mov_create_chapter_track(AVFormatContext *s, int tracknum) { AVIOContext *pb; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[tracknum]; AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY }; int i, len; track->mode = mov->mode; track->tag = MKTAG('t','e','x','t'); track->timescale = MOV_TIMESCALE; track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_SUBTITLE; #if 0 // These properties are required to make QT recognize the chapter track uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, }; if (ff_alloc_extradata(track->par, sizeof(chapter_properties))) return AVERROR(ENOMEM); memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties)); #else if (avio_open_dyn_buf(&pb) >= 0) { int size; uint8_t *buf; /* Stub header (usually for Quicktime chapter track) */ // TextSampleEntry avio_wb32(pb, 0x01); // displayFlags avio_w8(pb, 0x00); // horizontal justification avio_w8(pb, 0x00); // vertical justification avio_w8(pb, 0x00); // bgColourRed avio_w8(pb, 0x00); // bgColourGreen avio_w8(pb, 0x00); // bgColourBlue avio_w8(pb, 0x00); // bgColourAlpha // BoxRecord avio_wb16(pb, 0x00); // defTextBoxTop avio_wb16(pb, 0x00); // defTextBoxLeft avio_wb16(pb, 0x00); // defTextBoxBottom avio_wb16(pb, 0x00); // defTextBoxRight // StyleRecord avio_wb16(pb, 0x00); // startChar avio_wb16(pb, 0x00); // endChar avio_wb16(pb, 0x01); // fontID avio_w8(pb, 0x00); // fontStyleFlags avio_w8(pb, 0x00); // fontSize avio_w8(pb, 0x00); // fgColourRed avio_w8(pb, 0x00); // fgColourGreen avio_w8(pb, 0x00); // fgColourBlue avio_w8(pb, 0x00); // fgColourAlpha // FontTableBox avio_wb32(pb, 0x0D); // box size ffio_wfourcc(pb, "ftab"); // box atom name avio_wb16(pb, 0x01); // entry count // FontRecord avio_wb16(pb, 0x01); // font ID avio_w8(pb, 0x00); // font name length if ((size = avio_close_dyn_buf(pb, &buf)) > 0) { track->par->extradata = buf; track->par->extradata_size = size; } else { av_freep(&buf); } } #endif for (i = 0; i < s->nb_chapters; i++) { AVChapter *c = s->chapters[i]; AVDictionaryEntry *t; int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE}); pkt.duration = end - pkt.dts; if ((t = av_dict_get(c->metadata, "title", NULL, 0))) { static const char encd[12] = { 0x00, 0x00, 0x00, 0x0C, 'e', 'n', 'c', 'd', 0x00, 0x00, 0x01, 0x00 }; len = strlen(t->value); pkt.size = len + 2 + 12; pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB16(pkt.data, len); memcpy(pkt.data + 2, t->value, len); memcpy(pkt.data + len + 2, encd, sizeof(encd)); ff_mov_write_packet(s, &pkt); av_freep(&pkt.data); } } return 0; } static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr) { int ret; /* compute the frame number */ ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s); return ret; } static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc) { int ret; MOVMuxContext *mov = s->priv_data; MOVTrack *track = &mov->tracks[index]; AVStream *src_st = s->streams[src_index]; AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4}; AVRational rate = find_fps(s, src_st); /* tmcd track based on video stream */ track->mode = mov->mode; track->tag = MKTAG('t','m','c','d'); track->src_track = src_index; track->timescale = mov->tracks[src_index].timescale; if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME) track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME; /* set st to src_st for metadata access*/ track->st = src_st; /* encode context: tmcd data stream */ track->par = avcodec_parameters_alloc(); if (!track->par) return AVERROR(ENOMEM); track->par->codec_type = AVMEDIA_TYPE_DATA; track->par->codec_tag = track->tag; track->st->avg_frame_rate = av_inv_q(rate); /* the tmcd track just contains one packet with the frame number */ pkt.data = av_malloc(pkt.size); if (!pkt.data) return AVERROR(ENOMEM); AV_WB32(pkt.data, tc.start); ret = ff_mov_write_packet(s, &pkt); av_free(pkt.data); return ret; } /* * st->disposition controls the "enabled" flag in the tkhd tag. * QuickTime will not play a track if it is not enabled. So make sure * that one track of each type (audio, video, subtitle) is enabled. * * Subtitles are special. For audio and video, setting "enabled" also * makes the track "default" (i.e. it is rendered when played). For * subtitles, an "enabled" subtitle is not rendered by default, but * if no subtitle is enabled, the subtitle menu in QuickTime will be * empty! */ static void enable_tracks(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; int enabled[AVMEDIA_TYPE_NB]; int first[AVMEDIA_TYPE_NB]; for (i = 0; i < AVMEDIA_TYPE_NB; i++) { enabled[i] = 0; first[i] = -1; } for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN || st->codecpar->codec_type >= AVMEDIA_TYPE_NB || is_cover_image(st)) continue; if (first[st->codecpar->codec_type] < 0) first[st->codecpar->codec_type] = i; if (st->disposition & AV_DISPOSITION_DEFAULT) { mov->tracks[i].flags |= MOV_TRACK_ENABLED; enabled[st->codecpar->codec_type]++; } } for (i = 0; i < AVMEDIA_TYPE_NB; i++) { switch (i) { case AVMEDIA_TYPE_VIDEO: case AVMEDIA_TYPE_AUDIO: case AVMEDIA_TYPE_SUBTITLE: if (enabled[i] > 1) mov->per_stream_grouping = 1; if (!enabled[i] && first[i] >= 0) mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED; break; } } } static void mov_free(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; int i; if (mov->chapter_track) { if (mov->tracks[mov->chapter_track].par) av_freep(&mov->tracks[mov->chapter_track].par->extradata); av_freep(&mov->tracks[mov->chapter_track].par); } for (i = 0; i < mov->nb_streams; i++) { if (mov->tracks[i].tag == MKTAG('r','t','p',' ')) ff_mov_close_hinting(&mov->tracks[i]); else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd) av_freep(&mov->tracks[i].par); av_freep(&mov->tracks[i].cluster); av_freep(&mov->tracks[i].frag_info); av_packet_unref(&mov->tracks[i].cover_image); if (mov->tracks[i].vos_len) av_freep(&mov->tracks[i].vos_data); ff_mov_cenc_free(&mov->tracks[i].cenc); } av_freep(&mov->tracks); } static uint32_t rgb_to_yuv(uint32_t rgb) { uint8_t r, g, b; int y, cb, cr; r = (rgb >> 16) & 0xFF; g = (rgb >> 8) & 0xFF; b = (rgb ) & 0xFF; y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000); cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000); cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000); return (y << 16) | (cr << 8) | cb; } static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track, AVStream *st) { int i, width = 720, height = 480; int have_palette = 0, have_size = 0; uint32_t palette[16]; char *cur = st->codecpar->extradata; while (cur && *cur) { if (strncmp("palette:", cur, 8) == 0) { int i, count; count = sscanf(cur + 8, "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", " "%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"", &palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3], &palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7], &palette[ 8], &palette[ 9], &palette[10], &palette[11], &palette[12], &palette[13], &palette[14], &palette[15]); for (i = 0; i < count; i++) { palette[i] = rgb_to_yuv(palette[i]); } have_palette = 1; } else if (!strncmp("size:", cur, 5)) { sscanf(cur + 5, "%dx%d", &width, &height); have_size = 1; } if (have_palette && have_size) break; cur += strcspn(cur, "\n\r"); cur += strspn(cur, "\n\r"); } if (have_palette) { track->vos_data = av_malloc(16*4); if (!track->vos_data) return AVERROR(ENOMEM); for (i = 0; i < 16; i++) { AV_WB32(track->vos_data + i * 4, palette[i]); } track->vos_len = 16 * 4; } st->codecpar->width = width; st->codecpar->height = track->height = height; return 0; } static int mov_init(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret; mov->fc = s; /* Default mode == MP4 */ mov->mode = MODE_MP4; if (s->oformat) { if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP; else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2; else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV; else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP; else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD; else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM; else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V; } if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV; /* Set the FRAGMENT flag if any of the fragmentation methods are * enabled. */ if (mov->max_fragment_duration || mov->max_fragment_size || mov->flags & (FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) mov->flags |= FF_MOV_FLAG_FRAGMENT; /* Set other implicit flags immediately */ if (mov->mode == MODE_ISM) mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF | FF_MOV_FLAG_FRAGMENT; if (mov->flags & FF_MOV_FLAG_DASH) mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_DEFAULT_BASE_MOOF; if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) { av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n"); s->flags &= ~AVFMT_FLAG_AUTO_BSF; } if (mov->flags & FF_MOV_FLAG_FASTSTART) { mov->reserved_moov_size = -1; } if (mov->use_editlist < 0) { mov->use_editlist = 1; if (mov->flags & FF_MOV_FLAG_FRAGMENT && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { // If we can avoid needing an edit list by shifting the // tracks, prefer that over (trying to) write edit lists // in fragmented output. if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO || s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) mov->use_editlist = 0; } } if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist) av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n"); if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO) s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO; /* Clear the omit_tfhd_offset flag if default_base_moof is set; * if the latter is set that's enough and omit_tfhd_offset doesn't * add anything extra on top of that. */ if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET; if (mov->frag_interleave && mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) { av_log(s, AV_LOG_ERROR, "Sample interleaving in fragments is mutually exclusive with " "omit_tfhd_offset and separate_moof\n"); return AVERROR(EINVAL); } /* Non-seekable output is ok if using fragmentation. If ism_lookahead * is enabled, we don't support non-seekable output at all. */ if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && (!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) { av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n"); return AVERROR(EINVAL); } mov->nb_streams = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) mov->chapter_track = mov->nb_streams++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) mov->nb_streams++; } if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4) || mov->write_tmcd == 1) { /* +1 tmcd track for each video stream with a timecode */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; AVDictionaryEntry *t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && (t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) { AVTimecode tc; ret = mov_check_timecode_track(s, &tc, i, t->value); if (ret >= 0) mov->nb_meta_tmcd++; } } /* check if there is already a tmcd track to remux */ if (mov->nb_meta_tmcd) { for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) { av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track " "so timecode metadata are now ignored\n"); mov->nb_meta_tmcd = 0; } } } mov->nb_streams += mov->nb_meta_tmcd; } // Reserve an extra stream for chapters for the case where chapters // are written in the trailer mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks)); if (!mov->tracks) return AVERROR(ENOMEM); if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) { if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) { mov->encryption_scheme = MOV_ENC_CENC_AES_CTR; if (mov->encryption_key_len != AES_CTR_KEY_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n", mov->encryption_key_len, AES_CTR_KEY_SIZE); return AVERROR(EINVAL); } if (mov->encryption_kid_len != CENC_KID_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n", mov->encryption_kid_len, CENC_KID_SIZE); return AVERROR(EINVAL); } } else { av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n", mov->encryption_scheme_str); return AVERROR(EINVAL); } } for (i = 0; i < s->nb_streams; i++) { AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0); track->st = st; track->par = st->codecpar; track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV); if (track->language < 0) track->language = 0; track->mode = mov->mode; track->tag = mov_find_codec_tag(s, track); if (!track->tag) { av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, " "codec not currently supported in container\n", avcodec_get_name(st->codecpar->codec_id), i); return AVERROR(EINVAL); } /* If hinting of this track is enabled by a later hint track, * this is updated. */ track->hint_track = -1; track->start_dts = AV_NOPTS_VALUE; track->start_cts = AV_NOPTS_VALUE; track->end_pts = AV_NOPTS_VALUE; track->dts_shift = AV_NOPTS_VALUE; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') || track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') || track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) { if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) { av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n"); return AVERROR(EINVAL); } track->height = track->tag >> 24 == 'n' ? 486 : 576; } if (mov->video_track_timescale) { track->timescale = mov->video_track_timescale; } else { track->timescale = st->time_base.den; while(track->timescale < 10000) track->timescale *= 2; } if (st->codecpar->width > 65535 || st->codecpar->height > 65535) { av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height); return AVERROR(EINVAL); } if (track->mode == MODE_MOV && track->timescale > 100000) av_log(s, AV_LOG_WARNING, "WARNING codec timebase is very high. If duration is too long,\n" "file may not be playable by quicktime. Specify a shorter timebase\n" "or choose different container.\n"); if (track->mode == MODE_MOV && track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->tag == MKTAG('r','a','w',' ')) { enum AVPixelFormat pix_fmt = track->par->format; if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1) pix_fmt = AV_PIX_FMT_MONOWHITE; track->is_unaligned_qt_rgb = pix_fmt == AV_PIX_FMT_RGB24 || pix_fmt == AV_PIX_FMT_BGR24 || pix_fmt == AV_PIX_FMT_PAL8 || pix_fmt == AV_PIX_FMT_GRAY8 || pix_fmt == AV_PIX_FMT_MONOWHITE || pix_fmt == AV_PIX_FMT_MONOBLACK; } if (track->par->codec_id == AV_CODEC_ID_VP9) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n"); return AVERROR(EINVAL); } } else if (track->par->codec_id == AV_CODEC_ID_AV1) { /* spec is not finished, so forbid for now */ av_log(s, AV_LOG_ERROR, "AV1 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } else if (track->par->codec_id == AV_CODEC_ID_VP8) { /* altref frames handling is not defined in the spec as of version v1.0, * so just forbid muxing VP8 streams altogether until a new version does */ av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n"); return AVERROR_PATCHWELCOME; } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { track->timescale = st->codecpar->sample_rate; if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) { av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i); track->audio_vbr = 1; }else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV || st->codecpar->codec_id == AV_CODEC_ID_ILBC){ if (!st->codecpar->block_align) { av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i); return AVERROR(EINVAL); } track->sample_size = st->codecpar->block_align; }else if (st->codecpar->frame_size > 1){ /* assume compressed audio */ track->audio_vbr = 1; }else{ track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels; } if (st->codecpar->codec_id == AV_CODEC_ID_ILBC || st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) { track->audio_vbr = 1; } if (track->mode != MODE_MOV && track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) { if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) { av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n", i, track->par->sample_rate); return AVERROR(EINVAL); } else { av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n", i, track->par->sample_rate); } } if (track->par->codec_id == AV_CODEC_ID_FLAC || track->par->codec_id == AV_CODEC_ID_OPUS) { if (track->mode != MODE_MP4) { av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id)); return AVERROR(EINVAL); } if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) { av_log(s, AV_LOG_ERROR, "%s in MP4 support is experimental, add " "'-strict %d' if you want to use it.\n", avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL); return AVERROR_EXPERIMENTAL; } } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { track->timescale = st->time_base.den; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { track->timescale = st->time_base.den; } else { track->timescale = MOV_TIMESCALE; } if (!track->height) track->height = st->codecpar->height; /* The ism specific timescale isn't mandatory, but is assumed by * some tools, such as mp4split. */ if (mov->mode == MODE_ISM) track->timescale = 10000000; avpriv_set_pts_info(st, 64, 1, track->timescale); if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) { ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key, track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT); if (ret) return ret; } } enable_tracks(s); return 0; } static int mov_write_header(AVFormatContext *s) { AVIOContext *pb = s->pb; MOVMuxContext *mov = s->priv_data; AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0); int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams; if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) nb_tracks++; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { hint_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) if (rtp_hinting_needed(s->streams[i])) nb_tracks++; } if (mov->mode == MODE_MOV || mov->mode == MODE_MP4) tmcd_track = nb_tracks; for (i = 0; i < s->nb_streams; i++) { int j; AVStream *st= s->streams[i]; MOVTrack *track= &mov->tracks[i]; /* copy extradata if it exists */ if (st->codecpar->extradata_size) { if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) mov_create_dvd_sub_decoder_specific_info(track, st); else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) { track->vos_len = st->codecpar->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) { return AVERROR(ENOMEM); } memcpy(track->vos_data, st->codecpar->extradata, track->vos_len); } } if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || track->par->channel_layout != AV_CH_LAYOUT_MONO) continue; for (j = 0; j < s->nb_streams; j++) { AVStream *stj= s->streams[j]; MOVTrack *trackj= &mov->tracks[j]; if (j == i) continue; if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || trackj->par->channel_layout != AV_CH_LAYOUT_MONO || trackj->language != track->language || trackj->tag != track->tag ) continue; track->multichannel_as_mono++; } } if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_identification(pb, s)) < 0) return ret; } if (mov->reserved_moov_size){ mov->reserved_header_pos = avio_tell(pb); if (mov->reserved_moov_size > 0) avio_skip(pb, mov->reserved_moov_size); } if (mov->flags & FF_MOV_FLAG_FRAGMENT) { /* If no fragmentation options have been set, set a default. */ if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME | FF_MOV_FLAG_FRAG_CUSTOM | FF_MOV_FLAG_FRAG_EVERY_FRAME)) && !mov->max_fragment_duration && !mov->max_fragment_size) mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME; } else { if (mov->flags & FF_MOV_FLAG_FASTSTART) mov->reserved_header_pos = avio_tell(pb); mov_write_mdat_tag(pb, mov); } ff_parse_creation_time_metadata(s, &mov->time, 1); if (mov->time) mov->time += 0x7C25B080; // 1970 based -> 1904 based if (mov->chapter_track) if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0) return ret; if (mov->flags & FF_MOV_FLAG_RTP_HINT) { for (i = 0; i < s->nb_streams; i++) { if (rtp_hinting_needed(s->streams[i])) { if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0) return ret; hint_track++; } } } if (mov->nb_meta_tmcd) { /* Initialize the tmcd tracks */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; t = global_tcr; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { AVTimecode tc; if (!t) t = av_dict_get(st->metadata, "timecode", NULL, 0); if (!t) continue; if (mov_check_timecode_track(s, &tc, i, t->value) < 0) continue; if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0) return ret; tmcd_track++; } } } avio_flush(pb); if (mov->flags & FF_MOV_FLAG_ISML) mov_write_isml_manifest(pb, mov, s); if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && !(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) { if ((ret = mov_write_moov_tag(pb, mov, s)) < 0) return ret; avio_flush(pb); mov->moov_written = 1; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) mov->reserved_header_pos = avio_tell(pb); } return 0; } static int get_moov_size(AVFormatContext *s) { int ret; AVIOContext *moov_buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&moov_buf)) < 0) return ret; if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0) return ret; return ffio_close_null_buf(moov_buf); } static int get_sidx_size(AVFormatContext *s) { int ret; AVIOContext *buf; MOVMuxContext *mov = s->priv_data; if ((ret = ffio_open_null_buf(&buf)) < 0) return ret; mov_write_sidx_tags(buf, mov, -1, 0); return ffio_close_null_buf(buf); } /* * This function gets the moov size if moved to the top of the file: the chunk * offset table can switch between stco (32-bit entries) to co64 (64-bit * entries) when the moov is moved to the beginning, so the size of the moov * would change. It also updates the chunk offset tables. */ static int compute_moov_size(AVFormatContext *s) { int i, moov_size, moov_size2; MOVMuxContext *mov = s->priv_data; moov_size = get_moov_size(s); if (moov_size < 0) return moov_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size; moov_size2 = get_moov_size(s); if (moov_size2 < 0) return moov_size2; /* if the size changed, we just switched from stco to co64 and need to * update the offsets */ if (moov_size2 != moov_size) for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += moov_size2 - moov_size; return moov_size2; } static int compute_sidx_size(AVFormatContext *s) { int i, sidx_size; MOVMuxContext *mov = s->priv_data; sidx_size = get_sidx_size(s); if (sidx_size < 0) return sidx_size; for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset += sidx_size; return sidx_size; } static int shift_data(AVFormatContext *s) { int ret = 0, moov_size; MOVMuxContext *mov = s->priv_data; int64_t pos, pos_end = avio_tell(s->pb); uint8_t *buf, *read_buf[2]; int read_buf_id = 0; int read_size[2]; AVIOContext *read_pb; if (mov->flags & FF_MOV_FLAG_FRAGMENT) moov_size = compute_sidx_size(s); else moov_size = compute_moov_size(s); if (moov_size < 0) return moov_size; buf = av_malloc(moov_size * 2); if (!buf) return AVERROR(ENOMEM); read_buf[0] = buf; read_buf[1] = buf + moov_size; /* Shift the data: the AVIO context of the output can only be used for * writing, so we re-open the same output, but for reading. It also avoids * a read/seek/write/seek back and forth. */ avio_flush(s->pb); ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL); if (ret < 0) { av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for " "the second pass (faststart)\n", s->url); goto end; } /* mark the end of the shift to up to the last data we wrote, and get ready * for writing */ pos_end = avio_tell(s->pb); avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET); /* start reading at where the new moov will be placed */ avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET); pos = avio_tell(read_pb); #define READ_BLOCK do { \ read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \ read_buf_id ^= 1; \ } while (0) /* shift data by chunk of at most moov_size */ READ_BLOCK; do { int n; READ_BLOCK; n = read_size[read_buf_id]; if (n <= 0) break; avio_write(s->pb, read_buf[read_buf_id], n); pos += n; } while (pos < pos_end); ff_format_io_close(s, &read_pb); end: av_free(buf); return ret; } static int mov_write_trailer(AVFormatContext *s) { MOVMuxContext *mov = s->priv_data; AVIOContext *pb = s->pb; int res = 0; int i; int64_t moov_pos; if (mov->need_rewrite_extradata) { for (i = 0; i < s->nb_streams; i++) { MOVTrack *track = &mov->tracks[i]; AVCodecParameters *par = track->par; track->vos_len = par->extradata_size; track->vos_data = av_malloc(track->vos_len); if (!track->vos_data) return AVERROR(ENOMEM); memcpy(track->vos_data, par->extradata, track->vos_len); } mov->need_rewrite_extradata = 0; } /* * Before actually writing the trailer, make sure that there are no * dangling subtitles, that need a terminating sample. */ for (i = 0; i < mov->nb_streams; i++) { MOVTrack *trk = &mov->tracks[i]; if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT && !trk->last_sample_is_subtitle_end) { mov_write_subtitle_end_packet(s, i, trk->track_duration); trk->last_sample_is_subtitle_end = 1; } } // If there were no chapters when the header was written, but there // are chapters now, write them in the trailer. This only works // when we are not doing fragments. if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) { if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) { mov->chapter_track = mov->nb_streams++; if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0) return res; } } if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) { moov_pos = avio_tell(pb); /* Write size of mdat tag */ if (mov->mdat_size + 8 <= UINT32_MAX) { avio_seek(pb, mov->mdat_pos, SEEK_SET); avio_wb32(pb, mov->mdat_size + 8); } else { /* overwrite 'wide' placeholder atom */ avio_seek(pb, mov->mdat_pos - 8, SEEK_SET); /* special value: real atom size will be 64 bit value after * tag field */ avio_wb32(pb, 1); ffio_wfourcc(pb, "mdat"); avio_wb64(pb, mov->mdat_size + 16); } avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET); if (mov->flags & FF_MOV_FLAG_FASTSTART) { av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n"); res = shift_data(s); if (res < 0) return res; avio_seek(pb, mov->reserved_header_pos, SEEK_SET); if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } else if (mov->reserved_moov_size > 0) { int64_t size; if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos); if (size < 8){ av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size); return AVERROR(EINVAL); } avio_wb32(pb, size); ffio_wfourcc(pb, "free"); ffio_fill(pb, 0, size - 8); avio_seek(pb, moov_pos, SEEK_SET); } else { if ((res = mov_write_moov_tag(pb, mov, s)) < 0) return res; } res = 0; } else { mov_auto_flush_fragment(s, 1); for (i = 0; i < mov->nb_streams; i++) mov->tracks[i].data_offset = 0; if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) { int64_t end; av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n"); res = shift_data(s); if (res < 0) return res; end = avio_tell(pb); avio_seek(pb, mov->reserved_header_pos, SEEK_SET); mov_write_sidx_tags(pb, mov, -1, 0); avio_seek(pb, end, SEEK_SET); avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) { avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER); mov_write_mfra_tag(pb, mov); } } return res; } static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt) { int ret = 1; AVStream *st = s->streams[pkt->stream_index]; if (st->codecpar->codec_id == AV_CODEC_ID_AAC) { if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL); } else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) { ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL); } return ret; } static const AVCodecTag codec_3gp_tags[] = { { AV_CODEC_ID_H263, MKTAG('s','2','6','3') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') }, { AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_NONE, 0 }, }; const AVCodecTag codec_mp4_tags[] = { { AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') }, { AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') }, { AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') }, { AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') }, { AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') }, { AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') }, { AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') }, { AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') }, { AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') }, { AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') }, { AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') }, { AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') }, { AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') }, { AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') }, { AV_CODEC_ID_NONE , 0 }, }; const AVCodecTag codec_ism_tags[] = { { AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') }, { AV_CODEC_ID_NONE , 0 }, }; static const AVCodecTag codec_ipod_tags[] = { { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') }, { AV_CODEC_ID_AC3, MKTAG('a','c','-','3') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') }, { AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') }, { AV_CODEC_ID_NONE, 0 }, }; static const AVCodecTag codec_f4v_tags[] = { { AV_CODEC_ID_MP3, MKTAG('.','m','p','3') }, { AV_CODEC_ID_AAC, MKTAG('m','p','4','a') }, { AV_CODEC_ID_H264, MKTAG('a','v','c','1') }, { AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') }, { AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') }, { AV_CODEC_ID_NONE, 0 }, }; #if CONFIG_MOV_MUXER MOV_CLASS(mov) AVOutputFormat ff_mov_muxer = { .name = "mov", .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"), .extensions = "mov", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mov_muxer_class, }; #endif #if CONFIG_TGP_MUXER MOV_CLASS(tgp) AVOutputFormat ff_tgp_muxer = { .name = "3gp", .long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"), .extensions = "3gp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tgp_muxer_class, }; #endif #if CONFIG_MP4_MUXER MOV_CLASS(mp4) AVOutputFormat ff_mp4_muxer = { .name = "mp4", .long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "mp4", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &mp4_muxer_class, }; #endif #if CONFIG_PSP_MUXER MOV_CLASS(psp) AVOutputFormat ff_psp_muxer = { .name = "psp", .long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"), .extensions = "mp4,psp", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = CONFIG_LIBX264_ENCODER ? AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &psp_muxer_class, }; #endif #if CONFIG_TG2_MUXER MOV_CLASS(tg2) AVOutputFormat ff_tg2_muxer = { .name = "3g2", .long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"), .extensions = "3g2", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AMR_NB, .video_codec = AV_CODEC_ID_H263, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &tg2_muxer_class, }; #endif #if CONFIG_IPOD_MUXER MOV_CLASS(ipod) AVOutputFormat ff_ipod_muxer = { .name = "ipod", .long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"), .mime_type = "video/mp4", .extensions = "m4v,m4a,m4b", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ipod_muxer_class, }; #endif #if CONFIG_ISMV_MUXER MOV_CLASS(ismv) AVOutputFormat ff_ismv_muxer = { .name = "ismv", .long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"), .mime_type = "video/mp4", .extensions = "ismv,isma", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE, .codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, codec_ism_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &ismv_muxer_class, }; #endif #if CONFIG_F4V_MUXER MOV_CLASS(f4v) AVOutputFormat ff_f4v_muxer = { .name = "f4v", .long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"), .mime_type = "application/f4v", .extensions = "f4v", .priv_data_size = sizeof(MOVMuxContext), .audio_codec = AV_CODEC_ID_AAC, .video_codec = AV_CODEC_ID_H264, .init = mov_init, .write_header = mov_write_header, .write_packet = mov_write_packet, .write_trailer = mov_write_trailer, .deinit = mov_free, .flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH, .codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 }, .check_bitstream = mov_check_bitstream, .priv_class = &f4v_muxer_class, }; #endif
./CrossVul/dataset_final_sorted/CWE-369/c/bad_258_0
crossvul-cpp_data_good_1008_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF EEEEE AAA TTTTT U U RRRR EEEEE % % F E A A T U U R R E % % FFF EEE AAAAA T U U RRRR EEE % % F E A A T U U R R E % % F EEEEE A A T UUU R R EEEEE % % % % % % MagickCore Image Feature Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 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://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/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/feature.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/image-private.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/morphology-private.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/random_.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/timer.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C a n n y E d g e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CannyEdgeImage() uses a multi-stage algorithm to detect a wide range of % edges in images. % % The format of the CannyEdgeImage method is: % % Image *CannyEdgeImage(const Image *image,const double radius, % const double sigma,const double lower_percent, % const double upper_percent,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the gaussian smoothing filter. % % o sigma: the sigma of the gaussian smoothing filter. % % o lower_percent: percentage of edge pixels in the lower threshold. % % o upper_percent: percentage of edge pixels in the upper threshold. % % o exception: return any errors or warnings in this structure. % */ typedef struct _CannyInfo { double magnitude, intensity; int orientation; ssize_t x, y; } CannyInfo; static inline MagickBooleanType IsAuthenticPixel(const Image *image, const ssize_t x,const ssize_t y) { if ((x < 0) || (x >= (ssize_t) image->columns)) return(MagickFalse); if ((y < 0) || (y >= (ssize_t) image->rows)) return(MagickFalse); return(MagickTrue); } static MagickBooleanType TraceEdges(Image *edge_image,CacheView *edge_view, MatrixInfo *canny_cache,const ssize_t x,const ssize_t y, const double lower_threshold,ExceptionInfo *exception) { CannyInfo edge, pixel; MagickBooleanType status; register Quantum *q; register ssize_t i; q=GetCacheViewAuthenticPixels(edge_view,x,y,1,1,exception); if (q == (Quantum *) NULL) return(MagickFalse); *q=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); if (GetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); edge.x=x; edge.y=y; if (SetMatrixElement(canny_cache,0,0,&edge) == MagickFalse) return(MagickFalse); for (i=1; i != 0; ) { ssize_t v; i--; status=GetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); for (v=(-1); v <= 1; v++) { ssize_t u; for (u=(-1); u <= 1; u++) { if ((u == 0) && (v == 0)) continue; if (IsAuthenticPixel(edge_image,edge.x+u,edge.y+v) == MagickFalse) continue; /* Not an edge if gradient value is below the lower threshold. */ q=GetCacheViewAuthenticPixels(edge_view,edge.x+u,edge.y+v,1,1, exception); if (q == (Quantum *) NULL) return(MagickFalse); status=GetMatrixElement(canny_cache,edge.x+u,edge.y+v,&pixel); if (status == MagickFalse) return(MagickFalse); if ((GetPixelIntensity(edge_image,q) == 0.0) && (pixel.intensity >= lower_threshold)) { *q=QuantumRange; status=SyncCacheViewAuthenticPixels(edge_view,exception); if (status == MagickFalse) return(MagickFalse); edge.x+=u; edge.y+=v; status=SetMatrixElement(canny_cache,i,0,&edge); if (status == MagickFalse) return(MagickFalse); i++; } } } } return(MagickTrue); } MagickExport Image *CannyEdgeImage(const Image *image,const double radius, const double sigma,const double lower_percent,const double upper_percent, ExceptionInfo *exception) { #define CannyEdgeImageTag "CannyEdge/Image" CacheView *edge_view; CannyInfo element; char geometry[MagickPathExtent]; double lower_threshold, max, min, upper_threshold; Image *edge_image; KernelInfo *kernel_info; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *canny_cache; ssize_t y; assert(image != (const 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); /* Filter out noise. */ (void) FormatLocaleString(geometry,MagickPathExtent, "blur:%.20gx%.20g;blur:%.20gx%.20g+90",radius,sigma,radius,sigma); kernel_info=AcquireKernelInfo(geometry,exception); if (kernel_info == (KernelInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); edge_image=MorphologyImage(image,ConvolveMorphology,1,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); if (edge_image == (Image *) NULL) return((Image *) NULL); if (TransformImageColorspace(edge_image,GRAYColorspace,exception) == MagickFalse) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } (void) SetImageAlphaChannel(edge_image,OffAlphaChannel,exception); /* Find the intensity gradient of the image. */ canny_cache=AcquireMatrixInfo(edge_image->columns,edge_image->rows, sizeof(CannyInfo),exception); if (canny_cache == (MatrixInfo *) NULL) { edge_image=DestroyImage(edge_image); return((Image *) NULL); } status=MagickTrue; edge_view=AcquireVirtualCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(edge_view,0,y,edge_image->columns+1,2, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; double dx, dy; register const Quantum *magick_restrict kernel_pixels; ssize_t v; static double Gx[2][2] = { { -1.0, +1.0 }, { -1.0, +1.0 } }, Gy[2][2] = { { +1.0, +1.0 }, { -1.0, -1.0 } }; (void) memset(&pixel,0,sizeof(pixel)); dx=0.0; dy=0.0; kernel_pixels=p; for (v=0; v < 2; v++) { ssize_t u; for (u=0; u < 2; u++) { double intensity; intensity=GetPixelIntensity(edge_image,kernel_pixels+u); dx+=0.5*Gx[v][u]*intensity; dy+=0.5*Gy[v][u]*intensity; } kernel_pixels+=edge_image->columns+1; } pixel.magnitude=hypot(dx,dy); pixel.orientation=0; if (fabs(dx) > MagickEpsilon) { double slope; slope=dy/dx; if (slope < 0.0) { if (slope < -2.41421356237) pixel.orientation=0; else if (slope < -0.414213562373) pixel.orientation=1; else pixel.orientation=2; } else { if (slope > 2.41421356237) pixel.orientation=0; else if (slope > 0.414213562373) pixel.orientation=3; else pixel.orientation=2; } } if (SetMatrixElement(canny_cache,x,y,&pixel) == MagickFalse) continue; p+=GetPixelChannels(edge_image); } } edge_view=DestroyCacheView(edge_view); /* Non-maxima suppression, remove pixels that are not considered to be part of an edge. */ progress=0; (void) GetMatrixElement(canny_cache,0,0,&element); max=element.intensity; min=element.intensity; edge_view=AcquireAuthenticCacheView(edge_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(edge_image,edge_image,edge_image->rows,1) #endif for (y=0; y < (ssize_t) edge_image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(edge_view,0,y,edge_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo alpha_pixel, beta_pixel, pixel; (void) GetMatrixElement(canny_cache,x,y,&pixel); switch (pixel.orientation) { case 0: default: { /* 0 degrees, north and south. */ (void) GetMatrixElement(canny_cache,x,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x,y+1,&beta_pixel); break; } case 1: { /* 45 degrees, northwest and southeast. */ (void) GetMatrixElement(canny_cache,x-1,y-1,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y+1,&beta_pixel); break; } case 2: { /* 90 degrees, east and west. */ (void) GetMatrixElement(canny_cache,x-1,y,&alpha_pixel); (void) GetMatrixElement(canny_cache,x+1,y,&beta_pixel); break; } case 3: { /* 135 degrees, northeast and southwest. */ (void) GetMatrixElement(canny_cache,x+1,y-1,&beta_pixel); (void) GetMatrixElement(canny_cache,x-1,y+1,&alpha_pixel); break; } } pixel.intensity=pixel.magnitude; if ((pixel.magnitude < alpha_pixel.magnitude) || (pixel.magnitude < beta_pixel.magnitude)) pixel.intensity=0; (void) SetMatrixElement(canny_cache,x,y,&pixel); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CannyEdgeImage) #endif { if (pixel.intensity < min) min=pixel.intensity; if (pixel.intensity > max) max=pixel.intensity; } *q=0; q+=GetPixelChannels(edge_image); } if (SyncCacheViewAuthenticPixels(edge_view,exception) == MagickFalse) status=MagickFalse; } edge_view=DestroyCacheView(edge_view); /* Estimate hysteresis threshold. */ lower_threshold=lower_percent*(max-min)+min; upper_threshold=upper_percent*(max-min)+min; /* Hysteresis threshold. */ edge_view=AcquireAuthenticCacheView(edge_image,exception); for (y=0; y < (ssize_t) edge_image->rows; y++) { register ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) edge_image->columns; x++) { CannyInfo pixel; register const Quantum *magick_restrict p; /* Edge if pixel gradient higher than upper threshold. */ p=GetCacheViewVirtualPixels(edge_view,x,y,1,1,exception); if (p == (const Quantum *) NULL) continue; status=GetMatrixElement(canny_cache,x,y,&pixel); if (status == MagickFalse) continue; if ((GetPixelIntensity(edge_image,p) == 0.0) && (pixel.intensity >= upper_threshold)) status=TraceEdges(edge_image,edge_view,canny_cache,x,y,lower_threshold, exception); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CannyEdgeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } edge_view=DestroyCacheView(edge_view); /* Free resources. */ canny_cache=DestroyMatrixInfo(canny_cache); return(edge_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e F e a t u r e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageFeatures() returns features for each channel in the image in % each of four directions (horizontal, vertical, left and right diagonals) % for the specified distance. The features include the angular second % moment, contrast, correlation, sum of squares: variance, inverse difference % moment, sum average, sum varience, sum entropy, entropy, difference variance,% difference entropy, information measures of correlation 1, information % measures of correlation 2, and maximum correlation coefficient. You can % access the red channel contrast, for example, like this: % % channel_features=GetImageFeatures(image,1,exception); % contrast=channel_features[RedPixelChannel].contrast[0]; % % Use MagickRelinquishMemory() to free the features buffer. % % The format of the GetImageFeatures method is: % % ChannelFeatures *GetImageFeatures(const Image *image, % const size_t distance,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o distance: the distance. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelFeatures *GetImageFeatures(const Image *image, const size_t distance,ExceptionInfo *exception) { typedef struct _ChannelStatistics { PixelInfo direction[4]; /* horizontal, vertical, left and right diagonals */ } ChannelStatistics; CacheView *image_view; ChannelFeatures *channel_features; ChannelStatistics **cooccurrence, correlation, *density_x, *density_xy, *density_y, entropy_x, entropy_xy, entropy_xy1, entropy_xy2, entropy_y, mean, **Q, *sum, sum_squares, variance; PixelPacket gray, *grays; MagickBooleanType status; register ssize_t i, r; size_t length; unsigned int number_grays; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns < (distance+1)) || (image->rows < (distance+1))) return((ChannelFeatures *) NULL); length=MaxPixelChannels+1UL; channel_features=(ChannelFeatures *) AcquireQuantumMemory(length, sizeof(*channel_features)); if (channel_features == (ChannelFeatures *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(channel_features,0,length* sizeof(*channel_features)); /* Form grays. */ grays=(PixelPacket *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*grays)); if (grays == (PixelPacket *) NULL) { channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } for (i=0; i <= (ssize_t) MaxMap; i++) { grays[i].red=(~0U); grays[i].green=(~0U); grays[i].blue=(~0U); grays[i].alpha=(~0U); grays[i].black=(~0U); } status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (r=0; r < (ssize_t) image->rows; r++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,r,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { grays[ScaleQuantumToMap(GetPixelRed(image,p))].red= ScaleQuantumToMap(GetPixelRed(image,p)); grays[ScaleQuantumToMap(GetPixelGreen(image,p))].green= ScaleQuantumToMap(GetPixelGreen(image,p)); grays[ScaleQuantumToMap(GetPixelBlue(image,p))].blue= ScaleQuantumToMap(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) grays[ScaleQuantumToMap(GetPixelBlack(image,p))].black= ScaleQuantumToMap(GetPixelBlack(image,p)); if (image->alpha_trait != UndefinedPixelTrait) grays[ScaleQuantumToMap(GetPixelAlpha(image,p))].alpha= ScaleQuantumToMap(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); return(channel_features); } (void) memset(&gray,0,sizeof(gray)); for (i=0; i <= (ssize_t) MaxMap; i++) { if (grays[i].red != ~0U) grays[gray.red++].red=grays[i].red; if (grays[i].green != ~0U) grays[gray.green++].green=grays[i].green; if (grays[i].blue != ~0U) grays[gray.blue++].blue=grays[i].blue; if (image->colorspace == CMYKColorspace) if (grays[i].black != ~0U) grays[gray.black++].black=grays[i].black; if (image->alpha_trait != UndefinedPixelTrait) if (grays[i].alpha != ~0U) grays[gray.alpha++].alpha=grays[i].alpha; } /* Allocate spatial dependence matrix. */ number_grays=gray.red; if (gray.green > number_grays) number_grays=gray.green; if (gray.blue > number_grays) number_grays=gray.blue; if (image->colorspace == CMYKColorspace) if (gray.black > number_grays) number_grays=gray.black; if (image->alpha_trait != UndefinedPixelTrait) if (gray.alpha > number_grays) number_grays=gray.alpha; cooccurrence=(ChannelStatistics **) AcquireQuantumMemory(number_grays, sizeof(*cooccurrence)); density_x=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_x)); density_xy=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_xy)); density_y=(ChannelStatistics *) AcquireQuantumMemory(2*(number_grays+1), sizeof(*density_y)); Q=(ChannelStatistics **) AcquireQuantumMemory(number_grays,sizeof(*Q)); sum=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(*sum)); if ((cooccurrence == (ChannelStatistics **) NULL) || (density_x == (ChannelStatistics *) NULL) || (density_xy == (ChannelStatistics *) NULL) || (density_y == (ChannelStatistics *) NULL) || (Q == (ChannelStatistics **) NULL) || (sum == (ChannelStatistics *) NULL)) { if (Q != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); } if (sum != (ChannelStatistics *) NULL) sum=(ChannelStatistics *) RelinquishMagickMemory(sum); if (density_y != (ChannelStatistics *) NULL) density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); if (density_xy != (ChannelStatistics *) NULL) density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); if (density_x != (ChannelStatistics *) NULL) density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); if (cooccurrence != (ChannelStatistics **) NULL) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory( cooccurrence); } grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } (void) memset(&correlation,0,sizeof(correlation)); (void) memset(density_x,0,2*(number_grays+1)*sizeof(*density_x)); (void) memset(density_xy,0,2*(number_grays+1)*sizeof(*density_xy)); (void) memset(density_y,0,2*(number_grays+1)*sizeof(*density_y)); (void) memset(&mean,0,sizeof(mean)); (void) memset(sum,0,number_grays*sizeof(*sum)); (void) memset(&sum_squares,0,sizeof(sum_squares)); (void) memset(density_xy,0,2*number_grays*sizeof(*density_xy)); (void) memset(&entropy_x,0,sizeof(entropy_x)); (void) memset(&entropy_xy,0,sizeof(entropy_xy)); (void) memset(&entropy_xy1,0,sizeof(entropy_xy1)); (void) memset(&entropy_xy2,0,sizeof(entropy_xy2)); (void) memset(&entropy_y,0,sizeof(entropy_y)); (void) memset(&variance,0,sizeof(variance)); for (i=0; i < (ssize_t) number_grays; i++) { cooccurrence[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays, sizeof(**cooccurrence)); Q[i]=(ChannelStatistics *) AcquireQuantumMemory(number_grays,sizeof(**Q)); if ((cooccurrence[i] == (ChannelStatistics *) NULL) || (Q[i] == (ChannelStatistics *) NULL)) break; (void) memset(cooccurrence[i],0,number_grays* sizeof(**cooccurrence)); (void) memset(Q[i],0,number_grays*sizeof(**Q)); } if (i < (ssize_t) number_grays) { for (i--; i >= 0; i--) { if (Q[i] != (ChannelStatistics *) NULL) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); if (cooccurrence[i] != (ChannelStatistics *) NULL) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); } Q=(ChannelStatistics **) RelinquishMagickMemory(Q); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); sum=(ChannelStatistics *) RelinquishMagickMemory(sum); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); grays=(PixelPacket *) RelinquishMagickMemory(grays); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Initialize spatial dependence matrix. */ status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); for (r=0; r < (ssize_t) image->rows; r++) { register const Quantum *magick_restrict p; register ssize_t x; ssize_t offset, u, v; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-(ssize_t) distance,r,image->columns+ 2*distance,distance+2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } p+=distance*GetPixelChannels(image);; for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < 4; i++) { switch (i) { case 0: default: { /* Horizontal adjacency. */ offset=(ssize_t) distance; break; } case 1: { /* Vertical adjacency. */ offset=(ssize_t) (image->columns+2*distance); break; } case 2: { /* Right diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)-distance); break; } case 3: { /* Left diagonal adjacency. */ offset=(ssize_t) ((image->columns+2*distance)+distance); break; } } u=0; v=0; while (grays[u].red != ScaleQuantumToMap(GetPixelRed(image,p))) u++; while (grays[v].red != ScaleQuantumToMap(GetPixelRed(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].red++; cooccurrence[v][u].direction[i].red++; u=0; v=0; while (grays[u].green != ScaleQuantumToMap(GetPixelGreen(image,p))) u++; while (grays[v].green != ScaleQuantumToMap(GetPixelGreen(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].green++; cooccurrence[v][u].direction[i].green++; u=0; v=0; while (grays[u].blue != ScaleQuantumToMap(GetPixelBlue(image,p))) u++; while (grays[v].blue != ScaleQuantumToMap(GetPixelBlue(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].blue++; cooccurrence[v][u].direction[i].blue++; if (image->colorspace == CMYKColorspace) { u=0; v=0; while (grays[u].black != ScaleQuantumToMap(GetPixelBlack(image,p))) u++; while (grays[v].black != ScaleQuantumToMap(GetPixelBlack(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].black++; cooccurrence[v][u].direction[i].black++; } if (image->alpha_trait != UndefinedPixelTrait) { u=0; v=0; while (grays[u].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p))) u++; while (grays[v].alpha != ScaleQuantumToMap(GetPixelAlpha(image,p+offset*GetPixelChannels(image)))) v++; cooccurrence[u][v].direction[i].alpha++; cooccurrence[v][u].direction[i].alpha++; } } p+=GetPixelChannels(image); } } grays=(PixelPacket *) RelinquishMagickMemory(grays); image_view=DestroyCacheView(image_view); if (status == MagickFalse) { for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); channel_features=(ChannelFeatures *) RelinquishMagickMemory( channel_features); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(channel_features); } /* Normalize spatial dependence matrix. */ for (i=0; i < 4; i++) { double normalize; register ssize_t y; switch (i) { case 0: default: { /* Horizontal adjacency. */ normalize=2.0*image->rows*(image->columns-distance); break; } case 1: { /* Vertical adjacency. */ normalize=2.0*(image->rows-distance)*image->columns; break; } case 2: { /* Right diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } case 3: { /* Left diagonal adjacency. */ normalize=2.0*(image->rows-distance)*(image->columns-distance); break; } } normalize=PerceptibleReciprocal(normalize); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { cooccurrence[x][y].direction[i].red*=normalize; cooccurrence[x][y].direction[i].green*=normalize; cooccurrence[x][y].direction[i].blue*=normalize; if (image->colorspace == CMYKColorspace) cooccurrence[x][y].direction[i].black*=normalize; if (image->alpha_trait != UndefinedPixelTrait) cooccurrence[x][y].direction[i].alpha*=normalize; } } } /* Compute texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Angular second moment: measure of homogeneity of the image. */ channel_features[RedPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].red* cooccurrence[x][y].direction[i].red; channel_features[GreenPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].green* cooccurrence[x][y].direction[i].green; channel_features[BluePixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].blue* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].black* cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].angular_second_moment[i]+= cooccurrence[x][y].direction[i].alpha* cooccurrence[x][y].direction[i].alpha; /* Correlation: measure of linear-dependencies in the image. */ sum[y].direction[i].red+=cooccurrence[x][y].direction[i].red; sum[y].direction[i].green+=cooccurrence[x][y].direction[i].green; sum[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) sum[y].direction[i].black+=cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) sum[y].direction[i].alpha+=cooccurrence[x][y].direction[i].alpha; correlation.direction[i].red+=x*y*cooccurrence[x][y].direction[i].red; correlation.direction[i].green+=x*y* cooccurrence[x][y].direction[i].green; correlation.direction[i].blue+=x*y* cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) correlation.direction[i].black+=x*y* cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) correlation.direction[i].alpha+=x*y* cooccurrence[x][y].direction[i].alpha; /* Inverse Difference Moment. */ channel_features[RedPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].red/((y-x)*(y-x)+1); channel_features[GreenPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].green/((y-x)*(y-x)+1); channel_features[BluePixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].blue/((y-x)*(y-x)+1); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].black/((y-x)*(y-x)+1); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].inverse_difference_moment[i]+= cooccurrence[x][y].direction[i].alpha/((y-x)*(y-x)+1); /* Sum average. */ density_xy[y+x+2].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[y+x+2].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[y+x+2].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[y+x+2].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_xy[y+x+2].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; /* Entropy. */ channel_features[RedPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); channel_features[GreenPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); channel_features[BluePixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].black* MagickLog10(cooccurrence[x][y].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].entropy[i]-= cooccurrence[x][y].direction[i].alpha* MagickLog10(cooccurrence[x][y].direction[i].alpha); /* Information Measures of Correlation. */ density_x[x].direction[i].red+=cooccurrence[x][y].direction[i].red; density_x[x].direction[i].green+=cooccurrence[x][y].direction[i].green; density_x[x].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->alpha_trait != UndefinedPixelTrait) density_x[x].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; if (image->colorspace == CMYKColorspace) density_x[x].direction[i].black+= cooccurrence[x][y].direction[i].black; density_y[y].direction[i].red+=cooccurrence[x][y].direction[i].red; density_y[y].direction[i].green+=cooccurrence[x][y].direction[i].green; density_y[y].direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_y[y].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_y[y].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; } mean.direction[i].red+=y*sum[y].direction[i].red; sum_squares.direction[i].red+=y*y*sum[y].direction[i].red; mean.direction[i].green+=y*sum[y].direction[i].green; sum_squares.direction[i].green+=y*y*sum[y].direction[i].green; mean.direction[i].blue+=y*sum[y].direction[i].blue; sum_squares.direction[i].blue+=y*y*sum[y].direction[i].blue; if (image->colorspace == CMYKColorspace) { mean.direction[i].black+=y*sum[y].direction[i].black; sum_squares.direction[i].black+=y*y*sum[y].direction[i].black; } if (image->alpha_trait != UndefinedPixelTrait) { mean.direction[i].alpha+=y*sum[y].direction[i].alpha; sum_squares.direction[i].alpha+=y*y*sum[y].direction[i].alpha; } } /* Correlation: measure of linear-dependencies in the image. */ channel_features[RedPixelChannel].correlation[i]= (correlation.direction[i].red-mean.direction[i].red* mean.direction[i].red)/(sqrt(sum_squares.direction[i].red- (mean.direction[i].red*mean.direction[i].red))*sqrt( sum_squares.direction[i].red-(mean.direction[i].red* mean.direction[i].red))); channel_features[GreenPixelChannel].correlation[i]= (correlation.direction[i].green-mean.direction[i].green* mean.direction[i].green)/(sqrt(sum_squares.direction[i].green- (mean.direction[i].green*mean.direction[i].green))*sqrt( sum_squares.direction[i].green-(mean.direction[i].green* mean.direction[i].green))); channel_features[BluePixelChannel].correlation[i]= (correlation.direction[i].blue-mean.direction[i].blue* mean.direction[i].blue)/(sqrt(sum_squares.direction[i].blue- (mean.direction[i].blue*mean.direction[i].blue))*sqrt( sum_squares.direction[i].blue-(mean.direction[i].blue* mean.direction[i].blue))); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].correlation[i]= (correlation.direction[i].black-mean.direction[i].black* mean.direction[i].black)/(sqrt(sum_squares.direction[i].black- (mean.direction[i].black*mean.direction[i].black))*sqrt( sum_squares.direction[i].black-(mean.direction[i].black* mean.direction[i].black))); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].correlation[i]= (correlation.direction[i].alpha-mean.direction[i].alpha* mean.direction[i].alpha)/(sqrt(sum_squares.direction[i].alpha- (mean.direction[i].alpha*mean.direction[i].alpha))*sqrt( sum_squares.direction[i].alpha-(mean.direction[i].alpha* mean.direction[i].alpha))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=2; x < (ssize_t) (2*number_grays); x++) { /* Sum average. */ channel_features[RedPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].red; channel_features[GreenPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].green; channel_features[BluePixelChannel].sum_average[i]+= x*density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_average[i]+= x*density_xy[x].direction[i].alpha; /* Sum entropy. */ channel_features[RedPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BluePixelChannel].sum_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].black* MagickLog10(density_xy[x].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_entropy[i]-= density_xy[x].direction[i].alpha* MagickLog10(density_xy[x].direction[i].alpha); /* Sum variance. */ channel_features[RedPixelChannel].sum_variance[i]+= (x-channel_features[RedPixelChannel].sum_entropy[i])* (x-channel_features[RedPixelChannel].sum_entropy[i])* density_xy[x].direction[i].red; channel_features[GreenPixelChannel].sum_variance[i]+= (x-channel_features[GreenPixelChannel].sum_entropy[i])* (x-channel_features[GreenPixelChannel].sum_entropy[i])* density_xy[x].direction[i].green; channel_features[BluePixelChannel].sum_variance[i]+= (x-channel_features[BluePixelChannel].sum_entropy[i])* (x-channel_features[BluePixelChannel].sum_entropy[i])* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].sum_variance[i]+= (x-channel_features[BlackPixelChannel].sum_entropy[i])* (x-channel_features[BlackPixelChannel].sum_entropy[i])* density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].sum_variance[i]+= (x-channel_features[AlphaPixelChannel].sum_entropy[i])* (x-channel_features[AlphaPixelChannel].sum_entropy[i])* density_xy[x].direction[i].alpha; } } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t y; for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Sum of Squares: Variance */ variance.direction[i].red+=(y-mean.direction[i].red+1)* (y-mean.direction[i].red+1)*cooccurrence[x][y].direction[i].red; variance.direction[i].green+=(y-mean.direction[i].green+1)* (y-mean.direction[i].green+1)*cooccurrence[x][y].direction[i].green; variance.direction[i].blue+=(y-mean.direction[i].blue+1)* (y-mean.direction[i].blue+1)*cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].black+=(y-mean.direction[i].black+1)* (y-mean.direction[i].black+1)*cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) variance.direction[i].alpha+=(y-mean.direction[i].alpha+1)* (y-mean.direction[i].alpha+1)* cooccurrence[x][y].direction[i].alpha; /* Sum average / Difference Variance. */ density_xy[MagickAbsoluteValue(y-x)].direction[i].red+= cooccurrence[x][y].direction[i].red; density_xy[MagickAbsoluteValue(y-x)].direction[i].green+= cooccurrence[x][y].direction[i].green; density_xy[MagickAbsoluteValue(y-x)].direction[i].blue+= cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) density_xy[MagickAbsoluteValue(y-x)].direction[i].black+= cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) density_xy[MagickAbsoluteValue(y-x)].direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; /* Information Measures of Correlation. */ entropy_xy.direction[i].red-=cooccurrence[x][y].direction[i].red* MagickLog10(cooccurrence[x][y].direction[i].red); entropy_xy.direction[i].green-=cooccurrence[x][y].direction[i].green* MagickLog10(cooccurrence[x][y].direction[i].green); entropy_xy.direction[i].blue-=cooccurrence[x][y].direction[i].blue* MagickLog10(cooccurrence[x][y].direction[i].blue); if (image->colorspace == CMYKColorspace) entropy_xy.direction[i].black-=cooccurrence[x][y].direction[i].black* MagickLog10(cooccurrence[x][y].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy.direction[i].alpha-= cooccurrence[x][y].direction[i].alpha*MagickLog10( cooccurrence[x][y].direction[i].alpha); entropy_xy1.direction[i].red-=(cooccurrence[x][y].direction[i].red* MagickLog10(density_x[x].direction[i].red*density_y[y].direction[i].red)); entropy_xy1.direction[i].green-=(cooccurrence[x][y].direction[i].green* MagickLog10(density_x[x].direction[i].green* density_y[y].direction[i].green)); entropy_xy1.direction[i].blue-=(cooccurrence[x][y].direction[i].blue* MagickLog10(density_x[x].direction[i].blue*density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy1.direction[i].black-=( cooccurrence[x][y].direction[i].black*MagickLog10( density_x[x].direction[i].black*density_y[y].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy1.direction[i].alpha-=( cooccurrence[x][y].direction[i].alpha*MagickLog10( density_x[x].direction[i].alpha*density_y[y].direction[i].alpha)); entropy_xy2.direction[i].red-=(density_x[x].direction[i].red* density_y[y].direction[i].red*MagickLog10(density_x[x].direction[i].red* density_y[y].direction[i].red)); entropy_xy2.direction[i].green-=(density_x[x].direction[i].green* density_y[y].direction[i].green*MagickLog10(density_x[x].direction[i].green* density_y[y].direction[i].green)); entropy_xy2.direction[i].blue-=(density_x[x].direction[i].blue* density_y[y].direction[i].blue*MagickLog10(density_x[x].direction[i].blue* density_y[y].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_xy2.direction[i].black-=(density_x[x].direction[i].black* density_y[y].direction[i].black*MagickLog10( density_x[x].direction[i].black*density_y[y].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_xy2.direction[i].alpha-=(density_x[x].direction[i].alpha* density_y[y].direction[i].alpha*MagickLog10( density_x[x].direction[i].alpha*density_y[y].direction[i].alpha)); } } channel_features[RedPixelChannel].variance_sum_of_squares[i]= variance.direction[i].red; channel_features[GreenPixelChannel].variance_sum_of_squares[i]= variance.direction[i].green; channel_features[BluePixelChannel].variance_sum_of_squares[i]= variance.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].variance_sum_of_squares[i]= variance.direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].variance_sum_of_squares[i]= variance.direction[i].alpha; } /* Compute more texture features. */ (void) memset(&variance,0,sizeof(variance)); (void) memset(&sum_squares,0,sizeof(sum_squares)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Difference variance. */ variance.direction[i].red+=density_xy[x].direction[i].red; variance.direction[i].green+=density_xy[x].direction[i].green; variance.direction[i].blue+=density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) variance.direction[i].black+=density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) variance.direction[i].alpha+=density_xy[x].direction[i].alpha; sum_squares.direction[i].red+=density_xy[x].direction[i].red* density_xy[x].direction[i].red; sum_squares.direction[i].green+=density_xy[x].direction[i].green* density_xy[x].direction[i].green; sum_squares.direction[i].blue+=density_xy[x].direction[i].blue* density_xy[x].direction[i].blue; if (image->colorspace == CMYKColorspace) sum_squares.direction[i].black+=density_xy[x].direction[i].black* density_xy[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) sum_squares.direction[i].alpha+=density_xy[x].direction[i].alpha* density_xy[x].direction[i].alpha; /* Difference entropy. */ channel_features[RedPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].red* MagickLog10(density_xy[x].direction[i].red); channel_features[GreenPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].green* MagickLog10(density_xy[x].direction[i].green); channel_features[BluePixelChannel].difference_entropy[i]-= density_xy[x].direction[i].blue* MagickLog10(density_xy[x].direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].black* MagickLog10(density_xy[x].direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].difference_entropy[i]-= density_xy[x].direction[i].alpha* MagickLog10(density_xy[x].direction[i].alpha); /* Information Measures of Correlation. */ entropy_x.direction[i].red-=(density_x[x].direction[i].red* MagickLog10(density_x[x].direction[i].red)); entropy_x.direction[i].green-=(density_x[x].direction[i].green* MagickLog10(density_x[x].direction[i].green)); entropy_x.direction[i].blue-=(density_x[x].direction[i].blue* MagickLog10(density_x[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_x.direction[i].black-=(density_x[x].direction[i].black* MagickLog10(density_x[x].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_x.direction[i].alpha-=(density_x[x].direction[i].alpha* MagickLog10(density_x[x].direction[i].alpha)); entropy_y.direction[i].red-=(density_y[x].direction[i].red* MagickLog10(density_y[x].direction[i].red)); entropy_y.direction[i].green-=(density_y[x].direction[i].green* MagickLog10(density_y[x].direction[i].green)); entropy_y.direction[i].blue-=(density_y[x].direction[i].blue* MagickLog10(density_y[x].direction[i].blue)); if (image->colorspace == CMYKColorspace) entropy_y.direction[i].black-=(density_y[x].direction[i].black* MagickLog10(density_y[x].direction[i].black)); if (image->alpha_trait != UndefinedPixelTrait) entropy_y.direction[i].alpha-=(density_y[x].direction[i].alpha* MagickLog10(density_y[x].direction[i].alpha)); } /* Difference variance. */ channel_features[RedPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].red)- (variance.direction[i].red*variance.direction[i].red))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[GreenPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].green)- (variance.direction[i].green*variance.direction[i].green))/ ((double) number_grays*number_grays*number_grays*number_grays); channel_features[BluePixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].blue)- (variance.direction[i].blue*variance.direction[i].blue))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].black)- (variance.direction[i].black*variance.direction[i].black))/ ((double) number_grays*number_grays*number_grays*number_grays); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].difference_variance[i]= (((double) number_grays*number_grays*sum_squares.direction[i].alpha)- (variance.direction[i].alpha*variance.direction[i].alpha))/ ((double) number_grays*number_grays*number_grays*number_grays); /* Information Measures of Correlation. */ channel_features[RedPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].red-entropy_xy1.direction[i].red)/ (entropy_x.direction[i].red > entropy_y.direction[i].red ? entropy_x.direction[i].red : entropy_y.direction[i].red); channel_features[GreenPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].green-entropy_xy1.direction[i].green)/ (entropy_x.direction[i].green > entropy_y.direction[i].green ? entropy_x.direction[i].green : entropy_y.direction[i].green); channel_features[BluePixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].blue-entropy_xy1.direction[i].blue)/ (entropy_x.direction[i].blue > entropy_y.direction[i].blue ? entropy_x.direction[i].blue : entropy_y.direction[i].blue); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].black-entropy_xy1.direction[i].black)/ (entropy_x.direction[i].black > entropy_y.direction[i].black ? entropy_x.direction[i].black : entropy_y.direction[i].black); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].measure_of_correlation_1[i]= (entropy_xy.direction[i].alpha-entropy_xy1.direction[i].alpha)/ (entropy_x.direction[i].alpha > entropy_y.direction[i].alpha ? entropy_x.direction[i].alpha : entropy_y.direction[i].alpha); channel_features[RedPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].red- entropy_xy.direction[i].red))))); channel_features[GreenPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].green- entropy_xy.direction[i].green))))); channel_features[BluePixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].blue- entropy_xy.direction[i].blue))))); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].black- entropy_xy.direction[i].black))))); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].measure_of_correlation_2[i]= (sqrt(fabs(1.0-exp(-2.0*(double) (entropy_xy2.direction[i].alpha- entropy_xy.direction[i].alpha))))); } /* Compute more texture features. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,number_grays,1) #endif for (i=0; i < 4; i++) { ssize_t z; for (z=0; z < (ssize_t) number_grays; z++) { register ssize_t y; ChannelStatistics pixel; (void) memset(&pixel,0,sizeof(pixel)); for (y=0; y < (ssize_t) number_grays; y++) { register ssize_t x; for (x=0; x < (ssize_t) number_grays; x++) { /* Contrast: amount of local variations present in an image. */ if (((y-x) == z) || ((x-y) == z)) { pixel.direction[i].red+=cooccurrence[x][y].direction[i].red; pixel.direction[i].green+=cooccurrence[x][y].direction[i].green; pixel.direction[i].blue+=cooccurrence[x][y].direction[i].blue; if (image->colorspace == CMYKColorspace) pixel.direction[i].black+=cooccurrence[x][y].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) pixel.direction[i].alpha+= cooccurrence[x][y].direction[i].alpha; } /* Maximum Correlation Coefficient. */ Q[z][y].direction[i].red+=cooccurrence[z][x].direction[i].red* cooccurrence[y][x].direction[i].red/density_x[z].direction[i].red/ density_y[x].direction[i].red; Q[z][y].direction[i].green+=cooccurrence[z][x].direction[i].green* cooccurrence[y][x].direction[i].green/ density_x[z].direction[i].green/density_y[x].direction[i].red; Q[z][y].direction[i].blue+=cooccurrence[z][x].direction[i].blue* cooccurrence[y][x].direction[i].blue/density_x[z].direction[i].blue/ density_y[x].direction[i].blue; if (image->colorspace == CMYKColorspace) Q[z][y].direction[i].black+=cooccurrence[z][x].direction[i].black* cooccurrence[y][x].direction[i].black/ density_x[z].direction[i].black/density_y[x].direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) Q[z][y].direction[i].alpha+= cooccurrence[z][x].direction[i].alpha* cooccurrence[y][x].direction[i].alpha/ density_x[z].direction[i].alpha/ density_y[x].direction[i].alpha; } } channel_features[RedPixelChannel].contrast[i]+=z*z* pixel.direction[i].red; channel_features[GreenPixelChannel].contrast[i]+=z*z* pixel.direction[i].green; channel_features[BluePixelChannel].contrast[i]+=z*z* pixel.direction[i].blue; if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].contrast[i]+=z*z* pixel.direction[i].black; if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].contrast[i]+=z*z* pixel.direction[i].alpha; } /* Maximum Correlation Coefficient. Future: return second largest eigenvalue of Q. */ channel_features[RedPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[GreenPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); channel_features[BluePixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->colorspace == CMYKColorspace) channel_features[BlackPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); if (image->alpha_trait != UndefinedPixelTrait) channel_features[AlphaPixelChannel].maximum_correlation_coefficient[i]= sqrt((double) -1.0); } /* Relinquish resources. */ sum=(ChannelStatistics *) RelinquishMagickMemory(sum); for (i=0; i < (ssize_t) number_grays; i++) Q[i]=(ChannelStatistics *) RelinquishMagickMemory(Q[i]); Q=(ChannelStatistics **) RelinquishMagickMemory(Q); density_y=(ChannelStatistics *) RelinquishMagickMemory(density_y); density_xy=(ChannelStatistics *) RelinquishMagickMemory(density_xy); density_x=(ChannelStatistics *) RelinquishMagickMemory(density_x); for (i=0; i < (ssize_t) number_grays; i++) cooccurrence[i]=(ChannelStatistics *) RelinquishMagickMemory(cooccurrence[i]); cooccurrence=(ChannelStatistics **) RelinquishMagickMemory(cooccurrence); return(channel_features); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % H o u g h L i n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Use HoughLineImage() in conjunction with any binary edge extracted image (we % recommand Canny) to identify lines in the image. The algorithm accumulates % counts for every white pixel for every possible orientation (for angles from % 0 to 179 in 1 degree increments) and distance from the center of the image to % the corner (in 1 px increments) and stores the counts in an accumulator % matrix of angle vs distance. The size of the accumulator is 180x(diagonal/2). % Next it searches this space for peaks in counts and converts the locations % of the peaks to slope and intercept in the normal x,y input image space. Use % the slope/intercepts to find the endpoints clipped to the bounds of the % image. The lines are then drawn. The counts are a measure of the length of % the lines. % % The format of the HoughLineImage method is: % % Image *HoughLineImage(const Image *image,const size_t width, % const size_t height,const size_t threshold,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find line pairs as local maxima in this neighborhood. % % o threshold: the line count threshold. % % o exception: return any errors or warnings in this structure. % */ 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)); } static Image *RenderHoughLines(const ImageInfo *image_info,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define BoundingBox "viewbox" DrawInfo *draw_info; Image *image; MagickBooleanType status; /* Open image. */ image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } image->columns=columns; image->rows=rows; draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->affine.sx=image->resolution.x == 0.0 ? 1.0 : image->resolution.x/ DefaultResolution; draw_info->affine.sy=image->resolution.y == 0.0 ? 1.0 : image->resolution.y/ DefaultResolution; image->columns=(size_t) (draw_info->affine.sx*image->columns); image->rows=(size_t) (draw_info->affine.sy*image->rows); status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Render drawing. */ if (GetBlobStreamData(image) == (unsigned char *) NULL) draw_info->primitive=FileToString(image->filename,~0UL,exception); else { draw_info->primitive=(char *) AcquireMagickMemory((size_t) GetBlobSize(image)+1); if (draw_info->primitive != (char *) NULL) { (void) memcpy(draw_info->primitive,GetBlobStreamData(image), (size_t) GetBlobSize(image)); draw_info->primitive[GetBlobSize(image)]='\0'; } } (void) DrawImage(image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } MagickExport Image *HoughLineImage(const Image *image,const size_t width, const size_t height,const size_t threshold,ExceptionInfo *exception) { #define HoughLineImageTag "HoughLine/Image" CacheView *image_view; char message[MagickPathExtent], path[MagickPathExtent]; const char *artifact; double hough_height; Image *lines_image = NULL; ImageInfo *image_info; int file; MagickBooleanType status; MagickOffsetType progress; MatrixInfo *accumulator; PointInfo center; register ssize_t y; size_t accumulator_height, accumulator_width, line_count; /* Create the accumulator. */ assert(image != (const 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); accumulator_width=180; hough_height=((sqrt(2.0)*(double) (image->rows > image->columns ? image->rows : image->columns))/2.0); accumulator_height=(size_t) (2.0*hough_height); accumulator=AcquireMatrixInfo(accumulator_width,accumulator_height, sizeof(double),exception); if (accumulator == (MatrixInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); if (NullMatrix(accumulator) == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Populate the accumulator. */ status=MagickTrue; progress=0; center.x=(double) image->columns/2.0; center.y=(double) image->rows/2.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelIntensity(image,p) > (QuantumRange/2.0)) { register ssize_t i; for (i=0; i < 180; i++) { double count, radius; radius=(((double) x-center.x)*cos(DegreesToRadians((double) i)))+ (((double) y-center.y)*sin(DegreesToRadians((double) i))); (void) GetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); count++; (void) SetMatrixElement(accumulator,i,(ssize_t) MagickRound(radius+hough_height),&count); } } p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,CannyEdgeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } /* Generate line segments from accumulator. */ file=AcquireUniqueFileResource(path); if (file == -1) { accumulator=DestroyMatrixInfo(accumulator); return((Image *) NULL); } (void) FormatLocaleString(message,MagickPathExtent, "# Hough line transform: %.20gx%.20g%+.20g\n",(double) width, (double) height,(double) threshold); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; (void) FormatLocaleString(message,MagickPathExtent, "viewbox 0 0 %.20g %.20g\n",(double) image->columns,(double) image->rows); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; (void) FormatLocaleString(message,MagickPathExtent, "# x1,y1 x2,y2 # count angle distance\n"); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; line_count=image->columns > image->rows ? image->columns/4 : image->rows/4; if (threshold != 0) line_count=threshold; for (y=0; y < (ssize_t) accumulator_height; y++) { register ssize_t x; for (x=0; x < (ssize_t) accumulator_width; x++) { double count; (void) GetMatrixElement(accumulator,x,y,&count); if (count >= (double) line_count) { double maxima; SegmentInfo line; ssize_t v; /* Is point a local maxima? */ maxima=count; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((u != 0) || (v !=0)) { (void) GetMatrixElement(accumulator,x+u,y+v,&count); if (count > maxima) { maxima=count; break; } } } if (u < (ssize_t) (width/2)) break; } (void) GetMatrixElement(accumulator,x,y,&count); if (maxima > count) continue; if ((x >= 45) && (x <= 135)) { /* y = (r-x cos(t))/sin(t) */ line.x1=0.0; line.y1=((double) (y-(accumulator_height/2.0))-((line.x1- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); line.x2=(double) image->columns; line.y2=((double) (y-(accumulator_height/2.0))-((line.x2- (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ sin(DegreesToRadians((double) x))+(image->rows/2.0); } else { /* x = (r-y cos(t))/sin(t) */ line.y1=0.0; line.x1=((double) (y-(accumulator_height/2.0))-((line.y1- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); line.y2=(double) image->rows; line.x2=((double) (y-(accumulator_height/2.0))-((line.y2- (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ cos(DegreesToRadians((double) x))+(image->columns/2.0); } (void) FormatLocaleString(message,MagickPathExtent, "line %g,%g %g,%g # %g %g %g\n",line.x1,line.y1,line.x2,line.y2, maxima,(double) x,(double) y); if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) status=MagickFalse; } } } (void) close(file); /* Render lines to image canvas. */ image_info=AcquireImageInfo(); image_info->background_color=image->background_color; (void) FormatLocaleString(image_info->filename,MagickPathExtent,"%s",path); artifact=GetImageArtifact(image,"background"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"background",artifact); artifact=GetImageArtifact(image,"fill"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"fill",artifact); artifact=GetImageArtifact(image,"stroke"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"stroke",artifact); artifact=GetImageArtifact(image,"strokewidth"); if (artifact != (const char *) NULL) (void) SetImageOption(image_info,"strokewidth",artifact); lines_image=RenderHoughLines(image_info,image->columns,image->rows,exception); artifact=GetImageArtifact(image,"hough-lines:accumulator"); if ((lines_image != (Image *) NULL) && (IsStringTrue(artifact) != MagickFalse)) { Image *accumulator_image; accumulator_image=MatrixToImage(accumulator,exception); if (accumulator_image != (Image *) NULL) AppendImageToList(&lines_image,accumulator_image); } /* Free resources. */ accumulator=DestroyMatrixInfo(accumulator); image_info=DestroyImageInfo(image_info); (void) RelinquishUniqueFileResource(path); return(GetFirstImageInList(lines_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M e a n S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MeanShiftImage() delineate arbitrarily shaped clusters in the image. For % each pixel, it visits all the pixels in the neighborhood specified by % the window centered at the pixel and excludes those that are outside the % radius=(window-1)/2 surrounding the pixel. From those pixels, it finds those % that are within the specified color distance from the current mean, and % computes a new x,y centroid from those coordinates and a new mean. This new % x,y centroid is used as the center for a new window. This process iterates % until it converges and the final mean is replaces the (original window % center) pixel value. It repeats this process for the next pixel, etc., % until it processes all pixels in the image. Results are typically better with % colorspaces other than sRGB. We recommend YIQ, YUV or YCbCr. % % The format of the MeanShiftImage method is: % % Image *MeanShiftImage(const Image *image,const size_t width, % const size_t height,const double color_distance, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width, height: find pixels in this neighborhood. % % o color_distance: the color distance. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MeanShiftImage(const Image *image,const size_t width, const size_t height,const double color_distance,ExceptionInfo *exception) { #define MaxMeanShiftIterations 100 #define MeanShiftImageTag "MeanShift/Image" CacheView *image_view, *mean_view, *pixel_view; Image *mean_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (const 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); mean_image=CloneImage(image,0,0,MagickTrue,exception); if (mean_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse) { mean_image=DestroyImage(mean_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); pixel_view=AcquireVirtualCacheView(image,exception); mean_view=AcquireAuthenticCacheView(mean_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,progress) \ magick_number_threads(mean_image,mean_image,mean_image->rows,1) #endif for (y=0; y < (ssize_t) mean_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) mean_image->columns; x++) { PixelInfo mean_pixel, previous_pixel; PointInfo mean_location, previous_location; register ssize_t i; GetPixelInfo(image,&mean_pixel); GetPixelInfoPixel(image,p,&mean_pixel); mean_location.x=(double) x; mean_location.y=(double) y; for (i=0; i < MaxMeanShiftIterations; i++) { double distance, gamma; PixelInfo sum_pixel; PointInfo sum_location; ssize_t count, v; sum_location.x=0.0; sum_location.y=0.0; GetPixelInfo(image,&sum_pixel); previous_location=mean_location; previous_pixel=mean_pixel; count=0; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) { PixelInfo pixel; status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t) MagickRound(mean_location.x+u),(ssize_t) MagickRound( mean_location.y+v),&pixel,exception); distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); if (distance <= (color_distance*color_distance)) { sum_location.x+=mean_location.x+u; sum_location.y+=mean_location.y+v; sum_pixel.red+=pixel.red; sum_pixel.green+=pixel.green; sum_pixel.blue+=pixel.blue; sum_pixel.alpha+=pixel.alpha; count++; } } } } gamma=PerceptibleReciprocal(count); mean_location.x=gamma*sum_location.x; mean_location.y=gamma*sum_location.y; mean_pixel.red=gamma*sum_pixel.red; mean_pixel.green=gamma*sum_pixel.green; mean_pixel.blue=gamma*sum_pixel.blue; mean_pixel.alpha=gamma*sum_pixel.alpha; distance=(mean_location.x-previous_location.x)* (mean_location.x-previous_location.x)+ (mean_location.y-previous_location.y)* (mean_location.y-previous_location.y)+ 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); if (distance <= 3.0) break; } SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q); SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q); SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q); SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q); p+=GetPixelChannels(image); q+=GetPixelChannels(mean_image); } if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } mean_view=DestroyCacheView(mean_view); pixel_view=DestroyCacheView(pixel_view); image_view=DestroyCacheView(image_view); return(mean_image); }
./CrossVul/dataset_final_sorted/CWE-369/c/good_1008_0
crossvul-cpp_data_bad_4778_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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-2016 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/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/draw.h" #include "magick/enhance.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/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/memory-private.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/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/splay-tree.h" #include "magick/static.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread_.h" #include "magick/token.h" #include "magick/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; #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 *), WritePTIFImage(const ImageInfo *,Image *), WriteTIFFImage(const ImageInfo *,Image *); #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[MaxTextExtent]; 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 == 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); } /* 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); 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,(size_t) (image->x_resolution+0.5)); 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); (void) fclose(file); (void) CloseBlob(image); image=DestroyImage(image); /* Read TIFF image. */ read_info=CloneImageInfo((ImageInfo *) NULL); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"%s",filename); image=ReadTIFFImage(read_info,exception); read_info=DestroyImageInfo(read_info); 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,"GROUP4",MaxTextExtent); } (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 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; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(q)+0.5; if (a > 1.0) a-=1.0; b=QuantumScale*GetPixelb(q)+0.5; if (b > 1.0) b-=1.0; SetPixela(q,QuantumRange*a); SetPixelb(q,QuantumRange*b); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } static MagickBooleanType ReadProfile(Image *image,const char *name, const unsigned char *datum,ssize_t length) { 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); 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[MaxTextExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MaxTextExtent,format,error); #else (void) vsprintf(message,format,error); #endif (void) ConcatenateMagickString(message,".",MaxTextExtent); 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,MagickBooleanType ping) { uint32 length; unsigned char *profile; length=0; if (ping == MagickFalse) { #if defined(TIFFTAG_ICCPROFILE) if ((TIFFGetField(tiff,TIFFTAG_ICCPROFILE,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"icc",profile,(ssize_t) length); #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); #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); } #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); #endif if ((TIFFGetField(tiff,34118,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:34118",profile,(ssize_t) length); } if ((TIFFGetField(tiff,37724,&length,&profile) == 1) && (profile != (unsigned char *) NULL)) (void) ReadProfile(image,"tiff:37724",profile,(ssize_t) length); } static void TIFFGetProperties(TIFF *tiff,Image *image) { char message[MaxTextExtent], *text; uint32 count, length, type; unsigned long *tietz; if (TIFFGetField(tiff,TIFFTAG_ARTIST,&text) == 1) (void) SetImageProperty(image,"tiff:artist",text); if (TIFFGetField(tiff,TIFFTAG_COPYRIGHT,&text) == 1) (void) SetImageProperty(image,"tiff:copyright",text); if (TIFFGetField(tiff,TIFFTAG_DATETIME,&text) == 1) (void) SetImageProperty(image,"tiff:timestamp",text); if (TIFFGetField(tiff,TIFFTAG_DOCUMENTNAME,&text) == 1) (void) SetImageProperty(image,"tiff:document",text); if (TIFFGetField(tiff,TIFFTAG_HOSTCOMPUTER,&text) == 1) (void) SetImageProperty(image,"tiff:hostcomputer",text); if (TIFFGetField(tiff,TIFFTAG_IMAGEDESCRIPTION,&text) == 1) (void) SetImageProperty(image,"comment",text); if (TIFFGetField(tiff,TIFFTAG_MAKE,&text) == 1) (void) SetImageProperty(image,"tiff:make",text); if (TIFFGetField(tiff,TIFFTAG_MODEL,&text) == 1) (void) SetImageProperty(image,"tiff:model",text); if (TIFFGetField(tiff,TIFFTAG_OPIIMAGEID,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:image-id",message); } if (TIFFGetField(tiff,TIFFTAG_PAGENAME,&text) == 1) (void) SetImageProperty(image,"label",text); if (TIFFGetField(tiff,TIFFTAG_SOFTWARE,&text) == 1) (void) SetImageProperty(image,"tiff:software",text); if (TIFFGetField(tiff,33423,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-33423",message); } if (TIFFGetField(tiff,36867,&count,&text) == 1) { if (count >= MaxTextExtent) count=MaxTextExtent-1; (void) CopyMagickString(message,text,count+1); (void) SetImageProperty(image,"tiff:kodak-36867",message); } if (TIFFGetField(tiff,TIFFTAG_SUBFILETYPE,&type) == 1) switch (type) { case 0x01: { (void) SetImageProperty(image,"tiff:subfiletype","REDUCEDIMAGE"); break; } case 0x02: { (void) SetImageProperty(image,"tiff:subfiletype","PAGE"); break; } case 0x04: { (void) SetImageProperty(image,"tiff:subfiletype","MASK"); break; } default: break; } if (TIFFGetField(tiff,37706,&length,&tietz) == 1) { (void) FormatLocaleString(message,MaxTextExtent,"%lu",tietz[0]); (void) SetImageProperty(image,"tiff:tietz_offset",message); } } static void TIFFGetEXIFProperties(TIFF *tiff,Image *image) { #if defined(MAGICKCORE_HAVE_TIFFREADEXIFDIRECTORY) char value[MaxTextExtent]; register ssize_t i; tdir_t directory; #if defined(TIFF_VERSION_BIG) uint64 #else uint32 #endif offset; void *sans; /* 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; } sans=NULL; 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,&sans) == 1) && (ascii != (char *) NULL) && (*ascii != '\0')) (void) CopyMagickString(value,ascii,MaxTextExtent); break; } case TIFF_SHORT: { if (exif_info[i].variable_length == 0) { uint16 shorty; shorty=0; if (TIFFGetField(tiff,exif_info[i].tag,&shorty,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",shorty); } else { int tiff_status; uint16 *shorty; uint16 shorty_num; tiff_status=TIFFGetField(tiff,exif_info[i].tag,&shorty_num,&shorty, &sans,&sans); if (tiff_status == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d", shorty_num != 0 ? shorty[0] : 0); } break; } case TIFF_LONG: { uint32 longy; longy=0; if (TIFFGetField(tiff,exif_info[i].tag,&longy,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%d",longy); break; } #if defined(TIFF_VERSION_BIG) case TIFF_LONG8: { uint64 long8y; long8y=0; if (TIFFGetField(tiff,exif_info[i].tag,&long8y,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%.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,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",(double) floaty); break; } case TIFF_DOUBLE: { double doubley; doubley=0.0; if (TIFFGetField(tiff,exif_info[i].tag,&doubley,&sans,&sans) == 1) (void) FormatLocaleString(value,MaxTextExtent,"%g",doubley); break; } default: break; } if (*value != '\0') (void) SetImageProperty(image,exif_info[i].property,value); } 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,size_t bits_per_sample, tsample_t sample,ssize_t row,tdata_t scanline) { int32 status; (void) bits_per_sample; 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[MaxTextExtent]; ExceptionInfo *exception; #if defined(MAGICKCORE_HAVE_VSNPRINTF) (void) vsnprintf(message,MaxTextExtent,format,warning); #else (void) vsprintf(message,format,warning); #endif (void) ConcatenateMagickString(message,".",MaxTextExtent); 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 */ if (!TIFFGetField(tiff,TIFFTAG_STRIPOFFSETS,&value)) 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 void TIFFReadPhotoshopLayers(Image* image,const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; const StringInfo *layer_info; Image *layers; 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; layer_info=GetImageProfile(image,"tiff:37724"); if (layer_info == (const StringInfo *) NULL) return; for (i=0; i < (ssize_t) layer_info->length-8; i++) { if (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "8BIM" : "MIB8",4) != 0) continue; i+=4; if ((LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Layr" : "ryaL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "LMsk" : "ksML",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr16" : "61rL",4) == 0) || (LocaleNCompare((const char *) (layer_info->datum+i), image->endian == MSBEndian ? "Lr32" : "23rL",4) == 0)) break; } i+=4; if (i >= (ssize_t) (layer_info->length-8)) return; layers=CloneImage(image,image->columns,image->rows,MagickTrue,exception); (void) DeleteImageProfile(layers,"tiff:37724"); AttachBlob(layers->blob,layer_info->datum,layer_info->length); SeekBlob(layers,(MagickOffsetType) i,SEEK_SET); info.version=1; info.columns=layers->columns; info.rows=layers->rows; /* Setting the mode to a value that won't change the colorspace */ info.mode=10; if (IsGrayImage(image,&image->exception) != MagickFalse) info.channels=(image->matte != MagickFalse ? 2UL : 1UL); else if (image->storage_class == PseudoClass) info.channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->colorspace != CMYKColorspace) info.channels=(image->matte != MagickFalse ? 4UL : 3UL); else info.channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) ReadPSDLayers(layers,image_info,&info,MagickFalse,exception); InheritException(exception,&layers->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); } } } #if defined(__cplusplus) || defined(c_plusplus) } #endif static Image *ReadTIFFImage(const ImageInfo *image_info, ExceptionInfo *exception) { const char *option; float *chromaticity, x_position, y_position, x_resolution, y_resolution; Image *image; int tiff_status; MagickBooleanType 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 *pixels; /* Open image. */ 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) 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); if (GetNextImageInList(image) == (Image *) NULL) { TIFFClose(tiff); image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); } } } do { DisableMSCWarning(4127) if (0 && (image_info->verbose != MagickFalse)) TIFFPrintDirectory(tiff,stdout,MagickFalse); RestoreMSCWarning if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 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) || (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric) != 1)) { TIFFClose(tiff); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (sample_format == SAMPLEFORMAT_IEEEFP) (void) SetImageProperty(image,"quantum:format","floating-point"); switch (photometric) { case PHOTOMETRIC_MINISBLACK: { (void) SetImageProperty(image,"tiff:photometric","min-is-black"); break; } case PHOTOMETRIC_MINISWHITE: { (void) SetImageProperty(image,"tiff:photometric","min-is-white"); break; } case PHOTOMETRIC_PALETTE: { (void) SetImageProperty(image,"tiff:photometric","palette"); break; } case PHOTOMETRIC_RGB: { (void) SetImageProperty(image,"tiff:photometric","RGB"); break; } case PHOTOMETRIC_CIELAB: { (void) SetImageProperty(image,"tiff:photometric","CIELAB"); break; } case PHOTOMETRIC_LOGL: { (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); break; } case PHOTOMETRIC_LOGLUV: { (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); break; } #if defined(PHOTOMETRIC_MASK) case PHOTOMETRIC_MASK: { (void) SetImageProperty(image,"tiff:photometric","MASK"); break; } #endif case PHOTOMETRIC_SEPARATED: { (void) SetImageProperty(image,"tiff:photometric","separated"); break; } case PHOTOMETRIC_YCBCR: { (void) SetImageProperty(image,"tiff:photometric","YCBCR"); break; } default: { (void) SetImageProperty(image,"tiff:photometric","unknown"); 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")); } 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"); image->endian=LSBEndian; } else { (void) SetImageProperty(image,"tiff:endian","msb"); image->endian=MSBEndian; } #endif if ((photometric == PHOTOMETRIC_MINISBLACK) || (photometric == PHOTOMETRIC_MINISWHITE)) SetImageColorspace(image,GRAYColorspace); if (photometric == PHOTOMETRIC_SEPARATED) SetImageColorspace(image,CMYKColorspace); if (photometric == PHOTOMETRIC_CIELAB) SetImageColorspace(image,LabColorspace); TIFFGetProfiles(tiff,image,image_info->ping); TIFFGetProperties(tiff,image); option=GetImageOption(image_info,"tiff:exif-properties"); if ((option == (const char *) NULL) || (IsMagickTrue(option) != MagickFalse)) TIFFGetEXIFProperties(tiff,image); if ((TIFFGetFieldDefaulted(tiff,TIFFTAG_XRESOLUTION,&x_resolution) == 1) && (TIFFGetFieldDefaulted(tiff,TIFFTAG_YRESOLUTION,&y_resolution) == 1)) { image->x_resolution=x_resolution; image->y_resolution=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->x_resolution-0.5); image->page.y=(ssize_t) ceil(y_position*image->y_resolution-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[MaxTextExtent]; int tiff_status; uint16 horizontal, vertical; tiff_status=TIFFGetFieldDefaulted(tiff,TIFFTAG_YCBCRSUBSAMPLING, &horizontal,&vertical); if (tiff_status == 1) { (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", horizontal,vertical); (void) SetImageProperty(image,"jpeg:sampling-factor", sampling_factor); (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; } /* Allocate memory for the image and pixel buffer. */ quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(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) { TIFFClose(tiff); quantum_info=DestroyQuantumInfo(quantum_info); ThrowReaderException(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"); if (extra_samples == 0) { if ((samples_per_pixel == 4) && (photometric == PHOTOMETRIC_RGB)) image->matte=MagickTrue; } else for (i=0; i < extra_samples; i++) { image->matte=MagickTrue; if (sample_info[i] == EXTRASAMPLE_ASSOCALPHA) { SetQuantumAlphaType(quantum_info,DisassociatedQuantumAlpha); (void) SetImageProperty(image,"tiff:alpha","associated"); } else if (sample_info[i] == EXTRASAMPLE_UNASSALPHA) (void) SetImageProperty(image,"tiff:alpha","unassociated"); } } 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) == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } } if (TIFFGetFieldDefaulted(tiff,TIFFTAG_PAGENUMBER,&value,&pages) == 1) image->scene=value; if (image->storage_class == PseudoClass) { int tiff_status; 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->matte == MagickFalse) image->depth=GetImageDepth(image,exception); } if (image_info->ping != MagickFalse) { if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) { quantum_info=DestroyQuantumInfo(quantum_info); break; } goto next_tiff_frame; } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } method=ReadGenericMethod; if (TIFFGetField(tiff,TIFFTAG_ROWSPERSTRIP,&rows_per_strip) == 1) { char value[MaxTextExtent]; method=ReadStripMethod; (void) FormatLocaleString(value,MaxTextExtent,"%u",(unsigned int) rows_per_strip); (void) SetImageProperty(image,"tiff:rows-per-strip",value); } if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_CONTIG)) method=ReadRGBAMethod; if ((samples_per_pixel >= 2) && (interlace == PLANARCONFIG_SEPARATE)) 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; pixels=GetQuantumPixels(quantum_info); switch (method) { case ReadSingleSampleMethod: { /* Convert TIFF image to PseudoClass MIFF image. */ quantum_type=IndexQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); if (image->matte != MagickFalse) { if (image->storage_class != PseudoClass) { quantum_type=samples_per_pixel == 1 ? AlphaQuantum : GrayAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } else { quantum_type=IndexAlphaQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-2,0); } } else if (image->storage_class != PseudoClass) { quantum_type=GrayQuantum; pad=(size_t) MagickMax((size_t) samples_per_pixel-1,0); } status=SetQuantumPad(image,quantum_info,pad*pow(2,ceil(log( bits_per_sample)/log(2)))); if (status == MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,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->matte != MagickFalse) { 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->matte != MagickFalse) { 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) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register PixelPacket *magick_restrict q; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; (void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,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 PixelPacket *magick_restrict q; int status; status=TIFFReadPixels(tiff,bits_per_sample,(tsample_t) i,y,(char *) pixels); if (status == -1) break; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) 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,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: { pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { int status; register IndexPacket *indexes; register PixelPacket *magick_restrict q; register ssize_t x; unsigned char *p; status=TIFFReadPixels(tiff,bits_per_sample,0,y,(char *) pixels); if (status == -1) break; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); p=pixels; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.402*(double) *(p+2))-179.456))); SetPixelMagenta(q,ScaleCharToQuantum(ClampYCC((double) *p- (0.34414*(double) *(p+1))-(0.71414*(double ) *(p+2))+ 135.45984))); SetPixelYellow(q,ScaleCharToQuantum(ClampYCC((double) *p+ (1.772*(double) *(p+1))-226.816))); SetPixelBlack(indexes+x,ScaleCharToQuantum((unsigned char)*(p+3))); q++; 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 PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; if (i == 0) { if (TIFFReadRGBAStrip(tiff,(tstrip_t) y,(uint32 *) pixels) == 0) break; i=(ssize_t) MagickMin((ssize_t) rows_per_strip,(ssize_t) image->rows-y); } i--; p=((uint32 *) pixels)+image->columns*i; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) (TIFFGetR(*p)))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) (TIFFGetG(*p)))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) (TIFFGetB(*p)))); if (image->matte != MagickFalse) SetPixelOpacity(q,ScaleCharToQuantum((unsigned char) (TIFFGetA(*p)))); p++; q++; } 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)) { TIFFClose(tiff); ThrowReaderException(CoderError,"ImageIsNotTiled"); } (void) SetImageStorageClass(image,DirectClass); number_pixels=(MagickSizeType) columns*rows; if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } tile_pixels=(uint32 *) AcquireQuantumMemory(columns, rows*sizeof(*tile_pixels)); if (tile_pixels == (uint32 *) NULL) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y+=rows) { PixelPacket *tile; register ssize_t x; register PixelPacket *magick_restrict q; 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 == (PixelPacket *) 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+(image->columns*(rows_remaining-1)+x); for (row=rows_remaining; row > 0; row--) { if (image->matte != MagickFalse) for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); q++; p++; } else for (column=columns_remaining; column > 0; column--) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); q++; p++; } p+=columns-columns_remaining; q-=(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) { TIFFClose(tiff); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } pixel_info=AcquireVirtualMemory(image->columns,image->rows* sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { TIFFClose(tiff); ThrowReaderException(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 PixelPacket *magick_restrict q; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; q+=image->columns-1; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) TIFFGetR(*p))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) TIFFGetG(*p))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) TIFFGetB(*p))); if (image->matte != MagickFalse) SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) TIFFGetA(*p))); p--; q--; } 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; } } SetQuantumImageType(image,quantum_type); next_tiff_frame: 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; status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; if (status != MagickFalse) { /* 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,image->scene-1, image->scene); if (status == MagickFalse) break; } } while (status != MagickFalse); TIFFClose(tiff); TIFFReadPhotoshopLayers(image,image_info,exception); if (image_info->number_scenes != 0) { if (image_info->scene >= GetImageListLength(image)) { /* Subimage was not found in the Photoshop layer */ image = DestroyImageList(image); return((Image *)NULL); } } 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)); /* This also sets field_bit to 0 (FIELD_IGNORE) */ ResetMagickMemory(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[MaxTextExtent]; 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,MaxTextExtent,"%d",TIFF_VERSION); #endif #if defined(MAGICKCORE_TIFF_DELEGATE) { const char *p; register ssize_t i; p=TIFFGetVersion(); for (i=0; (i < (MaxTextExtent-1)) && (*p != 0) && (*p != '\n'); i++) version[i]=(*p++); version[i]='\0'; } #endif entry=SetMagickInfo("GROUP4"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadGROUP4Image; entry->encoder=(EncodeImageHandler *) WriteGROUP4Image; #endif entry->raw=MagickTrue; entry->endian_support=MagickTrue; entry->adjoin=MagickFalse; entry->format_type=ImplicitFormatType; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Raw CCITT Group4"); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PTIF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WritePTIFImage; #endif entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Pyramid encoded TIFF"); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->stealth=MagickTrue; entry->description=ConstantString(TIFFDescription); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIFF"); #if defined(MAGICKCORE_TIFF_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->magick=(IsImageFormatHandler *) IsTIFF; entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString(TIFFDescription); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("TIFF"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("TIFF64"); #if defined(TIFF_VERSION_BIG) entry->decoder=(DecodeImageHandler *) ReadTIFFImage; entry->encoder=(EncodeImageHandler *) WriteTIFFImage; #endif entry->adjoin=MagickFalse; entry->endian_support=MagickTrue; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Tagged Image File Format (64-bit)"); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/tiff"); entry->module=ConstantString("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 (DeleteMagickThreadKey(tiff_exception) == MagickFalse) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); #if defined(MAGICKCORE_HAVE_TIFFMERGEFIELDINFO) && defined(MAGICKCORE_HAVE_TIFFSETTAGEXTENDER) if (tag_extender == (TIFFExtendProc) NULL) (void) TIFFSetTagExtender(tag_extender); #endif (void) TIFFSetWarningHandler(warning_handler); (void) TIFFSetErrorHandler(error_handler); instantiate_key=MagickFalse; } UnlockSemaphoreInfo(tiff_semaphore); DestroySemaphoreInfo(&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) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ static MagickBooleanType WriteGROUP4Image(const ImageInfo *image_info, Image *image) { char filename[MaxTextExtent]; 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 == 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); huffman_image=CloneImage(image,0,0,MagickTrue,&image->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(&image->exception,FileOpenError, "UnableToCreateTemporaryFile",filename); return(MagickFalse); } (void) FormatLocaleString(huffman_image->filename,MaxTextExtent,"tiff:%s", filename); (void) SetImageType(huffman_image,BilevelType); write_info=CloneImageInfo((ImageInfo *) NULL); SetImageInfoFile(write_info,file); (void) SetImageDepth(image,1); (void) SetImageType(image,BilevelType); write_info->compression=Group4Compression; write_info->type=BilevelType; (void) SetImageOption(write_info,"quantum:polarity","min-is-white"); status=WriteTIFFImage(write_info,huffman_image); (void) fflush(file); write_info=DestroyImageInfo(write_info); if (status == MagickFalse) { InheritException(&image->exception,&huffman_image->exception); 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(&image->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) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ 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. */ exception=(&image->exception); 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"); AppendImageToList(&images,clone_image); columns=next->columns; rows=next->rows; resolution.x=next->x_resolution; resolution.y=next->y_resolution; while ((columns > 64) && (rows > 64)) { columns/=2; rows/=2; resolution.x/=2.0; resolution.y/=2.0; pyramid_image=ResizeImage(next,columns,rows,image->filter,image->blur, exception); if (pyramid_image == (Image *) NULL) break; pyramid_image->x_resolution=resolution.x; pyramid_image->y_resolution=resolution.y; (void) SetImageProperty(pyramid_image,"tiff:subfiletype","REDUCEDIMAGE"); AppendImageToList(&images,pyramid_image); } } /* Write pyramid-encoded TIFF image. */ write_info=CloneImageInfo(image_info); write_info->adjoin=MagickTrue; status=WriteTIFFImage(write_info,GetFirstImageInList(images)); 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) % % A description of each parameter follows: % % o image_info: the image info. % % o image: The image. % */ 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 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; } for (x=0; x < (ssize_t) image->columns; x++) { double a, b; a=QuantumScale*GetPixela(q)-0.5; if (a < 0.0) a+=1.0; b=QuantumScale*GetPixelb(q)-0.5; if (b < 0.0) b+=1.0; SetPixela(q,QuantumRange*a); SetPixelb(q,QuantumRange*b); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } 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) ResetMagickMemory(tiff_info,0,sizeof(*tiff_info)); option=GetImageOption(image_info,"tiff:tile-geometry"); if (option == (const char *) NULL) return(MagickTrue); 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; 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) CopyMagickMemory(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 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 ImageInfo *image_info, Image *image) { 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"); if (value != (const char *) NULL) (void) TIFFSetField(tiff,TIFFTAG_PAGENAME,value); value=GetImageProperty(image,"comment"); 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 ((image_info->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) { #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); 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) { #if !defined(TIFFDefaultStripSize) #define TIFFDefaultStripSize(tiff,request) (8192UL/TIFFScanlineSize(tiff)) #endif const char *mode, *option; CompressionType compression; EndianType endian_type; MagickBooleanType debug, status; MagickOffsetType scene; QuantumInfo *quantum_info; QuantumType quantum_type; register ssize_t i; ssize_t y; TIFF *tiff; TIFFInfo tiff_info; uint16 bits_per_sample, compress_tag, endian, photometric; uint32 rows_per_strip; unsigned char *pixels; /* Open TIFF 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) SetMagickThreadValue(tiff_exception,&image->exception); endian_type=UndefinedEndian; 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;; } switch (endian_type) { case LSBEndian: mode="wl"; break; case MSBEndian: mode="wb"; break; default: mode="w"; break; } #if defined(TIFF_VERSION_BIG) if (LocaleCompare(image_info->magick,"TIFF64") == 0) switch (endian_type) { case LSBEndian: mode="wl8"; break; case MSBEndian: mode="wb8"; break; default: mode="w8"; break; } #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; do { /* Initialize TIFF fields. */ if ((image_info->type != UndefinedType) && (image_info->type != OptimizeType)) (void) SetImageType(image,image_info->type); 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); (void) SetImageDepth(image,1); break; } case JPEGCompression: { (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); 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,&image->exception) != MagickFalse)) { status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) 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(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; } #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(&image->exception,GetMagickModule(), CoderError,"CompressionNotSupported","`%s'",CommandOptionToMnemonic( MagickCompressOptions,(ssize_t) compression)); compress_tag=COMPRESSION_NONE; 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,&image->exception); } else if (image->colorspace == YCbCrColorspace) { photometric=PHOTOMETRIC_YCBCR; (void) TIFFSetField(tiff,TIFFTAG_YCBCRSUBSAMPLING,1,1); (void) SetImageStorageClass(image,DirectClass); (void) SetImageDepth(image,8); } else photometric=PHOTOMETRIC_RGB; (void) TIFFSetField(tiff,TIFFTAG_SAMPLESPERPIXEL,3); if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType)) { if ((image_info->type != PaletteType) && (SetImageGray(image,&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->matte == MagickFalse)) SetImageMonochrome(image,&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->matte != MagickFalse) { 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); rows_per_strip=TIFFDefaultStripSize(tiff,0); option=GetImageOption(image_info,"tiff:rows-per-strip"); if (option != (const char *) NULL) rows_per_strip=(size_t) strtol(option,(char **) NULL,10); switch (compress_tag) { case COMPRESSION_JPEG: { #if defined(JPEG_SUPPORT) const char *sampling_factor; GeometryInfo geometry_info; MagickStatusType flags; rows_per_strip+=(16-(rows_per_strip % 16)); 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); sampling_factor=(const char *) NULL; value=GetImageProperty(image,"jpeg:sampling-factor"); 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; if (image->colorspace == YCbCrColorspace) (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: { rows_per_strip=(uint32) image->rows; (void) TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE, &bits_per_sample); if (((photometric == PHOTOMETRIC_RGB) || (photometric == PHOTOMETRIC_MINISBLACK)) && ((bits_per_sample == 8) || (bits_per_sample == 16))) (void) TIFFSetField(tiff,TIFFTAG_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. */ rows_per_strip=(uint32) image->rows; (void) TIFFSetField(tiff,TIFFTAG_GROUP3OPTIONS,4); break; } case COMPRESSION_CCITTFAX4: { rows_per_strip=(uint32) image->rows; 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))) (void) TIFFSetField(tiff,TIFFTAG_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))) (void) TIFFSetField(tiff,TIFFTAG_PREDICTOR,PREDICTOR_HORIZONTAL); break; } default: break; } if (rows_per_strip < 1) rows_per_strip=1; if ((image->rows/rows_per_strip) >= (1UL << 15)) rows_per_strip=(uint32) (image->rows >> 15); (void) TIFFSetField(tiff,TIFFTAG_ROWSPERSTRIP,rows_per_strip); if ((image->x_resolution != 0.0) && (image->y_resolution != 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->x_resolution); (void) TIFFSetField(tiff,TIFFTAG_YRESOLUTION,image->y_resolution); if ((image->page.x < 0) || (image->page.y < 0)) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderError,"TIFF: negative image positions unsupported","%s", image->filename); if ((image->page.x > 0) && (image->x_resolution > 0.0)) { /* Set horizontal image position. */ (void) TIFFSetField(tiff,TIFFTAG_XPOSITION,(float) image->page.x/ image->x_resolution); } if ((image->page.y > 0) && (image->y_resolution > 0.0)) { /* Set vertical image position. */ (void) TIFFSetField(tiff,TIFFTAG_YPOSITION,(float) image->page.y/ image->y_resolution); } } 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); } if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (GetImageListLength(image) > 1)) { (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); if (image->scene != 0) (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,(uint16) image->scene, GetImageListLength(image)); } if (image->orientation != UndefinedOrientation) (void) TIFFSetField(tiff,TIFFTAG_ORIENTATION,(uint16) image->orientation); (void) TIFFSetProfiles(tiff,image); { uint16 page, pages; page=(uint16) scene; pages=(uint16) GetImageListLength(image); if ((LocaleCompare(image_info->magick,"PTIF") != 0) && (image_info->adjoin != MagickFalse) && (pages > 1)) (void) TIFFSetField(tiff,TIFFTAG_SUBFILETYPE,FILETYPE_PAGE); (void) TIFFSetField(tiff,TIFFTAG_PAGENUMBER,page,pages); } (void) TIFFSetProperties(tiff,image_info,image); DisableMSCWarning(4127) if (0) RestoreMSCWarning (void) TIFFSetEXIFProperties(tiff,image); /* Write image scanlines. */ if (GetTIFFInfo(image_info,tiff,&tiff_info) == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); quantum_info->endian=LSBEndian; pixels=GetQuantumPixels(quantum_info); tiff_info.scanline=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->matte != MagickFalse) quantum_type=RGBAQuantum; for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->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 PlaneInterlace: case PartitionInterlace: { /* Plane interlacing: RRRRRR...GGGGGG...BBBBBB... */ for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,RedQuantum,pixels,&image->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 PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,GreenQuantum,pixels,&image->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 PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,BlueQuantum,pixels,&image->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->matte != MagickFalse) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,AlphaQuantum,pixels,&image->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->matte != MagickFalse) quantum_type=CMYKAQuantum; if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->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)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize TIFF colormap. */ (void) ResetMagickMemory(red,0,65536*sizeof(*red)); (void) ResetMagickMemory(green,0,65536*sizeof(*green)); (void) ResetMagickMemory(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->matte != MagickFalse) { 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 PixelPacket *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; (void) ExportQuantumPixels(image,(const CacheView *) NULL, quantum_info,quantum_type,pixels,&image->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,&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++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); TIFFClose(tiff); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-369/c/bad_4778_1
crossvul-cpp_data_bad_2303_1
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library UNIX-specific Routines. These are should also work with the * Windows Common RunTime Library. */ #include "tif_config.h" #ifdef HAVE_SYS_TYPES_H # include <sys/types.h> #endif #include <errno.h> #include <stdarg.h> #include <stdlib.h> #include <sys/stat.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_FCNTL_H # include <fcntl.h> #endif #ifdef HAVE_IO_H # include <io.h> #endif #include "tiffiop.h" static tmsize_t _tiffReadProc(thandle_t fd, void* buf, tmsize_t size) { size_t size_io = (size_t) size; if ((tmsize_t) size_io != size) { errno=EINVAL; return (tmsize_t) -1; } return ((tmsize_t) read((int) fd, buf, size_io)); } static tmsize_t _tiffWriteProc(thandle_t fd, void* buf, tmsize_t size) { size_t size_io = (size_t) size; if ((tmsize_t) size_io != size) { errno=EINVAL; return (tmsize_t) -1; } return ((tmsize_t) write((int) fd, buf, size_io)); } static uint64 _tiffSeekProc(thandle_t fd, uint64 off, int whence) { off_t off_io = (off_t) off; if ((uint64) off_io != off) { errno=EINVAL; return (uint64) -1; /* this is really gross */ } return((uint64)lseek((int)fd,off_io,whence)); } static int _tiffCloseProc(thandle_t fd) { return(close((int)fd)); } static uint64 _tiffSizeProc(thandle_t fd) { struct stat sb; if (fstat((int)fd,&sb)<0) return(0); else return((uint64)sb.st_size); } #ifdef HAVE_MMAP #include <sys/mman.h> static int _tiffMapProc(thandle_t fd, void** pbase, toff_t* psize) { uint64 size64 = _tiffSizeProc(fd); tmsize_t sizem = (tmsize_t)size64; if ((uint64)sizem==size64) { *pbase = (void*) mmap(0, (size_t)sizem, PROT_READ, MAP_SHARED, (int) fd, 0); if (*pbase != (void*) -1) { *psize = (tmsize_t)sizem; return (1); } } return (0); } static void _tiffUnmapProc(thandle_t fd, void* base, toff_t size) { (void) fd; (void) munmap(base, (off_t) size); } #else /* !HAVE_MMAP */ static int _tiffMapProc(thandle_t fd, void** pbase, toff_t* psize) { (void) fd; (void) pbase; (void) psize; return (0); } static void _tiffUnmapProc(thandle_t fd, void* base, toff_t size) { (void) fd; (void) base; (void) size; } #endif /* !HAVE_MMAP */ /* * Open a TIFF file descriptor for read/writing. */ TIFF* TIFFFdOpen(int fd, const char* name, const char* mode) { TIFF* tif; tif = TIFFClientOpen(name, mode, (thandle_t) fd, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); if (tif) tif->tif_fd = fd; return (tif); } /* * Open a TIFF file for read/writing. */ TIFF* TIFFOpen(const char* name, const char* mode) { static const char module[] = "TIFFOpen"; int m, fd; TIFF* tif; m = _TIFFgetMode(mode, module); if (m == -1) return ((TIFF*)0); /* for cygwin and mingw */ #ifdef O_BINARY m |= O_BINARY; #endif fd = open(name, m, 0666); if (fd < 0) { if (errno > 0 && strerror(errno) != NULL ) { TIFFErrorExt(0, module, "%s: %s", name, strerror(errno) ); } else { TIFFErrorExt(0, module, "%s: Cannot open", name); } return ((TIFF *)0); } tif = TIFFFdOpen((int)fd, name, mode); if(!tif) close(fd); return tif; } #ifdef __WIN32__ #include <windows.h> /* * Open a TIFF file with a Unicode filename, for read/writing. */ TIFF* TIFFOpenW(const wchar_t* name, const char* mode) { static const char module[] = "TIFFOpenW"; int m, fd; int mbsize; char *mbname; TIFF* tif; m = _TIFFgetMode(mode, module); if (m == -1) return ((TIFF*)0); /* for cygwin and mingw */ #ifdef O_BINARY m |= O_BINARY; #endif fd = _wopen(name, m, 0666); if (fd < 0) { TIFFErrorExt(0, module, "%s: Cannot open", name); return ((TIFF *)0); } mbname = NULL; mbsize = WideCharToMultiByte(CP_ACP, 0, name, -1, NULL, 0, NULL, NULL); if (mbsize > 0) { mbname = _TIFFmalloc(mbsize); if (!mbname) { TIFFErrorExt(0, module, "Can't allocate space for filename conversion buffer"); return ((TIFF*)0); } WideCharToMultiByte(CP_ACP, 0, name, -1, mbname, mbsize, NULL, NULL); } tif = TIFFFdOpen((int)fd, (mbname != NULL) ? mbname : "<unknown>", mode); _TIFFfree(mbname); if(!tif) close(fd); return tif; } #endif void* _TIFFmalloc(tmsize_t s) { return (malloc((size_t) s)); } void _TIFFfree(void* p) { free(p); } void* _TIFFrealloc(void* p, tmsize_t s) { return (realloc(p, (size_t) s)); } void _TIFFmemset(void* p, int v, tmsize_t c) { memset(p, v, (size_t) c); } void _TIFFmemcpy(void* d, const void* s, tmsize_t c) { memcpy(d, s, (size_t) c); } int _TIFFmemcmp(const void* p1, const void* p2, tmsize_t c) { return (memcmp(p1, p2, (size_t) c)); } static void unixWarningHandler(const char* module, const char* fmt, va_list ap) { if (module != NULL) fprintf(stderr, "%s: ", module); fprintf(stderr, "Warning, "); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); } TIFFErrorHandler _TIFFwarningHandler = unixWarningHandler; static void unixErrorHandler(const char* module, const char* fmt, va_list ap) { if (module != NULL) fprintf(stderr, "%s: ", module); vfprintf(stderr, fmt, ap); fprintf(stderr, ".\n"); } TIFFErrorHandler _TIFFerrorHandler = unixErrorHandler; /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-369/c/bad_2303_1
crossvul-cpp_data_good_4277_0
/* * Copyright (c) 2011-2020 Meltytech, LLC * * 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 3 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, see <http://www.gnu.org/licenses/>. */ #include "mainwindow.h" #include "ui_mainwindow.h" #include "scrubbar.h" #include "openotherdialog.h" #include "player.h" #include "widgets/alsawidget.h" #include "widgets/colorbarswidget.h" #include "widgets/colorproducerwidget.h" #include "widgets/countproducerwidget.h" #include "widgets/decklinkproducerwidget.h" #include "widgets/directshowvideowidget.h" #include "widgets/isingwidget.h" #include "widgets/jackproducerwidget.h" #include "widgets/toneproducerwidget.h" #include "widgets/lissajouswidget.h" #include "widgets/networkproducerwidget.h" #include "widgets/noisewidget.h" #include "widgets/plasmawidget.h" #include "widgets/pulseaudiowidget.h" #include "widgets/video4linuxwidget.h" #include "widgets/x11grabwidget.h" #include "widgets/avformatproducerwidget.h" #include "widgets/imageproducerwidget.h" #include "widgets/webvfxproducer.h" #include "widgets/blipproducerwidget.h" #include "widgets/newprojectfolder.h" #include "docks/recentdock.h" #include "docks/encodedock.h" #include "docks/jobsdock.h" #include "jobqueue.h" #include "docks/playlistdock.h" #include "glwidget.h" #include "controllers/filtercontroller.h" #include "controllers/scopecontroller.h" #include "docks/filtersdock.h" #include "dialogs/customprofiledialog.h" #include "htmleditor/htmleditor.h" #include "settings.h" #include "leapnetworklistener.h" #include "database.h" #include "widgets/gltestwidget.h" #include "docks/timelinedock.h" #include "widgets/lumamixtransition.h" #include "qmltypes/qmlutilities.h" #include "qmltypes/qmlapplication.h" #include "autosavefile.h" #include "commands/playlistcommands.h" #include "shotcut_mlt_properties.h" #include "widgets/avfoundationproducerwidget.h" #include "dialogs/textviewerdialog.h" #include "widgets/gdigrabwidget.h" #include "models/audiolevelstask.h" #include "widgets/trackpropertieswidget.h" #include "widgets/timelinepropertieswidget.h" #include "dialogs/unlinkedfilesdialog.h" #include "docks/keyframesdock.h" #include "util.h" #include "models/keyframesmodel.h" #include "dialogs/listselectiondialog.h" #include "widgets/textproducerwidget.h" #include "qmltypes/qmlprofile.h" #include "dialogs/longuitask.h" #include "dialogs/systemsyncdialog.h" #include "proxymanager.h" #include <QtWidgets> #include <Logger.h> #include <QThreadPool> #include <QtConcurrent/QtConcurrentRun> #include <QMutexLocker> #include <QQuickItem> #include <QtNetwork> #include <QJsonDocument> #include <QJSEngine> #include <QDirIterator> #include <QQuickWindow> #include <QVersionNumber> #include <clocale> static bool eventDebugCallback(void **data) { QEvent *event = reinterpret_cast<QEvent*>(data[1]); if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QObject *receiver = reinterpret_cast<QObject*>(data[0]); LOG_DEBUG() << event << "->" << receiver; } else if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease) { QObject *receiver = reinterpret_cast<QObject*>(data[0]); LOG_DEBUG() << event << "->" << receiver; } return false; } static const int AUTOSAVE_TIMEOUT_MS = 60000; MainWindow::MainWindow() : QMainWindow(0) , ui(new Ui::MainWindow) , m_isKKeyPressed(false) , m_keyerGroup(0) , m_previewScaleGroup(0) , m_keyerMenu(0) , m_isPlaylistLoaded(false) , m_exitCode(EXIT_SUCCESS) , m_navigationPosition(0) , m_upgradeUrl("https://www.shotcut.org/download/") , m_keyframesDock(0) { #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) QLibrary libJack("libjack.so.0"); if (!libJack.load()) { QMessageBox::critical(this, qApp->applicationName(), tr("Error: This program requires the JACK 1 library.\n\nPlease install it using your package manager. It may be named libjack0, jack-audio-connection-kit, jack, or similar.")); ::exit(EXIT_FAILURE); } else { libJack.unload(); } QLibrary libSDL("libSDL2-2.0.so.0"); if (!libSDL.load()) { QMessageBox::critical(this, qApp->applicationName(), tr("Error: This program requires the SDL 2 library.\n\nPlease install it using your package manager. It may be named libsdl2-2.0-0, SDL2, or similar.")); ::exit(EXIT_FAILURE); } else { libSDL.unload(); } #endif if (!qgetenv("OBSERVE_FOCUS").isEmpty()) { connect(qApp, &QApplication::focusChanged, this, &MainWindow::onFocusChanged); connect(qApp, &QGuiApplication::focusObjectChanged, this, &MainWindow::onFocusObjectChanged); connect(qApp, &QGuiApplication::focusWindowChanged, this, &MainWindow::onFocusWindowChanged); } if (!qgetenv("EVENT_DEBUG").isEmpty()) QInternal::registerCallback(QInternal::EventNotifyCallback, eventDebugCallback); LOG_DEBUG() << "begin"; #ifndef Q_OS_WIN new GLTestWidget(this); #endif Database::singleton(this); m_autosaveTimer.setSingleShot(true); m_autosaveTimer.setInterval(AUTOSAVE_TIMEOUT_MS); connect(&m_autosaveTimer, SIGNAL(timeout()), this, SLOT(onAutosaveTimeout())); // Initialize all QML types QmlUtilities::registerCommonTypes(); // Create the UI. ui->setupUi(this); #ifdef Q_OS_MAC // Qt 5 on OS X supports the standard Full Screen window widget. ui->mainToolBar->removeAction(ui->actionFullscreen); // OS X has a standard Full Screen shortcut we should use. ui->actionEnter_Full_Screen->setShortcut(QKeySequence((Qt::CTRL + Qt::META + Qt::Key_F))); #endif setDockNestingEnabled(true); ui->statusBar->hide(); // Connect UI signals. connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openVideo())); connect(ui->actionAbout_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(this, SIGNAL(producerOpened()), this, SLOT(onProducerOpened())); if (ui->actionFullscreen) connect(ui->actionFullscreen, SIGNAL(triggered()), this, SLOT(on_actionEnter_Full_Screen_triggered())); connect(ui->mainToolBar, SIGNAL(visibilityChanged(bool)), SLOT(onToolbarVisibilityChanged(bool))); // Accept drag-n-drop of files. this->setAcceptDrops(true); // Setup the undo stack. m_undoStack = new QUndoStack(this); m_undoStack->setUndoLimit(Settings.undoLimit()); QAction *undoAction = m_undoStack->createUndoAction(this); QAction *redoAction = m_undoStack->createRedoAction(this); undoAction->setIcon(QIcon::fromTheme("edit-undo", QIcon(":/icons/oxygen/32x32/actions/edit-undo.png"))); redoAction->setIcon(QIcon::fromTheme("edit-redo", QIcon(":/icons/oxygen/32x32/actions/edit-redo.png"))); undoAction->setShortcut(QApplication::translate("MainWindow", "Ctrl+Z", 0)); #ifdef Q_OS_WIN redoAction->setShortcut(QApplication::translate("MainWindow", "Ctrl+Y", 0)); #else redoAction->setShortcut(QApplication::translate("MainWindow", "Ctrl+Shift+Z", 0)); #endif ui->menuEdit->insertAction(ui->actionCut, undoAction); ui->menuEdit->insertAction(ui->actionCut, redoAction); ui->menuEdit->insertSeparator(ui->actionCut); ui->actionUndo->setIcon(undoAction->icon()); ui->actionRedo->setIcon(redoAction->icon()); ui->actionUndo->setToolTip(undoAction->toolTip()); ui->actionRedo->setToolTip(redoAction->toolTip()); connect(m_undoStack, SIGNAL(canUndoChanged(bool)), ui->actionUndo, SLOT(setEnabled(bool))); connect(m_undoStack, SIGNAL(canRedoChanged(bool)), ui->actionRedo, SLOT(setEnabled(bool))); // Add the player widget. m_player = new Player; MLT.videoWidget()->installEventFilter(this); ui->centralWidget->layout()->addWidget(m_player); connect(this, SIGNAL(producerOpened()), m_player, SLOT(onProducerOpened())); connect(m_player, SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_player, SIGNAL(inChanged(int)), this, SLOT(onCutModified())); connect(m_player, SIGNAL(outChanged(int)), this, SLOT(onCutModified())); connect(m_player, SIGNAL(tabIndexChanged(int)), SLOT(onPlayerTabIndexChanged(int))); connect(MLT.videoWidget(), SIGNAL(started()), SLOT(processMultipleFiles())); connect(MLT.videoWidget(), SIGNAL(paused()), m_player, SLOT(showPaused())); connect(MLT.videoWidget(), SIGNAL(playing()), m_player, SLOT(showPlaying())); connect(MLT.videoWidget(), SIGNAL(toggleZoom(bool)), m_player, SLOT(toggleZoom(bool))); setupSettingsMenu(); setupOpenOtherMenu(); readPlayerSettings(); configureVideoWidget(); #ifndef SHOTCUT_NOUPGRADE if (Settings.noUpgrade() || qApp->property("noupgrade").toBool()) #endif delete ui->actionUpgrade; // Add the docks. m_scopeController = new ScopeController(this, ui->menuView); QDockWidget* audioMeterDock = findChild<QDockWidget*>("AudioPeakMeterDock"); if (audioMeterDock) { audioMeterDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1)); connect(ui->actionAudioMeter, SIGNAL(triggered()), audioMeterDock->toggleViewAction(), SLOT(trigger())); } m_propertiesDock = new QDockWidget(tr("Properties"), this); m_propertiesDock->hide(); m_propertiesDock->setObjectName("propertiesDock"); m_propertiesDock->setWindowIcon(ui->actionProperties->icon()); m_propertiesDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2)); m_propertiesDock->toggleViewAction()->setIcon(ui->actionProperties->icon()); m_propertiesDock->setMinimumWidth(300); QScrollArea* scroll = new QScrollArea; scroll->setWidgetResizable(true); m_propertiesDock->setWidget(scroll); addDockWidget(Qt::LeftDockWidgetArea, m_propertiesDock); ui->menuView->addAction(m_propertiesDock->toggleViewAction()); connect(m_propertiesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onPropertiesDockTriggered(bool))); connect(ui->actionProperties, SIGNAL(triggered()), this, SLOT(onPropertiesDockTriggered())); m_recentDock = new RecentDock(this); m_recentDock->hide(); addDockWidget(Qt::RightDockWidgetArea, m_recentDock); m_recentDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_3)); ui->menuView->addAction(m_recentDock->toggleViewAction()); connect(m_recentDock, SIGNAL(itemActivated(QString)), this, SLOT(open(QString))); connect(m_recentDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onRecentDockTriggered(bool))); connect(ui->actionRecent, SIGNAL(triggered()), this, SLOT(onRecentDockTriggered())); connect(this, SIGNAL(openFailed(QString)), m_recentDock, SLOT(remove(QString))); connect(m_recentDock, &RecentDock::deleted, m_player->projectWidget(), &NewProjectFolder::updateRecentProjects); m_playlistDock = new PlaylistDock(this); m_playlistDock->hide(); addDockWidget(Qt::LeftDockWidgetArea, m_playlistDock); m_playlistDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_4)); ui->menuView->addAction(m_playlistDock->toggleViewAction()); connect(m_playlistDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onPlaylistDockTriggered(bool))); connect(ui->actionPlaylist, SIGNAL(triggered()), this, SLOT(onPlaylistDockTriggered())); connect(m_playlistDock, SIGNAL(clipOpened(Mlt::Producer*, bool)), this, SLOT(openCut(Mlt::Producer*, bool))); connect(m_playlistDock, SIGNAL(itemActivated(int)), this, SLOT(seekPlaylist(int))); connect(m_playlistDock, SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_playlistDock->model(), SIGNAL(created()), this, SLOT(onPlaylistCreated())); connect(m_playlistDock->model(), SIGNAL(cleared()), this, SLOT(onPlaylistCleared())); connect(m_playlistDock->model(), SIGNAL(cleared()), this, SLOT(updateAutoSave())); connect(m_playlistDock->model(), SIGNAL(closed()), this, SLOT(onPlaylistClosed())); connect(m_playlistDock->model(), SIGNAL(modified()), this, SLOT(onPlaylistModified())); connect(m_playlistDock->model(), SIGNAL(modified()), this, SLOT(updateAutoSave())); connect(m_playlistDock->model(), SIGNAL(loaded()), this, SLOT(onPlaylistLoaded())); connect(this, SIGNAL(producerOpened()), m_playlistDock, SLOT(onProducerOpened())); if (!Settings.playerGPU()) connect(m_playlistDock->model(), SIGNAL(loaded()), this, SLOT(updateThumbnails())); connect(m_player, &Player::inChanged, m_playlistDock, &PlaylistDock::onInChanged); connect(m_player, &Player::outChanged, m_playlistDock, &PlaylistDock::onOutChanged); connect(m_playlistDock->model(), &PlaylistModel::inChanged, this, &MainWindow::onPlaylistInChanged); connect(m_playlistDock->model(), &PlaylistModel::outChanged, this, &MainWindow::onPlaylistOutChanged); m_timelineDock = new TimelineDock(this); m_timelineDock->hide(); addDockWidget(Qt::BottomDockWidgetArea, m_timelineDock); m_timelineDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_5)); ui->menuView->addAction(m_timelineDock->toggleViewAction()); connect(m_timelineDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onTimelineDockTriggered(bool))); connect(ui->actionTimeline, SIGNAL(triggered()), SLOT(onTimelineDockTriggered())); connect(m_player, SIGNAL(seeked(int)), m_timelineDock, SLOT(onSeeked(int))); connect(m_timelineDock, SIGNAL(seeked(int)), SLOT(seekTimeline(int))); connect(m_timelineDock, SIGNAL(clipClicked()), SLOT(onTimelineClipSelected())); connect(m_timelineDock, SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_timelineDock->model(), SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_timelineDock->model(), SIGNAL(created()), SLOT(onMultitrackCreated())); connect(m_timelineDock->model(), SIGNAL(closed()), SLOT(onMultitrackClosed())); connect(m_timelineDock->model(), SIGNAL(modified()), SLOT(onMultitrackModified())); connect(m_timelineDock->model(), SIGNAL(modified()), SLOT(updateAutoSave())); connect(m_timelineDock->model(), SIGNAL(durationChanged()), SLOT(onMultitrackDurationChanged())); connect(m_timelineDock, SIGNAL(clipOpened(Mlt::Producer*)), SLOT(openCut(Mlt::Producer*))); connect(m_timelineDock->model(), &MultitrackModel::seeked, this, &MainWindow::seekTimeline); connect(m_timelineDock->model(), SIGNAL(scaleFactorChanged()), m_player, SLOT(pause())); connect(m_timelineDock, SIGNAL(selected(Mlt::Producer*)), SLOT(loadProducerWidget(Mlt::Producer*))); connect(m_timelineDock, SIGNAL(selectionChanged()), SLOT(onTimelineSelectionChanged())); connect(m_timelineDock, SIGNAL(clipCopied()), SLOT(onClipCopied())); connect(m_timelineDock, SIGNAL(filteredClicked()), SLOT(onFiltersDockTriggered())); connect(m_playlistDock, SIGNAL(addAllTimeline(Mlt::Playlist*)), SLOT(onTimelineDockTriggered())); connect(m_playlistDock, SIGNAL(addAllTimeline(Mlt::Playlist*, bool)), SLOT(onAddAllToTimeline(Mlt::Playlist*, bool))); connect(m_player, SIGNAL(previousSought()), m_timelineDock, SLOT(seekPreviousEdit())); connect(m_player, SIGNAL(nextSought()), m_timelineDock, SLOT(seekNextEdit())); m_filterController = new FilterController(this); m_filtersDock = new FiltersDock(m_filterController->metadataModel(), m_filterController->attachedModel(), this); m_filtersDock->setMinimumSize(400, 300); m_filtersDock->hide(); addDockWidget(Qt::LeftDockWidgetArea, m_filtersDock); m_filtersDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_6)); ui->menuView->addAction(m_filtersDock->toggleViewAction()); connect(m_filtersDock, SIGNAL(currentFilterRequested(int)), m_filterController, SLOT(setCurrentFilter(int)), Qt::QueuedConnection); connect(m_filtersDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onFiltersDockTriggered(bool))); connect(ui->actionFilters, SIGNAL(triggered()), this, SLOT(onFiltersDockTriggered())); connect(m_filterController, SIGNAL(currentFilterChanged(QmlFilter*, QmlMetadata*, int)), m_filtersDock, SLOT(setCurrentFilter(QmlFilter*, QmlMetadata*, int))); connect(this, SIGNAL(producerOpened()), m_filterController, SLOT(setProducer())); connect(m_filterController->attachedModel(), SIGNAL(changed()), SLOT(onFilterModelChanged())); connect(m_filtersDock, SIGNAL(changed()), SLOT(onFilterModelChanged())); connect(m_filterController, SIGNAL(filterChanged(Mlt::Filter*)), m_timelineDock->model(), SLOT(onFilterChanged(Mlt::Filter*))); connect(m_filterController->attachedModel(), SIGNAL(addedOrRemoved(Mlt::Producer*)), m_timelineDock->model(), SLOT(filterAddedOrRemoved(Mlt::Producer*))); connect(&QmlApplication::singleton(), SIGNAL(filtersPasted(Mlt::Producer*)), m_timelineDock->model(), SLOT(filterAddedOrRemoved(Mlt::Producer*))); connect(&QmlApplication::singleton(), &QmlApplication::filtersPasted, this, &MainWindow::onProducerModified); connect(m_filterController, SIGNAL(statusChanged(QString)), this, SLOT(showStatusMessage(QString))); connect(m_timelineDock, SIGNAL(fadeInChanged(int)), m_filterController, SLOT(onFadeInChanged())); connect(m_timelineDock, SIGNAL(fadeOutChanged(int)), m_filterController, SLOT(onFadeOutChanged())); connect(m_timelineDock, SIGNAL(selected(Mlt::Producer*)), m_filterController, SLOT(setProducer(Mlt::Producer*))); connect(m_player, SIGNAL(seeked(int)), m_filtersDock, SLOT(onSeeked(int)), Qt::QueuedConnection); connect(m_filtersDock, SIGNAL(seeked(int)), SLOT(seekKeyframes(int))); connect(MLT.videoWidget(), SIGNAL(frameDisplayed(const SharedFrame&)), m_filtersDock, SLOT(onShowFrame(const SharedFrame&))); connect(m_player, SIGNAL(inChanged(int)), m_filtersDock, SIGNAL(producerInChanged(int))); connect(m_player, SIGNAL(outChanged(int)), m_filtersDock, SIGNAL(producerOutChanged(int))); connect(m_player, SIGNAL(inChanged(int)), m_filterController, SLOT(onFilterInChanged(int))); connect(m_player, SIGNAL(outChanged(int)), m_filterController, SLOT(onFilterOutChanged(int))); connect(m_timelineDock->model(), SIGNAL(filterInChanged(int, Mlt::Filter*)), m_filterController, SLOT(onFilterInChanged(int, Mlt::Filter*))); connect(m_timelineDock->model(), SIGNAL(filterOutChanged(int, Mlt::Filter*)), m_filterController, SLOT(onFilterOutChanged(int, Mlt::Filter*))); m_keyframesDock = new KeyframesDock(m_filtersDock->qmlProducer(), this); m_keyframesDock->hide(); addDockWidget(Qt::BottomDockWidgetArea, m_keyframesDock); m_keyframesDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_7)); ui->menuView->addAction(m_keyframesDock->toggleViewAction()); connect(m_keyframesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onKeyframesDockTriggered(bool))); connect(ui->actionKeyframes, SIGNAL(triggered()), this, SLOT(onKeyframesDockTriggered())); connect(m_filterController, SIGNAL(currentFilterChanged(QmlFilter*, QmlMetadata*, int)), m_keyframesDock, SLOT(setCurrentFilter(QmlFilter*, QmlMetadata*))); connect(m_keyframesDock, SIGNAL(visibilityChanged(bool)), m_filtersDock->qmlProducer(), SLOT(remakeAudioLevels(bool))); m_historyDock = new QDockWidget(tr("History"), this); m_historyDock->hide(); m_historyDock->setObjectName("historyDock"); m_historyDock->setWindowIcon(ui->actionHistory->icon()); m_historyDock->toggleViewAction()->setIcon(ui->actionHistory->icon()); m_historyDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_8)); m_historyDock->setMinimumWidth(150); addDockWidget(Qt::RightDockWidgetArea, m_historyDock); ui->menuView->addAction(m_historyDock->toggleViewAction()); connect(m_historyDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onHistoryDockTriggered(bool))); connect(ui->actionHistory, SIGNAL(triggered()), this, SLOT(onHistoryDockTriggered())); QUndoView* undoView = new QUndoView(m_undoStack, m_historyDock); undoView->setObjectName("historyView"); undoView->setAlternatingRowColors(true); undoView->setSpacing(2); m_historyDock->setWidget(undoView); ui->actionUndo->setDisabled(true); ui->actionRedo->setDisabled(true); m_encodeDock = new EncodeDock(this); m_encodeDock->hide(); addDockWidget(Qt::LeftDockWidgetArea, m_encodeDock); m_encodeDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_9)); ui->menuView->addAction(m_encodeDock->toggleViewAction()); connect(this, SIGNAL(producerOpened()), m_encodeDock, SLOT(onProducerOpened())); connect(ui->actionEncode, SIGNAL(triggered()), this, SLOT(onEncodeTriggered())); connect(ui->actionExportVideo, SIGNAL(triggered()), this, SLOT(onEncodeTriggered())); connect(m_encodeDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onEncodeTriggered(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_player, SLOT(onCaptureStateChanged(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_propertiesDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_recentDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_filtersDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_keyframesDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionOpen, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionOpenOther, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionExit, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), this, SLOT(onCaptureStateChanged(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_historyDock, SLOT(setDisabled(bool))); connect(this, SIGNAL(profileChanged()), m_encodeDock, SLOT(onProfileChanged())); connect(this, SIGNAL(profileChanged()), SLOT(onProfileChanged())); connect(this, SIGNAL(profileChanged()), &QmlProfile::singleton(), SIGNAL(profileChanged())); connect(this, SIGNAL(audioChannelsChanged()), m_encodeDock, SLOT(onAudioChannelsChanged())); connect(m_playlistDock->model(), SIGNAL(modified()), m_encodeDock, SLOT(onProducerOpened())); connect(m_timelineDock, SIGNAL(clipCopied()), m_encodeDock, SLOT(onProducerOpened())); m_encodeDock->onProfileChanged(); m_jobsDock = new JobsDock(this); m_jobsDock->hide(); addDockWidget(Qt::RightDockWidgetArea, m_jobsDock); m_jobsDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0)); ui->menuView->addAction(m_jobsDock->toggleViewAction()); connect(&JOBS, SIGNAL(jobAdded()), m_jobsDock, SLOT(onJobAdded())); connect(m_jobsDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onJobsDockTriggered(bool))); connect(ui->actionJobs, SIGNAL(triggered()), this, SLOT(onJobsDockTriggered())); tabifyDockWidget(m_propertiesDock, m_playlistDock); tabifyDockWidget(m_playlistDock, m_filtersDock); tabifyDockWidget(m_filtersDock, m_encodeDock); QDockWidget* audioWaveformDock = findChild<QDockWidget*>("AudioWaveformDock"); splitDockWidget(m_recentDock, audioWaveformDock, Qt::Vertical); splitDockWidget(audioMeterDock, m_recentDock, Qt::Horizontal); tabifyDockWidget(m_recentDock, m_historyDock); tabifyDockWidget(m_historyDock, m_jobsDock); tabifyDockWidget(m_keyframesDock, m_timelineDock); m_recentDock->raise(); // Configure the View menu. ui->menuView->addSeparator(); ui->menuView->addAction(ui->actionApplicationLog); // connect video widget signals Mlt::GLWidget* videoWidget = (Mlt::GLWidget*) &(MLT); connect(videoWidget, SIGNAL(dragStarted()), m_playlistDock, SLOT(onPlayerDragStarted())); connect(videoWidget, SIGNAL(seekTo(int)), m_player, SLOT(seek(int))); connect(videoWidget, SIGNAL(gpuNotSupported()), this, SLOT(onGpuNotSupported())); connect(videoWidget->quickWindow(), SIGNAL(sceneGraphInitialized()), SLOT(onSceneGraphInitialized()), Qt::QueuedConnection); connect(videoWidget, SIGNAL(frameDisplayed(const SharedFrame&)), m_scopeController, SIGNAL(newFrame(const SharedFrame&))); connect(m_filterController, SIGNAL(currentFilterChanged(QmlFilter*, QmlMetadata*, int)), videoWidget, SLOT(setCurrentFilter(QmlFilter*, QmlMetadata*))); readWindowSettings(); setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea); setDockNestingEnabled(true); setFocus(); setCurrentFile(""); LeapNetworkListener* leap = new LeapNetworkListener(this); connect(leap, SIGNAL(shuttle(float)), SLOT(onShuttle(float))); connect(leap, SIGNAL(jogRightFrame()), SLOT(stepRightOneFrame())); connect(leap, SIGNAL(jogRightSecond()), SLOT(stepRightOneSecond())); connect(leap, SIGNAL(jogLeftFrame()), SLOT(stepLeftOneFrame())); connect(leap, SIGNAL(jogLeftSecond()), SLOT(stepLeftOneSecond())); connect(&m_network, SIGNAL(finished(QNetworkReply*)), SLOT(onUpgradeCheckFinished(QNetworkReply*))); QThreadPool::globalInstance()->setMaxThreadCount(qMin(4, QThreadPool::globalInstance()->maxThreadCount())); ProxyManager::removePending(); LOG_DEBUG() << "end"; } void MainWindow::onFocusWindowChanged(QWindow *) const { LOG_DEBUG() << "Focuswindow changed"; LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); } void MainWindow::onFocusObjectChanged(QObject *) const { LOG_DEBUG() << "Focusobject changed"; LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); } void MainWindow::onTimelineClipSelected() { // Synchronize navigation position with timeline selection. TimelineDock * t = m_timelineDock; if (t->selection().isEmpty()) return; m_navigationPosition = t->centerOfClip(t->selection().first().y(), t->selection().first().x()); // Switch to Project player. if (m_player->tabIndex() != Player::ProjectTabIndex) { t->saveAndClearSelection(); m_player->onTabBarClicked(Player::ProjectTabIndex); } } void MainWindow::onAddAllToTimeline(Mlt::Playlist* playlist, bool skipProxy) { // We stop the player because of a bug on Windows that results in some // strange memory leak when using Add All To Timeline, more noticeable // with (high res?) still image files. if (MLT.isSeekable()) m_player->pause(); else m_player->stop(); m_timelineDock->appendFromPlaylist(playlist, skipProxy); } MainWindow& MainWindow::singleton() { static MainWindow* instance = new MainWindow; return *instance; } MainWindow::~MainWindow() { delete ui; Mlt::Controller::destroy(); } void MainWindow::setupSettingsMenu() { LOG_DEBUG() << "begin"; QActionGroup* group = new QActionGroup(this); group->addAction(ui->actionChannels1); group->addAction(ui->actionChannels2); group->addAction(ui->actionChannels6); group = new QActionGroup(this); group->addAction(ui->actionOneField); group->addAction(ui->actionLinearBlend); #if LIBMLT_VERSION_INT >= MLT_VERSION_PREVIEW_SCALE m_previewScaleGroup = new QActionGroup(this); m_previewScaleGroup->addAction(ui->actionPreviewNone); m_previewScaleGroup->addAction(ui->actionPreview360); m_previewScaleGroup->addAction(ui->actionPreview540); m_previewScaleGroup->addAction(ui->actionPreview720); #else delete ui->menuPreviewScaling; #endif //XXX workaround yadif crashing with mlt_transition // group->addAction(ui->actionYadifTemporal); // group->addAction(ui->actionYadifSpatial); ui->actionYadifTemporal->setVisible(false); ui->actionYadifSpatial->setVisible(false); group = new QActionGroup(this); group->addAction(ui->actionNearest); group->addAction(ui->actionBilinear); group->addAction(ui->actionBicubic); group->addAction(ui->actionHyper); if (Settings.playerGPU()) { group = new QActionGroup(this); group->addAction(ui->actionGammaRec709); group->addAction(ui->actionGammaSRGB); } else { delete ui->menuGamma; } m_profileGroup = new QActionGroup(this); m_profileGroup->addAction(ui->actionProfileAutomatic); ui->actionProfileAutomatic->setData(QString()); buildVideoModeMenu(ui->menuProfile, m_customProfileMenu, m_profileGroup, ui->actionAddCustomProfile, ui->actionProfileRemove); // Add the SDI and HDMI devices to the Settings menu. m_externalGroup = new QActionGroup(this); ui->actionExternalNone->setData(QString()); m_externalGroup->addAction(ui->actionExternalNone); QList<QScreen*> screens = QGuiApplication::screens(); int n = screens.size(); for (int i = 0; n > 1 && i < n; i++) { QAction* action = new QAction(tr("Screen %1 (%2 x %3 @ %4 Hz)").arg(i) .arg(screens[i]->size().width() * screens[i]->devicePixelRatio()) .arg(screens[i]->size().height() * screens[i]->devicePixelRatio()) .arg(screens[i]->refreshRate()), this); action->setCheckable(true); action->setData(i); m_externalGroup->addAction(action); } Mlt::Profile profile; Mlt::Consumer decklink(profile, "decklink:"); if (decklink.is_valid()) { decklink.set("list_devices", 1); int n = decklink.get_int("devices"); for (int i = 0; i < n; ++i) { QString device(decklink.get(QString("device.%1").arg(i).toLatin1().constData())); if (!device.isEmpty()) { QAction* action = new QAction(device, this); action->setCheckable(true); action->setData(QString("decklink:%1").arg(i)); m_externalGroup->addAction(action); if (!m_keyerGroup) { m_keyerGroup = new QActionGroup(this); action = new QAction(tr("Off"), m_keyerGroup); action->setData(QVariant(0)); action->setCheckable(true); action = new QAction(tr("Internal"), m_keyerGroup); action->setData(QVariant(1)); action->setCheckable(true); action = new QAction(tr("External"), m_keyerGroup); action->setData(QVariant(2)); action->setCheckable(true); } } } } if (m_externalGroup->actions().count() > 1) ui->menuExternal->addActions(m_externalGroup->actions()); else { delete ui->menuExternal; ui->menuExternal = 0; } if (m_keyerGroup) { m_keyerMenu = ui->menuExternal->addMenu(tr("DeckLink Keyer")); m_keyerMenu->addActions(m_keyerGroup->actions()); m_keyerMenu->setDisabled(true); connect(m_keyerGroup, SIGNAL(triggered(QAction*)), this, SLOT(onKeyerTriggered(QAction*))); } connect(m_externalGroup, SIGNAL(triggered(QAction*)), this, SLOT(onExternalTriggered(QAction*))); connect(m_profileGroup, SIGNAL(triggered(QAction*)), this, SLOT(onProfileTriggered(QAction*))); // Setup the language menu actions m_languagesGroup = new QActionGroup(this); QAction* a; a = new QAction(QLocale::languageToString(QLocale::Arabic), m_languagesGroup); a->setCheckable(true); a->setData("ar"); a = new QAction(QLocale::languageToString(QLocale::Catalan), m_languagesGroup); a->setCheckable(true); a->setData("ca"); a = new QAction(QLocale::languageToString(QLocale::Chinese).append(" (China)"), m_languagesGroup); a->setCheckable(true); a->setData("zh_CN"); a = new QAction(QLocale::languageToString(QLocale::Chinese).append(" (Taiwan)"), m_languagesGroup); a->setCheckable(true); a->setData("zh_TW"); a = new QAction(QLocale::languageToString(QLocale::Czech), m_languagesGroup); a->setCheckable(true); a->setData("cs"); a = new QAction(QLocale::languageToString(QLocale::Danish), m_languagesGroup); a->setCheckable(true); a->setData("da"); a = new QAction(QLocale::languageToString(QLocale::Dutch), m_languagesGroup); a->setCheckable(true); a->setData("nl"); a = new QAction(QLocale::languageToString(QLocale::English).append(" (Great Britain)"), m_languagesGroup); a->setCheckable(true); a->setData("en_GB"); a = new QAction(QLocale::languageToString(QLocale::English).append(" (United States)"), m_languagesGroup); a->setCheckable(true); a->setData("en_US"); a = new QAction(QLocale::languageToString(QLocale::Estonian), m_languagesGroup); a->setCheckable(true); a->setData("et"); a = new QAction(QLocale::languageToString(QLocale::Finnish), m_languagesGroup); a->setCheckable(true); a->setData("fi"); a = new QAction(QLocale::languageToString(QLocale::French), m_languagesGroup); a->setCheckable(true); a->setData("fr"); a = new QAction(QLocale::languageToString(QLocale::Gaelic), m_languagesGroup); a->setCheckable(true); a->setData("gd"); a = new QAction(QLocale::languageToString(QLocale::Galician), m_languagesGroup); a->setCheckable(true); a->setData("gl"); a = new QAction(QLocale::languageToString(QLocale::German), m_languagesGroup); a->setCheckable(true); a->setData("de"); a = new QAction(QLocale::languageToString(QLocale::Greek), m_languagesGroup); a->setCheckable(true); a->setData("el"); a = new QAction(QLocale::languageToString(QLocale::Hungarian), m_languagesGroup); a->setCheckable(true); a->setData("hu"); a = new QAction(QLocale::languageToString(QLocale::Italian), m_languagesGroup); a->setCheckable(true); a->setData("it"); a = new QAction(QLocale::languageToString(QLocale::Japanese), m_languagesGroup); a->setCheckable(true); a->setData("ja"); a = new QAction(QLocale::languageToString(QLocale::Korean), m_languagesGroup); a->setCheckable(true); a->setData("ko"); a = new QAction(QLocale::languageToString(QLocale::Nepali), m_languagesGroup); a->setCheckable(true); a->setData("ne"); a = new QAction(QLocale::languageToString(QLocale::NorwegianBokmal), m_languagesGroup); a->setCheckable(true); a->setData("nb"); a = new QAction(QLocale::languageToString(QLocale::NorwegianNynorsk), m_languagesGroup); a->setCheckable(true); a->setData("nn"); a = new QAction(QLocale::languageToString(QLocale::Occitan), m_languagesGroup); a->setCheckable(true); a->setData("oc"); a = new QAction(QLocale::languageToString(QLocale::Polish), m_languagesGroup); a->setCheckable(true); a->setData("pl"); a = new QAction(QLocale::languageToString(QLocale::Portuguese).append(" (Brazil)"), m_languagesGroup); a->setCheckable(true); a->setData("pt_BR"); a = new QAction(QLocale::languageToString(QLocale::Portuguese).append(" (Portugal)"), m_languagesGroup); a->setCheckable(true); a->setData("pt_PT"); a = new QAction(QLocale::languageToString(QLocale::Russian), m_languagesGroup); a->setCheckable(true); a->setData("ru"); a = new QAction(QLocale::languageToString(QLocale::Slovak), m_languagesGroup); a->setCheckable(true); a->setData("sk"); a = new QAction(QLocale::languageToString(QLocale::Slovenian), m_languagesGroup); a->setCheckable(true); a->setData("sl"); a = new QAction(QLocale::languageToString(QLocale::Spanish), m_languagesGroup); a->setCheckable(true); a->setData("es"); a = new QAction(QLocale::languageToString(QLocale::Swedish), m_languagesGroup); a->setCheckable(true); a->setData("sv"); a = new QAction(QLocale::languageToString(QLocale::Thai), m_languagesGroup); a->setCheckable(true); a->setData("th"); a = new QAction(QLocale::languageToString(QLocale::Turkish), m_languagesGroup); a->setCheckable(true); a->setData("tr"); a = new QAction(QLocale::languageToString(QLocale::Ukrainian), m_languagesGroup); a->setCheckable(true); a->setData("uk"); ui->menuLanguage->addActions(m_languagesGroup->actions()); const QString locale = Settings.language(); foreach (QAction* action, m_languagesGroup->actions()) { if (action->data().toString().startsWith(locale)) { action->setChecked(true); break; } } connect(m_languagesGroup, SIGNAL(triggered(QAction*)), this, SLOT(onLanguageTriggered(QAction*))); // Setup the themes actions group = new QActionGroup(this); group->addAction(ui->actionSystemTheme); group->addAction(ui->actionFusionDark); group->addAction(ui->actionFusionLight); if (Settings.theme() == "dark") ui->actionFusionDark->setChecked(true); else if (Settings.theme() == "light") ui->actionFusionLight->setChecked(true); else ui->actionSystemTheme->setChecked(true); #ifdef Q_OS_WIN // On Windows, if there is no JACK or it is not running // then Shotcut crashes inside MLT's call to jack_client_open(). // Therefore, the JACK option for Shotcut is banned on Windows. delete ui->actionJack; ui->actionJack = 0; #endif #if !defined(Q_OS_MAC) // Setup the display method actions. if (!Settings.playerGPU()) { group = new QActionGroup(this); #if defined(Q_OS_WIN) ui->actionDrawingAutomatic->setData(0); group->addAction(ui->actionDrawingAutomatic); ui->actionDrawingDirectX->setData(Qt::AA_UseOpenGLES); group->addAction(ui->actionDrawingDirectX); #else delete ui->actionDrawingAutomatic; delete ui->actionDrawingDirectX; #endif ui->actionDrawingOpenGL->setData(Qt::AA_UseDesktopOpenGL); group->addAction(ui->actionDrawingOpenGL); ui->actionDrawingSoftware->setData(Qt::AA_UseSoftwareOpenGL); group->addAction(ui->actionDrawingSoftware); connect(group, SIGNAL(triggered(QAction*)), this, SLOT(onDrawingMethodTriggered(QAction*))); switch (Settings.drawMethod()) { case Qt::AA_UseDesktopOpenGL: ui->actionDrawingOpenGL->setChecked(true); break; #if defined(Q_OS_WIN) case Qt::AA_UseOpenGLES: ui->actionDrawingDirectX->setChecked(true); break; #endif case Qt::AA_UseSoftwareOpenGL: ui->actionDrawingSoftware->setChecked(true); break; #if defined(Q_OS_WIN) default: ui->actionDrawingAutomatic->setChecked(true); break; #else default: ui->actionDrawingOpenGL->setChecked(true); break; #endif } } else { // GPU mode only works with OpenGL. delete ui->menuDrawingMethod; ui->menuDrawingMethod = 0; } #else // Q_OS_MAC delete ui->menuDrawingMethod; ui->menuDrawingMethod = 0; #endif // Add custom layouts to View > Layout submenu. m_layoutGroup = new QActionGroup(this); connect(m_layoutGroup, SIGNAL(triggered(QAction*)), SLOT(onLayoutTriggered(QAction*))); if (Settings.layouts().size() > 0) { ui->menuLayout->addAction(ui->actionLayoutRemove); ui->menuLayout->addSeparator(); } foreach (QString name, Settings.layouts()) ui->menuLayout->addAction(addLayout(m_layoutGroup, name)); if (qApp->property("clearRecent").toBool()) { ui->actionClearRecentOnExit->setVisible(false); Settings.setRecent(QStringList()); Settings.setClearRecent(true); } else { ui->actionClearRecentOnExit->setChecked(Settings.clearRecent()); } // Initialze the proxy submenu ui->actionUseProxy->setChecked(Settings.proxyEnabled()); ui->actionProxyUseProjectFolder->setChecked(Settings.proxyUseProjectFolder()); ui->actionProxyUseHardware->setChecked(Settings.proxyUseHardware()); LOG_DEBUG() << "end"; } void MainWindow::setupOpenOtherMenu() { // Open Other toolbar menu button QScopedPointer<Mlt::Properties> mltProducers(MLT.repository()->producers()); QScopedPointer<Mlt::Properties> mltFilters(MLT.repository()->filters()); QMenu* otherMenu = new QMenu(this); ui->actionOpenOther2->setMenu(otherMenu); // populate the generators if (mltProducers->get_data("color")) { otherMenu->addAction(tr("Color"), this, SLOT(onOpenOtherTriggered()))->setObjectName("color"); if (!Settings.playerGPU() && mltProducers->get_data("qtext") && mltFilters->get_data("dynamictext")) otherMenu->addAction(tr("Text"), this, SLOT(onOpenOtherTriggered()))->setObjectName("text"); } if (mltProducers->get_data("noise")) otherMenu->addAction(tr("Noise"), this, SLOT(onOpenOtherTriggered()))->setObjectName("noise"); if (mltProducers->get_data("frei0r.ising0r")) otherMenu->addAction(tr("Ising"), this, SLOT(onOpenOtherTriggered()))->setObjectName("ising0r"); if (mltProducers->get_data("frei0r.lissajous0r")) otherMenu->addAction(tr("Lissajous"), this, SLOT(onOpenOtherTriggered()))->setObjectName("lissajous0r"); if (mltProducers->get_data("frei0r.plasma")) otherMenu->addAction(tr("Plasma"), this, SLOT(onOpenOtherTriggered()))->setObjectName("plasma"); if (mltProducers->get_data("frei0r.test_pat_B")) otherMenu->addAction(tr("Color Bars"), this, SLOT(onOpenOtherTriggered()))->setObjectName("test_pat_B"); if (mltProducers->get_data("tone")) otherMenu->addAction(tr("Audio Tone"), this, SLOT(onOpenOtherTriggered()))->setObjectName("tone"); if (mltProducers->get_data("count")) otherMenu->addAction(tr("Count"), this, SLOT(onOpenOtherTriggered()))->setObjectName("count"); if (mltProducers->get_data("blipflash")) otherMenu->addAction(tr("Blip Flash"), this, SLOT(onOpenOtherTriggered()))->setObjectName("blipflash"); #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) otherMenu->addAction(tr("Video4Linux"), this, SLOT(onOpenOtherTriggered()))->setObjectName("v4l2"); otherMenu->addAction(tr("PulseAudio"), this, SLOT(onOpenOtherTriggered()))->setObjectName("pulse"); otherMenu->addAction(tr("JACK Audio"), this, SLOT(onOpenOtherTriggered()))->setObjectName("jack"); otherMenu->addAction(tr("ALSA Audio"), this, SLOT(onOpenOtherTriggered()))->setObjectName("alsa"); #elif defined(Q_OS_WIN) || defined(Q_OS_MAC) otherMenu->addAction(tr("Audio/Video Device"), this, SLOT(onOpenOtherTriggered()))->setObjectName("device"); #endif if (mltProducers->get_data("decklink")) otherMenu->addAction(tr("SDI/HDMI"), this, SLOT(onOpenOtherTriggered()))->setObjectName("decklink"); } QAction* MainWindow::addProfile(QActionGroup* actionGroup, const QString& desc, const QString& name) { QAction* action = new QAction(desc, this); action->setCheckable(true); action->setData(name); actionGroup->addAction(action); return action; } QAction*MainWindow::addLayout(QActionGroup* actionGroup, const QString& name) { QAction* action = new QAction(name, this); actionGroup->addAction(action); return action; } void MainWindow::open(Mlt::Producer* producer) { if (!producer->is_valid()) showStatusMessage(tr("Failed to open ")); else if (producer->get_int("error")) showStatusMessage(tr("Failed to open ") + producer->get("resource")); bool ok = false; int screen = Settings.playerExternal().toInt(&ok); if (ok && screen != QApplication::desktop()->screenNumber(this)) m_player->moveVideoToScreen(screen); // no else here because open() will delete the producer if open fails if (!MLT.setProducer(producer)) { emit producerOpened(); if (!MLT.profile().is_explicit() || MLT.URL().endsWith(".mlt") || MLT.URL().endsWith(".xml")) emit profileChanged(); } m_player->setFocus(); m_playlistDock->setUpdateButtonEnabled(false); // Needed on Windows. Upon first file open, window is deactivated, perhaps OpenGL-related. activateWindow(); } bool MainWindow::isCompatibleWithGpuMode(MltXmlChecker& checker) { if (checker.needsGPU() && !Settings.playerGPU() && Settings.playerWarnGPU()) { LOG_INFO() << "file uses GPU but GPU not enabled"; QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("The file you opened uses GPU effects, but GPU effects are not enabled.\n\n" "GPU effects are EXPERIMENTAL, UNSTABLE and UNSUPPORTED! Unsupported means do not report bugs about it.\n\n" "Do you want to enable GPU effects and restart?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); int r = dialog.exec(); if (r == QMessageBox::Yes) { ui->actionGPU->setChecked(true); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } return false; } else if (checker.needsCPU() && Settings.playerGPU()) { LOG_INFO() << "file uses GPU incompatible filters but GPU is enabled"; QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("The file you opened uses CPU effects that are incompatible with GPU effects, but GPU effects are enabled.\n" "Do you want to disable GPU effects and restart?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); int r = dialog.exec(); if (r == QMessageBox::Yes) { ui->actionGPU->setChecked(false); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } return false; } return true; } bool MainWindow::saveRepairedXmlFile(MltXmlChecker& checker, QString& fileName) { QFileInfo fi(fileName); QFile repaired(QString("%1/%2 - %3.%4").arg(fi.path()) .arg(fi.completeBaseName()).arg(tr("Repaired")).arg(fi.suffix())); repaired.open(QIODevice::WriteOnly); LOG_INFO() << "repaired MLT XML file name" << repaired.fileName(); QFile temp(checker.tempFileName()); if (temp.exists() && repaired.exists()) { temp.open(QIODevice::ReadOnly); QByteArray xml = temp.readAll(); temp.close(); qint64 n = repaired.write(xml); while (n > 0 && n < xml.size()) { qint64 x = repaired.write(xml.right(xml.size() - n)); if (x > 0) n += x; else n = x; } repaired.close(); if (n == xml.size()) { fileName = repaired.fileName(); return true; } } QMessageBox::warning(this, qApp->applicationName(), tr("Repairing the project failed.")); LOG_WARNING() << "repairing failed"; return false; } bool MainWindow::isXmlRepaired(MltXmlChecker& checker, QString& fileName) { bool result = true; if (checker.isCorrected()) { LOG_WARNING() << fileName; QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Shotcut noticed some problems in your project.\n" "Do you want Shotcut to try to repair it?\n\n" "If you choose Yes, Shotcut will create a copy of your project\n" "with \"- Repaired\" in the file name and open it."), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); int r = dialog.exec(); if (r == QMessageBox::Yes) result = saveRepairedXmlFile(checker, fileName); } else if (checker.unlinkedFilesModel().rowCount() > 0) { UnlinkedFilesDialog dialog(this); dialog.setModel(checker.unlinkedFilesModel()); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QDialog::Accepted) { if (checker.check(fileName) && checker.isCorrected()) result = saveRepairedXmlFile(checker, fileName); } else { result = false; } } return result; } bool MainWindow::checkAutoSave(QString &url) { QMutexLocker locker(&m_autosaveMutex); // check whether autosave files exist: QSharedPointer<AutoSaveFile> stale(AutoSaveFile::getFile(url)); if (stale) { QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Auto-saved files exist. Do you want to recover them now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); int r = dialog.exec(); if (r == QMessageBox::Yes) { if (!stale->open(QIODevice::ReadWrite)) { LOG_WARNING() << "failed to recover autosave file" << url; } else { m_autosaveFile = stale; url = stale->fileName(); return true; } } } // create new autosave object m_autosaveFile.reset(new AutoSaveFile(url)); return false; } void MainWindow::stepLeftBySeconds(int sec) { m_player->seek(m_player->position() + sec * qRound(MLT.profile().fps())); } void MainWindow::doAutosave() { QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile) { bool success = false; if (m_autosaveFile->isOpen() || m_autosaveFile->open(QIODevice::ReadWrite)) { m_autosaveFile->close(); success = saveXML(m_autosaveFile->fileName(), false /* without relative paths */); m_autosaveFile->open(QIODevice::ReadWrite); } if (!success) { LOG_ERROR() << "failed to open autosave file for writing" << m_autosaveFile->fileName(); } } } void MainWindow::setFullScreen(bool isFullScreen) { if (isFullScreen) { #ifdef Q_OS_WIN showMaximized(); #else showFullScreen(); #endif ui->actionEnter_Full_Screen->setVisible(false); ui->actionFullscreen->setVisible(false); } } QString MainWindow::untitledFileName() const { QDir dir = Settings.appDataLocation(); if (!dir.exists()) dir.mkpath(dir.path()); return dir.filePath("__untitled__.mlt"); } void MainWindow::setProfile(const QString &profile_name) { LOG_DEBUG() << profile_name; MLT.setProfile(profile_name); emit profileChanged(); } bool MainWindow::isSourceClipMyProject(QString resource) { if (m_player->tabIndex() == Player::ProjectTabIndex && MLT.savedProducer() && MLT.savedProducer()->is_valid()) resource = QString::fromUtf8(MLT.savedProducer()->get("resource")); if (!resource.isEmpty() && QDir(resource) == QDir(fileName())) { QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You cannot add a project to itself!"), QMessageBox::Ok, this); dialog.setDefaultButton(QMessageBox::Ok); dialog.setEscapeButton(QMessageBox::Ok); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.exec(); return true; } return false; } bool MainWindow::keyframesDockIsVisible() const { return m_keyframesDock && m_keyframesDock->isVisible(); } void MainWindow::setAudioChannels(int channels) { LOG_DEBUG() << channels; MLT.videoWidget()->setProperty("audio_channels", channels); MLT.setAudioChannels(channels); if (channels == 1) ui->actionChannels1->setChecked(true); else if (channels == 2) ui->actionChannels2->setChecked(true); else if (channels == 6) ui->actionChannels6->setChecked(true); emit audioChannelsChanged(); } void MainWindow::showSaveError() { QMessageBox dialog(QMessageBox::Critical, qApp->applicationName(), tr("There was an error saving. Please try again."), QMessageBox::Ok, this); dialog.setDefaultButton(QMessageBox::Ok); dialog.setEscapeButton(QMessageBox::Ok); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.exec(); } void MainWindow::setPreviewScale(int scale) { LOG_DEBUG() << scale; switch (scale) { case 360: ui->actionPreview360->setChecked(true); break; case 540: ui->actionPreview540->setChecked(true); break; case 720: ui->actionPreview720->setChecked(true); break; default: ui->actionPreviewNone->setChecked(true); break; } MLT.setPreviewScale(scale); MLT.refreshConsumer(); } void MainWindow::setVideoModeMenu() { // Find a matching video mode for (const auto action : m_profileGroup->actions()) { auto s = action->data().toString(); Mlt::Profile profile(s.toUtf8().constData()); if (MLT.profile().width() == profile.width() && MLT.profile().height() == profile.height() && MLT.profile().sample_aspect_num() == profile.sample_aspect_num() && MLT.profile().sample_aspect_den() == profile.sample_aspect_den() && MLT.profile().frame_rate_num() == profile.frame_rate_num() && MLT.profile().frame_rate_den() == profile.frame_rate_den() && MLT.profile().colorspace() == profile.colorspace() && MLT.profile().progressive() == profile.progressive()) { // Select it action->setChecked(true); return; } } // Choose Automatic if nothing found m_profileGroup->actions().first()->setChecked(true); } void MainWindow::resetVideoModeMenu() { // Change selected Video Mode back to Settings for (const auto action : m_profileGroup->actions()) { if (action->data().toString() == Settings.playerProfile()) { action->setChecked(true); break; } } } static void autosaveTask(MainWindow* p) { LOG_DEBUG_TIME(); p->doAutosave(); } void MainWindow::onAutosaveTimeout() { if (isWindowModified()) QtConcurrent::run(autosaveTask, this); } void MainWindow::updateAutoSave() { if (!m_autosaveTimer.isActive()) m_autosaveTimer.start(); } void MainWindow::open(QString url, const Mlt::Properties* properties, bool play) { LOG_DEBUG() << url; bool modified = false; MltXmlChecker checker; QFileInfo info(url); if (info.isRelative()) { QDir pwd(QDir::currentPath()); url = pwd.filePath(url); } if (url.endsWith(".mlt") || url.endsWith(".xml")) { if (url != untitledFileName()) { showStatusMessage(tr("Opening %1").arg(url)); QCoreApplication::processEvents(); } } if (checker.check(url)) { if (!isCompatibleWithGpuMode(checker)) return; } if (url.endsWith(".mlt") || url.endsWith(".xml")) { // only check for a modified project when loading a project, not a simple producer if (!continueModified()) return; QCoreApplication::processEvents(); // close existing project if (playlist()) m_playlistDock->model()->close(); if (multitrack()) m_timelineDock->model()->close(); MLT.purgeMemoryPool(); if (!isXmlRepaired(checker, url)) return; modified = checkAutoSave(url); if (modified) { if (checker.check(url)) { if (!isCompatibleWithGpuMode(checker)) return; } if (!isXmlRepaired(checker, url)) return; } // let the new project change the profile if (modified || QFile::exists(url)) { MLT.profile().set_explicit(false); setWindowModified(modified); } } if (!playlist() && !multitrack()) { if (!modified && !continueModified()) return; setCurrentFile(""); setWindowModified(modified); MLT.resetURL(); // Return to automatic video mode if selected. if (m_profileGroup->checkedAction() && m_profileGroup->checkedAction()->data().toString().isEmpty()) MLT.profile().set_explicit(false); } if (url.endsWith(".mlt") || url.endsWith(".xml")) { checker.setLocale(); LOG_INFO() << "decimal point" << MLT.decimalPoint(); } QString urlToOpen = checker.isUpdated()? checker.tempFileName() : url; if (!MLT.open(QDir::fromNativeSeparators(urlToOpen), QDir::fromNativeSeparators(url)) && MLT.producer() && MLT.producer()->is_valid()) { Mlt::Properties* props = const_cast<Mlt::Properties*>(properties); if (props && props->is_valid()) mlt_properties_inherit(MLT.producer()->get_properties(), props->get_properties()); m_player->setPauseAfterOpen(!play || !MLT.isClip()); setAudioChannels(MLT.audioChannels()); if (url.endsWith(".mlt") || url.endsWith(".xml")) { setVideoModeMenu(); } open(MLT.producer()); if (url.startsWith(AutoSaveFile::path())) { QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile && m_autosaveFile->managedFileName() != untitledFileName()) { m_recentDock->add(m_autosaveFile->managedFileName()); LOG_INFO() << m_autosaveFile->managedFileName(); } } else { m_recentDock->add(url); LOG_INFO() << url; } } else if (url != untitledFileName()) { showStatusMessage(tr("Failed to open ") + url); emit openFailed(url); } } void MainWindow::openMultiple(const QStringList& paths) { if (paths.size() > 1) { QList<QUrl> urls; foreach (const QString& s, paths) urls << s; openMultiple(urls); } else if (!paths.isEmpty()) { open(paths.first()); } } void MainWindow::openMultiple(const QList<QUrl>& urls) { if (urls.size() > 1) { m_multipleFiles = Util::sortedFileList(Util::expandDirectories(urls)); open(m_multipleFiles.first()); } else { QUrl url = urls.first(); open(Util::removeFileScheme(url)); } } void MainWindow::openVideo() { QString path = Settings.openPath(); #ifdef Q_OS_MAC path.append("/*"); #endif QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path, tr("All Files (*);;MLT XML (*.mlt)")); if (filenames.length() > 0) { Settings.setOpenPath(QFileInfo(filenames.first()).path()); activateWindow(); if (filenames.length() > 1) m_multipleFiles = filenames; open(filenames.first()); } else { // If file invalid, then on some platforms the dialog messes up SDL. MLT.onWindowResize(); activateWindow(); } } void MainWindow::openCut(Mlt::Producer* producer, bool play) { m_player->setPauseAfterOpen(!play); open(producer); MLT.seek(producer->get_in()); } void MainWindow::hideProducer() { // This is a hack to release references to the old producer, but it // probably leaves a reference to the new color producer somewhere not // yet identified (root cause). openCut(new Mlt::Producer(MLT.profile(), "color:_hide")); QCoreApplication::processEvents(); openCut(new Mlt::Producer(MLT.profile(), "color:_hide")); QCoreApplication::processEvents(); QScrollArea* scrollArea = (QScrollArea*) m_propertiesDock->widget(); delete scrollArea->widget(); scrollArea->setWidget(nullptr); m_player->reset(); QCoreApplication::processEvents(); } void MainWindow::closeProducer() { hideProducer(); MLT.stop(); MLT.close(); MLT.setSavedProducer(0); } void MainWindow::showStatusMessage(QAction* action, int timeoutSeconds) { // This object takes ownership of the passed action. // This version does not currently log its message. m_statusBarAction.reset(action); action->setParent(0); m_player->setStatusLabel(action->text(), timeoutSeconds, action); } void MainWindow::showStatusMessage(const QString& message, int timeoutSeconds) { LOG_INFO() << message; m_player->setStatusLabel(message, timeoutSeconds, 0 /* QAction */); m_statusBarAction.reset(); } void MainWindow::seekPlaylist(int start) { if (!playlist()) return; // we bypass this->open() to prevent sending producerOpened signal to self, which causes to reload playlist if (!MLT.producer() || (void*) MLT.producer()->get_producer() != (void*) playlist()->get_playlist()) MLT.setProducer(new Mlt::Producer(*playlist())); m_player->setIn(-1); m_player->setOut(-1); // since we do not emit producerOpened, these components need updating on_actionJack_triggered(ui->actionJack && ui->actionJack->isChecked()); m_player->onProducerOpened(false); m_encodeDock->onProducerOpened(); m_filterController->setProducer(); updateMarkers(); MLT.seek(start); m_player->setFocus(); m_player->switchToTab(Player::ProjectTabIndex); } void MainWindow::seekTimeline(int position, bool seekPlayer) { if (!multitrack()) return; // we bypass this->open() to prevent sending producerOpened signal to self, which causes to reload playlist if (MLT.producer() && (void*) MLT.producer()->get_producer() != (void*) multitrack()->get_producer()) { MLT.setProducer(new Mlt::Producer(*multitrack())); m_player->setIn(-1); m_player->setOut(-1); // since we do not emit producerOpened, these components need updating on_actionJack_triggered(ui->actionJack && ui->actionJack->isChecked()); m_player->onProducerOpened(false); m_encodeDock->onProducerOpened(); m_filterController->setProducer(); updateMarkers(); m_player->setFocus(); m_player->switchToTab(Player::ProjectTabIndex); m_timelineDock->emitSelectedFromSelection(); } if (seekPlayer) m_player->seek(position); else m_player->pause(); } void MainWindow::seekKeyframes(int position) { m_player->seek(position); } void MainWindow::readPlayerSettings() { LOG_DEBUG() << "begin"; ui->actionRealtime->setChecked(Settings.playerRealtime()); ui->actionProgressive->setChecked(Settings.playerProgressive()); ui->actionScrubAudio->setChecked(Settings.playerScrubAudio()); if (ui->actionJack) ui->actionJack->setChecked(Settings.playerJACK()); if (ui->actionGPU) { MLT.videoWidget()->setProperty("gpu", ui->actionGPU->isChecked()); ui->actionGPU->setChecked(Settings.playerGPU()); } QString external = Settings.playerExternal(); bool ok = false; external.toInt(&ok); auto isExternalPeripheral = !external.isEmpty() && !ok; setAudioChannels(Settings.playerAudioChannels()); #if LIBMLT_VERSION_INT >= MLT_VERSION_PREVIEW_SCALE if (isExternalPeripheral) { setPreviewScale(0); m_previewScaleGroup->setEnabled(false); } else { setPreviewScale(Settings.playerPreviewScale()); m_previewScaleGroup->setEnabled(true); } #endif QString deinterlacer = Settings.playerDeinterlacer(); QString interpolation = Settings.playerInterpolation(); if (deinterlacer == "onefield") ui->actionOneField->setChecked(true); else if (deinterlacer == "linearblend") ui->actionLinearBlend->setChecked(true); else if (deinterlacer == "yadif-nospatial") ui->actionYadifTemporal->setChecked(true); else ui->actionYadifSpatial->setChecked(true); if (interpolation == "nearest") ui->actionNearest->setChecked(true); else if (interpolation == "bilinear") ui->actionBilinear->setChecked(true); else if (interpolation == "bicubic") ui->actionBicubic->setChecked(true); else ui->actionHyper->setChecked(true); foreach (QAction* a, m_externalGroup->actions()) { if (a->data() == external) { a->setChecked(true); if (a->data().toString().startsWith("decklink") && m_keyerMenu) m_keyerMenu->setEnabled(true); break; } } if (m_keyerGroup) { int keyer = Settings.playerKeyerMode(); foreach (QAction* a, m_keyerGroup->actions()) { if (a->data() == keyer) { a->setChecked(true); break; } } } QString profile = Settings.playerProfile(); // Automatic not permitted for SDI/HDMI if (isExternalPeripheral && profile.isEmpty()) profile = "atsc_720p_50"; foreach (QAction* a, m_profileGroup->actions()) { // Automatic not permitted for SDI/HDMI if (a->data().toString().isEmpty() && !external.isEmpty() && !ok) a->setDisabled(true); if (a->data().toString() == profile) { a->setChecked(true); break; } } QString gamma = Settings.playerGamma(); if (gamma == "bt709") ui->actionGammaRec709->setChecked(true); else ui->actionGammaSRGB->setChecked(true); LOG_DEBUG() << "end"; } void MainWindow::readWindowSettings() { LOG_DEBUG() << "begin"; Settings.setWindowGeometryDefault(saveGeometry()); Settings.setWindowStateDefault(saveState()); Settings.sync(); if (!Settings.windowGeometry().isEmpty()) { restoreGeometry(Settings.windowGeometry()); restoreState(Settings.windowState()); #ifdef Q_OS_MAC m_filtersDock->setFloating(false); #endif } else { on_actionLayoutTimeline_triggered(); } LOG_DEBUG() << "end"; } void MainWindow::writeSettings() { #ifndef Q_OS_MAC if (isFullScreen()) showNormal(); #endif Settings.setPlayerGPU(ui->actionGPU->isChecked()); Settings.setWindowGeometry(saveGeometry()); Settings.setWindowState(saveState()); Settings.sync(); } void MainWindow::configureVideoWidget() { LOG_DEBUG() << "begin"; if (m_profileGroup->checkedAction()) setProfile(m_profileGroup->checkedAction()->data().toString()); MLT.videoWidget()->setProperty("realtime", ui->actionRealtime->isChecked()); bool ok = false; m_externalGroup->checkedAction()->data().toInt(&ok); if (!ui->menuExternal || m_externalGroup->checkedAction()->data().toString().isEmpty() || ok) { MLT.videoWidget()->setProperty("progressive", ui->actionProgressive->isChecked()); } else { MLT.videoWidget()->setProperty("mlt_service", m_externalGroup->checkedAction()->data()); MLT.videoWidget()->setProperty("progressive", MLT.profile().progressive()); ui->actionProgressive->setEnabled(false); } if (ui->actionChannels1->isChecked()) setAudioChannels(1); else if (ui->actionChannels2->isChecked()) setAudioChannels(2); else setAudioChannels(6); if (ui->actionOneField->isChecked()) MLT.videoWidget()->setProperty("deinterlace_method", "onefield"); else if (ui->actionLinearBlend->isChecked()) MLT.videoWidget()->setProperty("deinterlace_method", "linearblend"); else if (ui->actionYadifTemporal->isChecked()) MLT.videoWidget()->setProperty("deinterlace_method", "yadif-nospatial"); else MLT.videoWidget()->setProperty("deinterlace_method", "yadif"); if (ui->actionNearest->isChecked()) MLT.videoWidget()->setProperty("rescale", "nearest"); else if (ui->actionBilinear->isChecked()) MLT.videoWidget()->setProperty("rescale", "bilinear"); else if (ui->actionBicubic->isChecked()) MLT.videoWidget()->setProperty("rescale", "bicubic"); else MLT.videoWidget()->setProperty("rescale", "hyper"); if (m_keyerGroup) MLT.videoWidget()->setProperty("keyer", m_keyerGroup->checkedAction()->data()); LOG_DEBUG() << "end"; } void MainWindow::setCurrentFile(const QString &filename) { QString shownName = tr("Untitled"); if (filename == untitledFileName()) m_currentFile.clear(); else m_currentFile = filename; if (!m_currentFile.isEmpty()) shownName = QFileInfo(m_currentFile).fileName(); #ifdef Q_OS_MAC setWindowTitle(QString("%1 - %2").arg(shownName).arg(qApp->applicationName())); #else setWindowTitle(QString("%1[*] - %2").arg(shownName).arg(qApp->applicationName())); #endif } void MainWindow::on_actionAbout_Shotcut_triggered() { QMessageBox::about(this, tr("About Shotcut"), tr("<h1>Shotcut version %1</h1>" "<p><a href=\"https://www.shotcut.org/\">Shotcut</a> is a free, open source, cross platform video editor.</p>" "<small><p>Copyright &copy; 2011-2020 <a href=\"https://www.meltytech.com/\">Meltytech</a>, LLC</p>" "<p>Licensed under the <a href=\"https://www.gnu.org/licenses/gpl.html\">GNU General Public License v3.0</a></p>" "<p>This program proudly uses the following projects:<ul>" "<li><a href=\"https://www.qt.io/\">Qt</a> application and UI framework</li>" "<li><a href=\"https://www.mltframework.org/\">MLT</a> multimedia authoring framework</li>" "<li><a href=\"https://www.ffmpeg.org/\">FFmpeg</a> multimedia format and codec libraries</li>" "<li><a href=\"https://www.videolan.org/developers/x264.html\">x264</a> H.264 encoder</li>" "<li><a href=\"https://www.webmproject.org/\">WebM</a> VP8 and VP9 encoders</li>" "<li><a href=\"http://lame.sourceforge.net/\">LAME</a> MP3 encoder</li>" "<li><a href=\"https://www.dyne.org/software/frei0r/\">Frei0r</a> video plugins</li>" "<li><a href=\"https://www.ladspa.org/\">LADSPA</a> audio plugins</li>" "<li><a href=\"http://www.defaulticon.com/\">DefaultIcon</a> icon collection by <a href=\"http://www.interactivemania.com/\">interactivemania</a></li>" "<li><a href=\"http://www.oxygen-icons.org/\">Oxygen</a> icon collection</li>" "</ul></p>" "<p>The source code used to build this program can be downloaded from " "<a href=\"https://www.shotcut.org/\">shotcut.org</a>.</p>" "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.</small>" ).arg(qApp->applicationVersion())); } void MainWindow::keyPressEvent(QKeyEvent* event) { if (event->isAccepted() && event->key() != Qt::Key_F12) return; bool handled = true; switch (event->key()) { case Qt::Key_Home: m_player->seek(0); break; case Qt::Key_End: if (MLT.producer()) m_player->seek(MLT.producer()->get_length() - 1); break; case Qt::Key_Left: if ((event->modifiers() & Qt::ControlModifier) && m_timelineDock->isVisible()) { if (m_timelineDock->selection().isEmpty()) { m_timelineDock->selectClipUnderPlayhead(); } else if (m_timelineDock->selection().size() == 1) { int newIndex = m_timelineDock->selection().first().x() - 1; if (newIndex < 0) break; m_timelineDock->setSelection(QList<QPoint>() << QPoint(newIndex, m_timelineDock->selection().first().y())); m_navigationPosition = m_timelineDock->centerOfClip(m_timelineDock->currentTrack(), newIndex); } } else { stepLeftOneFrame(); } break; case Qt::Key_Right: if ((event->modifiers() & Qt::ControlModifier) && m_timelineDock->isVisible()) { if (m_timelineDock->selection().isEmpty()) { m_timelineDock->selectClipUnderPlayhead(); } else if (m_timelineDock->selection().size() == 1) { int newIndex = m_timelineDock->selection().first().x() + 1; if (newIndex >= m_timelineDock->clipCount(-1)) break; m_timelineDock->setSelection(QList<QPoint>() << QPoint(newIndex, m_timelineDock->selection().first().y())); m_navigationPosition = m_timelineDock->centerOfClip(m_timelineDock->currentTrack(), newIndex); } } else { stepRightOneFrame(); } break; case Qt::Key_PageUp: case Qt::Key_PageDown: { int directionMultiplier = event->key() == Qt::Key_PageUp ? -1 : 1; int seconds = 1; if (event->modifiers() & Qt::ControlModifier) seconds *= 5; if (event->modifiers() & Qt::ShiftModifier) seconds *= 2; stepLeftBySeconds(seconds * directionMultiplier); } break; case Qt::Key_Space: #ifdef Q_OS_MAC // Spotlight defaults to Cmd+Space, so also accept Ctrl+Space. if ((event->modifiers() == Qt::MetaModifier || (event->modifiers() & Qt::ControlModifier)) && m_timelineDock->isVisible()) #else if (event->modifiers() == Qt::ControlModifier && m_timelineDock->isVisible()) #endif m_timelineDock->selectClipUnderPlayhead(); else handled = false; break; case Qt::Key_A: if (event->modifiers() == Qt::ShiftModifier) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionAppendCut_triggered(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::ShiftModifier)) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionSelectAll_triggered(); } else if (event->modifiers() == Qt::ControlModifier) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->selectAll(); } else if (event->modifiers() == Qt::NoModifier) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->append(-1); } break; case Qt::Key_C: if (event->modifiers() == Qt::ShiftModifier && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionCopy_triggered(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::AltModifier)) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->copyToSource(); } else if (isMultitrackValid()) { m_timelineDock->show(); m_timelineDock->raise(); if (m_timelineDock->selection().isEmpty()) { m_timelineDock->copyClip(-1, -1); } else { auto& selected = m_timelineDock->selection().first(); m_timelineDock->copyClip(selected.y(), selected.x()); } } break; case Qt::Key_D: if (event->modifiers() == Qt::ControlModifier) { m_timelineDock->setSelection(); m_timelineDock->model()->reload(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::ShiftModifier)) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionSelectNone_triggered(); } else { handled = false; } break; case Qt::Key_F: if (event->modifiers() == Qt::NoModifier || event->modifiers() == Qt::ControlModifier) { m_filtersDock->show(); m_filtersDock->raise(); m_filtersDock->widget()->setFocus(); m_filtersDock->openFilterMenu(); } else if (event->modifiers() == Qt::ShiftModifier) { filterController()->removeCurrent(); } else { handled = false; } break; case Qt::Key_H: #ifdef Q_OS_MAC // OS X uses Cmd+H to hide an app. if (event->modifiers() & Qt::MetaModifier && isMultitrackValid()) #else if (event->modifiers() & Qt::ControlModifier && isMultitrackValid()) #endif m_timelineDock->toggleTrackHidden(m_timelineDock->currentTrack()); break; case Qt::Key_J: if (m_isKKeyPressed) m_player->seek(m_player->position() - 1); else m_player->rewind(false); break; case Qt::Key_K: m_player->pause(); m_isKKeyPressed = true; break; case Qt::Key_L: #ifdef Q_OS_MAC // OS X uses Cmd+H to hide an app and Cmd+M to minimize. Therefore, we force // it to be the apple keyboard control key aka meta. Therefore, to be // consistent with all track header toggles, we make the lock toggle also use // meta. if (event->modifiers() & Qt::MetaModifier && isMultitrackValid()) #else if (event->modifiers() & Qt::ControlModifier && isMultitrackValid()) #endif m_timelineDock->setTrackLock(m_timelineDock->currentTrack(), !m_timelineDock->isTrackLocked(m_timelineDock->currentTrack())); else if (m_isKKeyPressed) m_player->seek(m_player->position() + 1); else m_player->fastForward(false); break; case Qt::Key_M: #ifdef Q_OS_MAC // OS X uses Cmd+M to minimize an app. if (event->modifiers() & Qt::MetaModifier && isMultitrackValid()) #else if (event->modifiers() & Qt::ControlModifier && isMultitrackValid()) #endif m_timelineDock->toggleTrackMute(m_timelineDock->currentTrack()); break; case Qt::Key_I: if (event->modifiers() == Qt::ControlModifier) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->addVideoTrack(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::AltModifier)) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->insertTrack(); } else { setInToCurrent(event->modifiers() & Qt::ShiftModifier); } break; case Qt::Key_O: setOutToCurrent(event->modifiers() & Qt::ShiftModifier); break; case Qt::Key_P: if (event->modifiers() == Qt::ControlModifier) { Settings.setTimelineSnap(!Settings.timelineSnap()); } break; case Qt::Key_R: if (event->modifiers() & Qt::ControlModifier) { if (event->modifiers() & Qt::AltModifier) { Settings.setTimelineRippleAllTracks(!Settings.timelineRippleAllTracks()); } else if (event->modifiers() & Qt::ShiftModifier) { Settings.setTimelineRippleAllTracks(!Settings.timelineRipple()); Settings.setTimelineRipple(!Settings.timelineRipple()); } else { Settings.setTimelineRipple(!Settings.timelineRipple()); } } else if (isMultitrackValid()) { m_timelineDock->show(); m_timelineDock->raise(); if (MLT.isClip() || m_timelineDock->selection().isEmpty()) { m_timelineDock->replace(-1, -1); } else { auto& selected = m_timelineDock->selection().first(); m_timelineDock->replace(selected.y(), selected.x()); } } break; case Qt::Key_S: if (isMultitrackValid()) m_timelineDock->splitClip(); break; case Qt::Key_U: if (event->modifiers() == Qt::ControlModifier) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->addAudioTrack(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::AltModifier)) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->removeTrack(); } break; case Qt::Key_V: // Avid Splice In if (event->modifiers() == Qt::ShiftModifier) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionInsertCut_triggered(); } else { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->insert(-1); } break; case Qt::Key_B: if (event->modifiers() & Qt::ControlModifier && event->modifiers() & Qt::AltModifier) { // Toggle track blending. int trackIndex = m_timelineDock->currentTrack(); bool isBottomVideo = m_timelineDock->model()->data(m_timelineDock->model()->index(trackIndex), MultitrackModel::IsBottomVideoRole).toBool(); if (!isBottomVideo) { bool isComposite = m_timelineDock->model()->data(m_timelineDock->model()->index(trackIndex), MultitrackModel::IsCompositeRole).toBool(); m_timelineDock->setTrackComposite(trackIndex, !isComposite); } } else if (event->modifiers() == Qt::ShiftModifier) { if (m_playlistDock->model()->rowCount() > 0) { // Update playlist item. m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionUpdate_triggered(); } } else { // Overwrite on timeline. m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->overwrite(-1); } break; case Qt::Key_Escape: // Avid Toggle Active Monitor if (MLT.isPlaylist()) { if (isMultitrackValid()) m_player->onTabBarClicked(Player::ProjectTabIndex); else if (MLT.savedProducer()) m_player->onTabBarClicked(Player::SourceTabIndex); else m_playlistDock->on_actionOpen_triggered(); } else if (MLT.isMultitrack()) { if (MLT.savedProducer()) m_player->onTabBarClicked(Player::SourceTabIndex); // TODO else open clip under playhead of current track if available } else { if (isMultitrackValid() || (playlist() && playlist()->count() > 0)) m_player->onTabBarClicked(Player::ProjectTabIndex); } break; case Qt::Key_Up: if (m_playlistDock->isVisible() && event->modifiers() & Qt::AltModifier && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->decrementIndex(); m_playlistDock->on_actionOpen_triggered(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::ShiftModifier)) { if (m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->moveClipUp(); m_playlistDock->decrementIndex(); } } else if (isMultitrackValid()) { int newClipIndex = -1; int trackIndex = m_timelineDock->currentTrack() - 1; if ((event->modifiers() & Qt::ControlModifier) && !m_timelineDock->selection().isEmpty() && trackIndex > -1) { newClipIndex = m_timelineDock->clipIndexAtPosition(trackIndex, m_navigationPosition); } m_timelineDock->incrementCurrentTrack(-1); if (newClipIndex >= 0) { newClipIndex = qMin(newClipIndex, m_timelineDock->clipCount(trackIndex) - 1); m_timelineDock->setSelection(QList<QPoint>() << QPoint(newClipIndex, trackIndex)); } } break; case Qt::Key_Down: if (m_playlistDock->isVisible() && event->modifiers() & Qt::AltModifier && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->incrementIndex(); m_playlistDock->on_actionOpen_triggered(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::ShiftModifier)) { if (m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->moveClipDown(); m_playlistDock->incrementIndex(); } } else if (isMultitrackValid()) { int newClipIndex = -1; int trackIndex = m_timelineDock->currentTrack() + 1; if ((event->modifiers() & Qt::ControlModifier) && !m_timelineDock->selection().isEmpty() && trackIndex < m_timelineDock->model()->trackList().count()) { newClipIndex = m_timelineDock->clipIndexAtPosition(trackIndex, m_navigationPosition); } m_timelineDock->incrementCurrentTrack(1); if (newClipIndex >= 0) { newClipIndex = qMin(newClipIndex, m_timelineDock->clipCount(trackIndex) - 1); m_timelineDock->setSelection(QList<QPoint>() << QPoint(newClipIndex, trackIndex)); } } break; case Qt::Key_1: case Qt::Key_2: case Qt::Key_3: case Qt::Key_4: case Qt::Key_5: case Qt::Key_6: case Qt::Key_7: case Qt::Key_8: case Qt::Key_9: if (!event->modifiers() && m_playlistDock->isVisible() && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->setIndex(event->key() - Qt::Key_1); } break; case Qt::Key_0: if (!event->modifiers() ) { if (m_timelineDock->isVisible()) { m_timelineDock->resetZoom(); } else if (m_playlistDock->isVisible() && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->setIndex(9); } } if (m_keyframesDock->isVisible() && (event->modifiers() & Qt::AltModifier)) { emit m_keyframesDock->resetZoom(); } break; case Qt::Key_X: // Avid Extract if (event->modifiers() == Qt::ShiftModifier && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_removeButton_clicked(); } else if (isMultitrackValid()) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->removeSelection(); } break; case Qt::Key_Backspace: case Qt::Key_Delete: if (isMultitrackValid()) { m_timelineDock->show(); m_timelineDock->raise(); if (event->modifiers() == Qt::ShiftModifier) m_timelineDock->removeSelection(); else m_timelineDock->liftSelection(); } else if (m_playlistDock->model()->rowCount() > 0) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_removeButton_clicked(); } break; case Qt::Key_Z: // Avid Lift if (event->modifiers() == Qt::ShiftModifier && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_removeButton_clicked(); } else if (isMultitrackValid() && event->modifiers() == Qt::NoModifier) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->liftSelection(); } break; case Qt::Key_Minus: if (m_timelineDock->isVisible() && !(event->modifiers() & Qt::AltModifier)) { if (event->modifiers() & Qt::ControlModifier) m_timelineDock->makeTracksShorter(); else m_timelineDock->zoomOut(); } if (m_keyframesDock->isVisible() && (event->modifiers() & Qt::AltModifier)) { emit m_keyframesDock->zoomOut(); } break; case Qt::Key_Equal: case Qt::Key_Plus: if (m_timelineDock->isVisible() && !(event->modifiers() & Qt::AltModifier)) { if (event->modifiers() & Qt::ControlModifier) m_timelineDock->makeTracksTaller(); else m_timelineDock->zoomIn(); } if (m_keyframesDock->isVisible() && (event->modifiers() & Qt::AltModifier)) { emit m_keyframesDock->zoomIn(); } break; case Qt::Key_Enter: // Seek to current playlist item case Qt::Key_Return: if (m_playlistDock->isVisible() && m_playlistDock->position() >= 0) { if (event->modifiers() == Qt::ShiftModifier) seekPlaylist(m_playlistDock->position()); else if (event->modifiers() == Qt::ControlModifier) m_playlistDock->on_actionOpen_triggered(); } break; case Qt::Key_F2: onPropertiesDockTriggered(true); emit renameRequested(); break; case Qt::Key_F3: onRecentDockTriggered(true); m_recentDock->find(); break; case Qt::Key_F5: m_timelineDock->model()->reload(); m_keyframesDock->model().reload(); break; case Qt::Key_F12: LOG_DEBUG() << "event isAccepted:" << event->isAccepted(); LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); break; case Qt::Key_BracketLeft: if (filterController()->currentFilter() && m_filtersDock->qmlProducer()) { if (event->modifiers() == Qt::AltModifier) { emit m_keyframesDock->seekPreviousSimple(); } else { int i = m_filtersDock->qmlProducer()->position() + m_filtersDock->qmlProducer()->in(); filterController()->currentFilter()->setIn(i); } } break; case Qt::Key_BracketRight: if (filterController()->currentFilter() && m_filtersDock->qmlProducer()) { if (event->modifiers() == Qt::AltModifier) { emit m_keyframesDock->seekNextSimple(); } else { int i = m_filtersDock->qmlProducer()->position() + m_filtersDock->qmlProducer()->in(); filterController()->currentFilter()->setOut(i); } } break; case Qt::Key_BraceLeft: if (filterController()->currentFilter() && m_filtersDock->qmlProducer()) { int i = m_filtersDock->qmlProducer()->position() + m_filtersDock->qmlProducer()->in() - filterController()->currentFilter()->in(); filterController()->currentFilter()->setAnimateIn(i); } break; case Qt::Key_BraceRight: if (filterController()->currentFilter() && m_filtersDock->qmlProducer()) { int i = filterController()->currentFilter()->out() - (m_filtersDock->qmlProducer()->position() + m_filtersDock->qmlProducer()->in()); filterController()->currentFilter()->setAnimateOut(i); } break; case Qt::Key_Semicolon: if (filterController()->currentFilter() && m_filtersDock->qmlProducer() && m_keyframesDock->currentParameter() >= 0) { auto position = m_filtersDock->qmlProducer()->position() - (filterController()->currentFilter()->in() - m_filtersDock->qmlProducer()->in()); auto parameterIndex = m_keyframesDock->currentParameter(); if (m_keyframesDock->model().isKeyframe(parameterIndex, position)) { auto keyframeIndex = m_keyframesDock->model().keyframeIndex(parameterIndex, position); m_keyframesDock->model().remove(parameterIndex, keyframeIndex); } else { m_keyframesDock->model().addKeyframe(parameterIndex, position); } } break; default: handled = false; break; } if (handled) event->setAccepted(handled); else QMainWindow::keyPressEvent(event); } void MainWindow::keyReleaseEvent(QKeyEvent* event) { if (event->key() == Qt::Key_K) { m_isKKeyPressed = false; event->setAccepted(true); } else { QMainWindow::keyReleaseEvent(event); } } void MainWindow::hideSetDataDirectory() { delete ui->actionAppDataSet; } QAction *MainWindow::actionAddCustomProfile() const { return ui->actionAddCustomProfile; } QAction *MainWindow::actionProfileRemove() const { return ui->actionProfileRemove; } void MainWindow::buildVideoModeMenu(QMenu* topMenu, QMenu*& customMenu, QActionGroup* group, QAction* addAction, QAction* removeAction) { topMenu->addAction(addProfile(group, "HD 720p 50 fps", "atsc_720p_50")); topMenu->addAction(addProfile(group, "HD 720p 59.94 fps", "atsc_720p_5994")); topMenu->addAction(addProfile(group, "HD 720p 60 fps", "atsc_720p_60")); topMenu->addAction(addProfile(group, "HD 1080i 25 fps", "atsc_1080i_50")); topMenu->addAction(addProfile(group, "HD 1080i 29.97 fps", "atsc_1080i_5994")); topMenu->addAction(addProfile(group, "HD 1080p 23.98 fps", "atsc_1080p_2398")); topMenu->addAction(addProfile(group, "HD 1080p 24 fps", "atsc_1080p_24")); topMenu->addAction(addProfile(group, "HD 1080p 25 fps", "atsc_1080p_25")); topMenu->addAction(addProfile(group, "HD 1080p 29.97 fps", "atsc_1080p_2997")); topMenu->addAction(addProfile(group, "HD 1080p 30 fps", "atsc_1080p_30")); topMenu->addAction(addProfile(group, "HD 1080p 59.94 fps", "atsc_1080p_5994")); topMenu->addAction(addProfile(group, "HD 1080p 50 fps", "atsc_1080p_50")); topMenu->addAction(addProfile(group, "HD 1080p 60 fps", "atsc_1080p_60")); topMenu->addAction(addProfile(group, "SD NTSC", "dv_ntsc")); topMenu->addAction(addProfile(group, "SD PAL", "dv_pal")); topMenu->addAction(addProfile(group, "UHD 2160p 23.98 fps", "uhd_2160p_2398")); topMenu->addAction(addProfile(group, "UHD 2160p 24 fps", "uhd_2160p_24")); topMenu->addAction(addProfile(group, "UHD 2160p 25 fps", "uhd_2160p_25")); topMenu->addAction(addProfile(group, "UHD 2160p 29.97 fps", "uhd_2160p_2997")); topMenu->addAction(addProfile(group, "UHD 2160p 30 fps", "uhd_2160p_30")); topMenu->addAction(addProfile(group, "UHD 2160p 50 fps", "uhd_2160p_50")); topMenu->addAction(addProfile(group, "UHD 2160p 59.94 fps", "uhd_2160p_5994")); topMenu->addAction(addProfile(group, "UHD 2160p 60 fps", "uhd_2160p_60")); QMenu* menu = topMenu->addMenu(tr("Non-Broadcast")); menu->addAction(addProfile(group, "640x480 4:3 NTSC", "square_ntsc")); menu->addAction(addProfile(group, "768x576 4:3 PAL", "square_pal")); menu->addAction(addProfile(group, "854x480 16:9 NTSC", "square_ntsc_wide")); menu->addAction(addProfile(group, "1024x576 16:9 PAL", "square_pal_wide")); menu->addAction(addProfile(group, tr("DVD Widescreen NTSC"), "dv_ntsc_wide")); menu->addAction(addProfile(group, tr("DVD Widescreen PAL"), "dv_pal_wide")); menu->addAction(addProfile(group, "HD 720p 23.98 fps", "atsc_720p_2398")); menu->addAction(addProfile(group, "HD 720p 24 fps", "atsc_720p_24")); menu->addAction(addProfile(group, "HD 720p 25 fps", "atsc_720p_25")); menu->addAction(addProfile(group, "HD 720p 29.97 fps", "atsc_720p_2997")); menu->addAction(addProfile(group, "HD 720p 30 fps", "atsc_720p_30")); menu->addAction(addProfile(group, "HD 1080i 60 fps", "atsc_1080i_60")); menu->addAction(addProfile(group, "HDV 1080i 25 fps", "hdv_1080_50i")); menu->addAction(addProfile(group, "HDV 1080i 29.97 fps", "hdv_1080_60i")); menu->addAction(addProfile(group, "HDV 1080p 25 fps", "hdv_1080_25p")); menu->addAction(addProfile(group, "HDV 1080p 29.97 fps", "hdv_1080_30p")); menu->addAction(addProfile(group, tr("Square 1080p 30 fps"), "square_1080p_30")); menu->addAction(addProfile(group, tr("Square 1080p 60 fps"), "square_1080p_60")); menu->addAction(addProfile(group, tr("Vertical HD 30 fps"), "vertical_hd_30")); menu->addAction(addProfile(group, tr("Vertical HD 60 fps"), "vertical_hd_60")); customMenu = topMenu->addMenu(tr("Custom")); customMenu->addAction(addAction); // Load custom profiles QDir dir(Settings.appDataLocation()); if (dir.cd("profiles")) { QStringList profiles = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); if (profiles.length() > 0) { customMenu->addAction(removeAction); customMenu->addSeparator(); } foreach (QString name, profiles) customMenu->addAction(addProfile(group, name, dir.filePath(name))); } } void MainWindow::newProject(const QString &filename, bool isProjectFolder) { if (isProjectFolder) { QFileInfo info(filename); MLT.setProjectFolder(info.absolutePath()); } if (saveXML(filename)) { QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile) m_autosaveFile->changeManagedFile(filename); else m_autosaveFile.reset(new AutoSaveFile(filename)); setCurrentFile(filename); setWindowModified(false); if (MLT.producer()) showStatusMessage(tr("Saved %1").arg(m_currentFile)); m_undoStack->setClean(); m_recentDock->add(filename); } else { showSaveError(); } } void MainWindow::addCustomProfile(const QString &name, QMenu *menu, QAction *action, QActionGroup *group) { // Add new profile to the menu. QDir dir(Settings.appDataLocation()); if (dir.cd("profiles")) { QStringList profiles = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); if (profiles.length() == 1) { menu->addAction(action); menu->addSeparator(); } action = addProfile(group, name, dir.filePath(name)); action->setChecked(true); menu->addAction(action); Settings.setPlayerProfile(dir.filePath(name)); Settings.sync(); } } void MainWindow::removeCustomProfiles(const QStringList &profiles, QDir& dir, QMenu *menu, QAction *action) { foreach(const QString& profile, profiles) { // Remove the file. dir.remove(profile); // Locate the menu item. foreach (QAction* a, menu->actions()) { if (a->text() == profile) { // Remove the menu item. delete a; break; } } } // If no more custom video modes. if (menu->actions().size() == 3) { // Remove the Remove action and separator. menu->removeAction(action); foreach (QAction* a, menu->actions()) { if (a->isSeparator()) { delete a; break; } } } } // Drag-n-drop events bool MainWindow::eventFilter(QObject* target, QEvent* event) { if (event->type() == QEvent::DragEnter && target == MLT.videoWidget()) { dragEnterEvent(static_cast<QDragEnterEvent*>(event)); return true; } else if (event->type() == QEvent::Drop && target == MLT.videoWidget()) { dropEvent(static_cast<QDropEvent*>(event)); return true; } else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { if (QEvent::KeyPress == event->type()) { // Let Shift+Escape be a global hook to defocus a widget (assign global player focus). auto keyEvent = static_cast<QKeyEvent*>(event); if (Qt::Key_Escape == keyEvent->key() && Qt::ShiftModifier == keyEvent->modifiers()) { m_player->setFocus(); return true; } } QQuickWidget * focusedQuickWidget = qobject_cast<QQuickWidget*>(qApp->focusWidget()); if (focusedQuickWidget && focusedQuickWidget->quickWindow()->activeFocusItem()) { event->accept(); focusedQuickWidget->quickWindow()->sendEvent(focusedQuickWidget->quickWindow()->activeFocusItem(), event); QWidget * w = focusedQuickWidget->parentWidget(); if (!event->isAccepted()) qApp->sendEvent(w, event); return true; } } return QMainWindow::eventFilter(target, event); } void MainWindow::dragEnterEvent(QDragEnterEvent *event) { // Simulate the player firing a dragStarted even to make the playlist close // its help text view. This lets one drop a clip directly into the playlist // from a fresh start. Mlt::GLWidget* videoWidget = (Mlt::GLWidget*) &Mlt::Controller::singleton(); emit videoWidget->dragStarted(); event->acceptProposedAction(); } void MainWindow::dropEvent(QDropEvent *event) { const QMimeData *mimeData = event->mimeData(); if (mimeData->hasFormat("application/x-qabstractitemmodeldatalist")) { QByteArray encoded = mimeData->data("application/x-qabstractitemmodeldatalist"); QDataStream stream(&encoded, QIODevice::ReadOnly); QMap<int, QVariant> roleDataMap; while (!stream.atEnd()) { int row, col; stream >> row >> col >> roleDataMap; } if (roleDataMap.contains(Qt::ToolTipRole)) { // DisplayRole is just basename, ToolTipRole contains full path open(roleDataMap[Qt::ToolTipRole].toString()); event->acceptProposedAction(); } } else if (mimeData->hasUrls()) { openMultiple(mimeData->urls()); event->acceptProposedAction(); } else if (mimeData->hasFormat(Mlt::XmlMimeType )) { m_playlistDock->on_actionOpen_triggered(); event->acceptProposedAction(); } } void MainWindow::closeEvent(QCloseEvent* event) { if (continueJobsRunning() && continueModified()) { if (!m_htmlEditor || m_htmlEditor->close()) { LOG_DEBUG() << "begin"; JOBS.cleanup(); writeSettings(); if (m_exitCode == EXIT_SUCCESS) { MLT.stop(); } else { if (multitrack()) m_timelineDock->model()->close(); if (playlist()) m_playlistDock->model()->close(); else onMultitrackClosed(); } QThreadPool::globalInstance()->clear(); AudioLevelsTask::closeAll(); event->accept(); emit aboutToShutDown(); if (m_exitCode == EXIT_SUCCESS) { QApplication::quit(); LOG_DEBUG() << "end"; ::_Exit(0); } else { QApplication::exit(m_exitCode); LOG_DEBUG() << "end"; } return; } } event->ignore(); } void MainWindow::showEvent(QShowEvent* event) { // This is needed to prevent a crash on windows on startup when timeline // is visible and dock title bars are hidden. Q_UNUSED(event) ui->actionShowTitleBars->setChecked(Settings.showTitleBars()); on_actionShowTitleBars_triggered(Settings.showTitleBars()); ui->actionShowToolbar->setChecked(Settings.showToolBar()); on_actionShowToolbar_triggered(Settings.showToolBar()); ui->actionShowTextUnderIcons->setChecked(Settings.textUnderIcons()); on_actionShowTextUnderIcons_toggled(Settings.textUnderIcons()); ui->actionShowSmallIcons->setChecked(Settings.smallIcons()); on_actionShowSmallIcons_toggled(Settings.smallIcons()); windowHandle()->installEventFilter(this); #ifndef SHOTCUT_NOUPGRADE if (!Settings.noUpgrade() && !qApp->property("noupgrade").toBool()) QTimer::singleShot(0, this, SLOT(showUpgradePrompt())); #endif } void MainWindow::on_actionOpenOther_triggered() { // these static are used to open dialog with previous configuration OpenOtherDialog dialog(this); if (MLT.producer()) dialog.load(MLT.producer()); if (dialog.exec() == QDialog::Accepted) { closeProducer(); open(dialog.newProducer(MLT.profile())); } } void MainWindow::onProducerOpened(bool withReopen) { QWidget* w = loadProducerWidget(MLT.producer()); if (withReopen && w && !MLT.producer()->get(kMultitrackItemProperty)) { if (-1 != w->metaObject()->indexOfSignal("producerReopened()")) connect(w, SIGNAL(producerReopened()), m_player, SLOT(onProducerOpened())); } else if (MLT.isPlaylist()) { m_playlistDock->model()->load(); if (playlist()) { m_isPlaylistLoaded = true; m_player->setIn(-1); m_player->setOut(-1); m_playlistDock->setVisible(true); m_playlistDock->raise(); m_player->enableTab(Player::ProjectTabIndex); m_player->switchToTab(Player::ProjectTabIndex); } } else if (MLT.isMultitrack()) { m_timelineDock->blockSelection(true); m_timelineDock->model()->load(); m_timelineDock->blockSelection(false); if (isMultitrackValid()) { m_player->setIn(-1); m_player->setOut(-1); m_timelineDock->setVisible(true); m_timelineDock->raise(); m_player->enableTab(Player::ProjectTabIndex); m_player->switchToTab(Player::ProjectTabIndex); m_timelineDock->selectMultitrack(); QTimer::singleShot(0, [=]() { m_timelineDock->setSelection(); }); } } if (MLT.isClip()) { m_player->enableTab(Player::SourceTabIndex); m_player->switchToTab(Player::SourceTabIndex); Util::getHash(*MLT.producer()); ui->actionPaste->setEnabled(true); } QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile) setCurrentFile(m_autosaveFile->managedFileName()); else if (!MLT.URL().isEmpty()) setCurrentFile(MLT.URL()); on_actionJack_triggered(ui->actionJack && ui->actionJack->isChecked()); } void MainWindow::onProducerChanged() { MLT.refreshConsumer(); if (playlist() && MLT.producer() && MLT.producer()->is_valid() && MLT.producer()->get_int(kPlaylistIndexProperty)) m_playlistDock->setUpdateButtonEnabled(true); } bool MainWindow::on_actionSave_triggered() { if (m_currentFile.isEmpty()) { return on_actionSave_As_triggered(); } else { if (Util::warnIfNotWritable(m_currentFile, this, tr("Save XML"))) return false; bool success = saveXML(m_currentFile); QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(new AutoSaveFile(m_currentFile)); setCurrentFile(m_currentFile); setWindowModified(false); if (success) { showStatusMessage(tr("Saved %1").arg(m_currentFile)); } else { showSaveError(); } m_undoStack->setClean(); return true; } } bool MainWindow::on_actionSave_As_triggered() { QString path = Settings.savePath(); if (!m_currentFile.isEmpty()) path = m_currentFile; QString caption = tr("Save XML"); QString filename = QFileDialog::getSaveFileName(this, caption, path, tr("MLT XML (*.mlt)")); if (!filename.isEmpty()) { QFileInfo fi(filename); Settings.setSavePath(fi.path()); if (fi.suffix() != "mlt") filename += ".mlt"; if (Util::warnIfNotWritable(filename, this, caption)) return false; newProject(filename); } return !filename.isEmpty(); } bool MainWindow::continueModified() { if (isWindowModified()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("The project has been modified.\n" "Do you want to save your changes?"), QMessageBox::No | QMessageBox::Cancel | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::Cancel); int r = dialog.exec(); if (r == QMessageBox::Yes || r == QMessageBox::No) { if (r == QMessageBox::Yes) { return on_actionSave_triggered(); } else { QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(); } } else if (r == QMessageBox::Cancel) { return false; } } return true; } bool MainWindow::continueJobsRunning() { if (JOBS.hasIncomplete()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("There are incomplete jobs.\n" "Do you want to still want to exit?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); return (dialog.exec() == QMessageBox::Yes); } if (m_encodeDock->isExportInProgress()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("An export is in progress.\n" "Do you want to still want to exit?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); return (dialog.exec() == QMessageBox::Yes); } return true; } QUndoStack* MainWindow::undoStack() const { return m_undoStack; } void MainWindow::onEncodeTriggered(bool checked) { if (checked) { m_encodeDock->show(); m_encodeDock->raise(); } } void MainWindow::onCaptureStateChanged(bool started) { if (started && (MLT.resource().startsWith("x11grab:") || MLT.resource().startsWith("gdigrab:") || MLT.resource().startsWith("avfoundation")) && !MLT.producer()->get_int(kBackgroundCaptureProperty)) showMinimized(); } void MainWindow::onJobsDockTriggered(bool checked) { if (checked) { m_jobsDock->show(); m_jobsDock->raise(); } } void MainWindow::onRecentDockTriggered(bool checked) { if (checked) { m_recentDock->show(); m_recentDock->raise(); } } void MainWindow::onPropertiesDockTriggered(bool checked) { if (checked) { m_propertiesDock->show(); m_propertiesDock->raise(); } } void MainWindow::onPlaylistDockTriggered(bool checked) { if (checked) { m_playlistDock->show(); m_playlistDock->raise(); } } void MainWindow::onTimelineDockTriggered(bool checked) { if (checked) { m_timelineDock->show(); m_timelineDock->raise(); } } void MainWindow::onHistoryDockTriggered(bool checked) { if (checked) { m_historyDock->show(); m_historyDock->raise(); } } void MainWindow::onFiltersDockTriggered(bool checked) { if (checked) { m_filtersDock->show(); m_filtersDock->raise(); } } void MainWindow::onKeyframesDockTriggered(bool checked) { if (checked) { m_keyframesDock->show(); m_keyframesDock->raise(); } } void MainWindow::onPlaylistCreated() { if (!playlist() || playlist()->count() == 0) return; m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onPlaylistLoaded() { updateMarkers(); m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onPlaylistCleared() { m_player->onTabBarClicked(Player::SourceTabIndex); setWindowModified(true); } void MainWindow::onPlaylistClosed() { closeProducer(); setProfile(Settings.playerProfile()); resetVideoModeMenu(); setAudioChannels(Settings.playerAudioChannels()); setCurrentFile(""); setWindowModified(false); m_undoStack->clear(); MLT.resetURL(); QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(new AutoSaveFile(untitledFileName())); if (!isMultitrackValid()) m_player->enableTab(Player::ProjectTabIndex, false); } void MainWindow::onPlaylistModified() { setWindowModified(true); if (MLT.producer() && playlist() && (void*) MLT.producer()->get_producer() == (void*) playlist()->get_playlist()) m_player->onDurationChanged(); updateMarkers(); m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onMultitrackCreated() { m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onMultitrackClosed() { setAudioChannels(Settings.playerAudioChannels()); closeProducer(); setProfile(Settings.playerProfile()); resetVideoModeMenu(); setCurrentFile(""); setWindowModified(false); m_undoStack->clear(); MLT.resetURL(); QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(new AutoSaveFile(untitledFileName())); if (!playlist() || playlist()->count() == 0) m_player->enableTab(Player::ProjectTabIndex, false); } void MainWindow::onMultitrackModified() { setWindowModified(true); // Reflect this playlist info onto the producer for keyframes dock. if (!m_timelineDock->selection().isEmpty()) { int trackIndex = m_timelineDock->selection().first().y(); int clipIndex = m_timelineDock->selection().first().x(); QScopedPointer<Mlt::ClipInfo> info(m_timelineDock->getClipInfo(trackIndex, clipIndex)); if (info && info->producer && info->producer->is_valid()) { int expected = info->frame_in; QScopedPointer<Mlt::ClipInfo> info2(m_timelineDock->getClipInfo(trackIndex, clipIndex - 1)); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition left of the clip. expected -= info2->frame_count; info->producer->set(kPlaylistStartProperty, info2->start); } else { info->producer->set(kPlaylistStartProperty, info->start); } if (expected != info->producer->get_int(kFilterInProperty)) { int delta = expected - info->producer->get_int(kFilterInProperty); info->producer->set(kFilterInProperty, expected); emit m_filtersDock->producerInChanged(delta); } expected = info->frame_out; info2.reset(m_timelineDock->getClipInfo(trackIndex, clipIndex + 1)); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition right of the clip. expected += info2->frame_count; } if (expected != info->producer->get_int(kFilterOutProperty)) { int delta = expected - info->producer->get_int(kFilterOutProperty); info->producer->set(kFilterOutProperty, expected); emit m_filtersDock->producerOutChanged(delta); } } } } void MainWindow::onMultitrackDurationChanged() { if (MLT.producer() && (void*) MLT.producer()->get_producer() == (void*) multitrack()->get_producer()) m_player->onDurationChanged(); } void MainWindow::onCutModified() { if (!playlist() && !multitrack()) { setWindowModified(true); updateAutoSave(); } if (playlist()) m_playlistDock->setUpdateButtonEnabled(true); } void MainWindow::onProducerModified() { setWindowModified(true); updateAutoSave(); } void MainWindow::onFilterModelChanged() { MLT.refreshConsumer(); setWindowModified(true); updateAutoSave(); if (playlist()) m_playlistDock->setUpdateButtonEnabled(true); } void MainWindow::updateMarkers() { if (playlist() && MLT.isPlaylist()) { QList<int> markers; int n = playlist()->count(); for (int i = 0; i < n; i++) markers.append(playlist()->clip_start(i)); m_player->setMarkers(markers); } } void MainWindow::updateThumbnails() { if (Settings.playlistThumbnails() != "hidden") m_playlistDock->model()->refreshThumbnails(); } void MainWindow::on_actionUndo_triggered() { TimelineSelectionBlocker blocker(*m_timelineDock); m_undoStack->undo(); } void MainWindow::on_actionRedo_triggered() { TimelineSelectionBlocker blocker(*m_timelineDock); m_undoStack->redo(); } void MainWindow::on_actionFAQ_triggered() { QDesktopServices::openUrl(QUrl("https://www.shotcut.org/FAQ/")); } void MainWindow::on_actionForum_triggered() { QDesktopServices::openUrl(QUrl("https://forum.shotcut.org/")); } bool MainWindow::saveXML(const QString &filename, bool withRelativePaths) { bool result; if (m_timelineDock->model()->rowCount() > 0) { result = MLT.saveXML(filename, multitrack(), withRelativePaths); } else if (m_playlistDock->model()->rowCount() > 0) { int in = MLT.producer()->get_in(); int out = MLT.producer()->get_out(); MLT.producer()->set_in_and_out(0, MLT.producer()->get_length() - 1); result = MLT.saveXML(filename, playlist(), withRelativePaths); MLT.producer()->set_in_and_out(in, out); } else if (MLT.producer()) { result = MLT.saveXML(filename, (MLT.isMultitrack() || MLT.isPlaylist())? MLT.savedProducer() : 0, withRelativePaths); } else { // Save an empty playlist, which is accepted by both MLT and Shotcut. Mlt::Playlist playlist(MLT.profile()); result = MLT.saveXML(filename, &playlist, withRelativePaths); } return result; } void MainWindow::changeTheme(const QString &theme) { LOG_DEBUG() << "begin"; if (theme == "dark") { QApplication::setStyle("Fusion"); QPalette palette; palette.setColor(QPalette::Window, QColor(50,50,50)); palette.setColor(QPalette::WindowText, QColor(220,220,220)); palette.setColor(QPalette::Base, QColor(30,30,30)); palette.setColor(QPalette::AlternateBase, QColor(40,40,40)); palette.setColor(QPalette::Highlight, QColor(23,92,118)); palette.setColor(QPalette::HighlightedText, Qt::white); palette.setColor(QPalette::ToolTipBase, palette.color(QPalette::Highlight)); palette.setColor(QPalette::ToolTipText, palette.color(QPalette::WindowText)); palette.setColor(QPalette::Text, palette.color(QPalette::WindowText)); palette.setColor(QPalette::BrightText, Qt::red); palette.setColor(QPalette::Button, palette.color(QPalette::Window)); palette.setColor(QPalette::ButtonText, palette.color(QPalette::WindowText)); palette.setColor(QPalette::Link, palette.color(QPalette::Highlight).lighter()); palette.setColor(QPalette::LinkVisited, palette.color(QPalette::Highlight)); palette.setColor(QPalette::Disabled, QPalette::Text, Qt::darkGray); palette.setColor(QPalette::Disabled, QPalette::ButtonText, Qt::darkGray); QApplication::setPalette(palette); QIcon::setThemeName("dark"); } else if (theme == "light") { QStyle* style = QStyleFactory::create("Fusion"); QApplication::setStyle(style); QApplication::setPalette(style->standardPalette()); QIcon::setThemeName("light"); } else { QApplication::setStyle(qApp->property("system-style").toString()); QIcon::setThemeName("oxygen"); } emit QmlApplication::singleton().paletteChanged(); LOG_DEBUG() << "end"; } Mlt::Playlist* MainWindow::playlist() const { return m_playlistDock->model()->playlist(); } bool MainWindow::isPlaylistValid() const { return m_playlistDock->model()->playlist() && m_playlistDock->model()->rowCount() > 0; } Mlt::Producer *MainWindow::multitrack() const { return m_timelineDock->model()->tractor(); } bool MainWindow::isMultitrackValid() const { return m_timelineDock->model()->tractor() && !m_timelineDock->model()->trackList().empty(); } QWidget *MainWindow::loadProducerWidget(Mlt::Producer* producer) { QWidget* w = 0; QScrollArea* scrollArea = (QScrollArea*) m_propertiesDock->widget(); if (!producer || !producer->is_valid()) { if (scrollArea->widget()) scrollArea->widget()->deleteLater(); return w; } else { scrollArea->show(); } QString service(producer->get("mlt_service")); QString resource = QString::fromUtf8(producer->get("resource")); QString shotcutProducer(producer->get(kShotcutProducerProperty)); if (resource.startsWith("video4linux2:") || QString::fromUtf8(producer->get("resource1")).startsWith("video4linux2:")) w = new Video4LinuxWidget(this); else if (resource.startsWith("pulse:")) w = new PulseAudioWidget(this); else if (resource.startsWith("jack:")) w = new JackProducerWidget(this); else if (resource.startsWith("alsa:")) w = new AlsaWidget(this); else if (resource.startsWith("dshow:") || QString::fromUtf8(producer->get("resource1")).startsWith("dshow:")) w = new DirectShowVideoWidget(this); else if (resource.startsWith("avfoundation:")) w = new AvfoundationProducerWidget(this); else if (resource.startsWith("x11grab:")) w = new X11grabWidget(this); else if (resource.startsWith("gdigrab:")) w = new GDIgrabWidget(this); else if (service.startsWith("avformat") || shotcutProducer == "avformat") w = new AvformatProducerWidget(this); else if (MLT.isImageProducer(producer)) { w = new ImageProducerWidget(this); connect(m_player, SIGNAL(outChanged(int)), w, SLOT(updateDuration())); } else if (service == "decklink" || resource.contains("decklink")) w = new DecklinkProducerWidget(this); else if (service == "color") w = new ColorProducerWidget(this); else if (service == "noise") w = new NoiseWidget(this); else if (service == "frei0r.ising0r") w = new IsingWidget(this); else if (service == "frei0r.lissajous0r") w = new LissajousWidget(this); else if (service == "frei0r.plasma") w = new PlasmaWidget(this); else if (service == "frei0r.test_pat_B") w = new ColorBarsWidget(this); else if (service == "webvfx") w = new WebvfxProducer(this); else if (service == "tone") w = new ToneProducerWidget(this); else if (service == "count") w = new CountProducerWidget(this); else if (service == "blipflash") w = new BlipProducerWidget(this); else if (producer->parent().get(kShotcutTransitionProperty)) { w = new LumaMixTransition(producer->parent(), this); scrollArea->setWidget(w); if (-1 != w->metaObject()->indexOfSignal("modified()")) connect(w, SIGNAL(modified()), SLOT(onProducerModified())); return w; } else if (playlist_type == producer->type()) { int trackIndex = m_timelineDock->currentTrack(); bool isBottomVideo = m_timelineDock->model()->data(m_timelineDock->model()->index(trackIndex), MultitrackModel::IsBottomVideoRole).toBool(); if (!isBottomVideo) { w = new TrackPropertiesWidget(*producer, this); scrollArea->setWidget(w); return w; } } else if (tractor_type == producer->type()) { w = new TimelinePropertiesWidget(*producer, this); scrollArea->setWidget(w); return w; } if (w) { dynamic_cast<AbstractProducerWidget*>(w)->setProducer(producer); if (-1 != w->metaObject()->indexOfSignal("producerChanged(Mlt::Producer*)")) { connect(w, SIGNAL(producerChanged(Mlt::Producer*)), SLOT(onProducerChanged())); connect(w, SIGNAL(producerChanged(Mlt::Producer*)), m_filterController, SLOT(setProducer(Mlt::Producer*))); connect(w, SIGNAL(producerChanged(Mlt::Producer*)), m_playlistDock, SLOT(onProducerChanged(Mlt::Producer*))); if (producer->get(kMultitrackItemProperty)) connect(w, SIGNAL(producerChanged(Mlt::Producer*)), m_timelineDock, SLOT(onProducerChanged(Mlt::Producer*))); } if (-1 != w->metaObject()->indexOfSignal("modified()")) { connect(w, SIGNAL(modified()), SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_playlistDock, SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_timelineDock, SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_keyframesDock, SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_filterController, SLOT(onProducerChanged())); } if (-1 != w->metaObject()->indexOfSlot("updateDuration()")) { connect(m_timelineDock, SIGNAL(durationChanged()), w, SLOT(updateDuration())); } if (-1 != w->metaObject()->indexOfSlot("rename()")) { connect(this, SIGNAL(renameRequested()), w, SLOT(rename())); } scrollArea->setWidget(w); onProducerChanged(); } else if (scrollArea->widget()) { scrollArea->widget()->deleteLater(); } return w; } void MainWindow::on_actionEnter_Full_Screen_triggered() { #ifdef Q_OS_WIN bool isFull = isMaximized(); #else bool isFull = isFullScreen(); #endif if (isFull) { showNormal(); ui->actionEnter_Full_Screen->setText(tr("Enter Full Screen")); } else { #ifdef Q_OS_WIN showMaximized(); #else showFullScreen(); #endif ui->actionEnter_Full_Screen->setText(tr("Enter Full Screen")); } } void MainWindow::onGpuNotSupported() { Settings.setPlayerGPU(false); if (ui->actionGPU) { ui->actionGPU->setChecked(false); ui->actionGPU->setDisabled(true); } LOG_WARNING() << ""; QMessageBox::critical(this, qApp->applicationName(), tr("GPU effects are not supported")); } void MainWindow::editHTML(const QString &fileName) { bool isNew = !m_htmlEditor; if (isNew) { m_htmlEditor.reset(new HtmlEditor); m_htmlEditor->setWindowIcon(windowIcon()); } m_htmlEditor->load(fileName); m_htmlEditor->show(); m_htmlEditor->raise(); bool isExternal = false; int screen = Settings.playerExternal().toInt(&isExternal); isExternal = isExternal && (screen != QApplication::desktop()->screenNumber(this)); if (!isExternal) { if (Settings.playerZoom() >= 1.0f) { m_htmlEditor->changeZoom(100 * m_player->videoSize().width() / MLT.profile().width()); m_htmlEditor->resizeWebView(m_player->videoSize().width(), m_player->videoSize().height()); } else { m_htmlEditor->changeZoom(100 * MLT.displayWidth() / MLT.profile().width()); m_htmlEditor->resizeWebView(MLT.displayWidth(), MLT.displayHeight()); } } else { m_htmlEditor->changeZoom(100); } if (isNew) { // Center the new window over the main window. QPoint point = pos(); QPoint halfSize(width(), height()); halfSize /= 2; point += halfSize; halfSize = QPoint(m_htmlEditor->width(), m_htmlEditor->height()); halfSize /= 2; point -= halfSize; m_htmlEditor->move(point); } } void MainWindow::stepLeftOneFrame() { m_player->seek(m_player->position() - 1); } void MainWindow::stepRightOneFrame() { m_player->seek(m_player->position() + 1); } void MainWindow::stepLeftOneSecond() { stepLeftBySeconds(-1); } void MainWindow::stepRightOneSecond() { stepLeftBySeconds(1); } void MainWindow::setInToCurrent(bool ripple) { if (m_player->tabIndex() == Player::ProjectTabIndex && isMultitrackValid()) { m_timelineDock->trimClipAtPlayhead(TimelineDock::TrimInPoint, ripple); } else if (MLT.isSeekable() && MLT.isClip()) { m_player->setIn(m_player->position()); int delta = m_player->position() - MLT.producer()->get_in(); emit m_player->inChanged(delta); } } void MainWindow::setOutToCurrent(bool ripple) { if (m_player->tabIndex() == Player::ProjectTabIndex && isMultitrackValid()) { m_timelineDock->trimClipAtPlayhead(TimelineDock::TrimOutPoint, ripple); } else if (MLT.isSeekable() && MLT.isClip()) { m_player->setOut(m_player->position()); int delta = m_player->position() - MLT.producer()->get_out(); emit m_player->outChanged(delta); } } void MainWindow::onShuttle(float x) { if (x == 0) { m_player->pause(); } else if (x > 0) { m_player->play(10.0 * x); } else { m_player->play(20.0 * x); } } void MainWindow::showUpgradePrompt() { if (Settings.checkUpgradeAutomatic()) { showStatusMessage("Checking for upgrade..."); m_network.get(QNetworkRequest(QUrl("https://check.shotcut.org/version.json"))); } else { QAction* action = new QAction(tr("Click here to check for a new version of Shotcut."), 0); connect(action, SIGNAL(triggered(bool)), SLOT(on_actionUpgrade_triggered())); showStatusMessage(action, 15 /* seconds */); } } void MainWindow::on_actionRealtime_triggered(bool checked) { Settings.setPlayerRealtime(checked); if (Settings.playerGPU()) MLT.pause(); if (MLT.consumer()) { MLT.restart(); } } void MainWindow::on_actionProgressive_triggered(bool checked) { MLT.videoWidget()->setProperty("progressive", checked); if (Settings.playerGPU()) MLT.pause(); if (MLT.consumer()) { MLT.profile().set_progressive(checked); MLT.updatePreviewProfile(); MLT.restart(); } Settings.setPlayerProgressive(checked); } void MainWindow::changeAudioChannels(bool checked, int channels) { if( checked ) { Settings.setPlayerAudioChannels(channels); setAudioChannels(Settings.playerAudioChannels()); } } void MainWindow::on_actionChannels1_triggered(bool checked) { changeAudioChannels(checked, 1); } void MainWindow::on_actionChannels2_triggered(bool checked) { changeAudioChannels(checked, 2); } void MainWindow::on_actionChannels6_triggered(bool checked) { changeAudioChannels(checked, 6); } void MainWindow::changeDeinterlacer(bool checked, const char* method) { if (checked) { MLT.videoWidget()->setProperty("deinterlace_method", method); if (MLT.consumer()) { MLT.consumer()->set("deinterlace_method", method); MLT.refreshConsumer(); } } Settings.setPlayerDeinterlacer(method); } void MainWindow::on_actionOneField_triggered(bool checked) { changeDeinterlacer(checked, "onefield"); } void MainWindow::on_actionLinearBlend_triggered(bool checked) { changeDeinterlacer(checked, "linearblend"); } void MainWindow::on_actionYadifTemporal_triggered(bool checked) { changeDeinterlacer(checked, "yadif-nospatial"); } void MainWindow::on_actionYadifSpatial_triggered(bool checked) { changeDeinterlacer(checked, "yadif"); } void MainWindow::changeInterpolation(bool checked, const char* method) { if (checked) { MLT.videoWidget()->setProperty("rescale", method); if (MLT.consumer()) { MLT.consumer()->set("rescale", method); MLT.refreshConsumer(); } } Settings.setPlayerInterpolation(method); } void MainWindow::processMultipleFiles() { if (m_multipleFiles.length() <= 0) return; QStringList multipleFiles = m_multipleFiles; m_multipleFiles.clear(); int count = multipleFiles.length(); if (count > 1) { LongUiTask longTask(tr("Open Files")); m_playlistDock->show(); m_playlistDock->raise(); for (int i = 0; i < count; i++) { QString filename = multipleFiles.takeFirst(); LOG_DEBUG() << filename; longTask.reportProgress(QFileInfo(filename).fileName(), i, count); Mlt::Producer p(MLT.profile(), filename.toUtf8().constData()); if (p.is_valid()) { // Convert avformat to avformat-novalidate so that XML loads faster. if (!qstrcmp(p.get("mlt_service"), "avformat")) { p.set("mlt_service", "avformat-novalidate"); p.set("mute_on_pause", 0); } if (QDir::toNativeSeparators(filename) == QDir::toNativeSeparators(MAIN.fileName())) { MAIN.showStatusMessage(QObject::tr("You cannot add a project to itself!")); continue; } MLT.setImageDurationFromDefault(&p); MLT.lockCreationTime(&p); p.get_length_time(mlt_time_clock); Util::getHash(p); ProxyManager::generateIfNotExists(p); undoStack()->push(new Playlist::AppendCommand(*m_playlistDock->model(), MLT.XML(&p), false)); m_recentDock->add(filename.toUtf8().constData()); } } emit m_playlistDock->model()->modified(); } if (m_isPlaylistLoaded && Settings.playerGPU()) { updateThumbnails(); m_isPlaylistLoaded = false; } } void MainWindow::onLanguageTriggered(QAction* action) { Settings.setLanguage(action->data().toString()); QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart Shotcut to switch to the new language.\n" "Do you want to restart now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } } void MainWindow::on_actionNearest_triggered(bool checked) { changeInterpolation(checked, "nearest"); } void MainWindow::on_actionBilinear_triggered(bool checked) { changeInterpolation(checked, "bilinear"); } void MainWindow::on_actionBicubic_triggered(bool checked) { changeInterpolation(checked, "bicubic"); } void MainWindow::on_actionHyper_triggered(bool checked) { changeInterpolation(checked, "hyper"); } void MainWindow::on_actionJack_triggered(bool checked) { Settings.setPlayerJACK(checked); if (!MLT.enableJack(checked)) { if (ui->actionJack) ui->actionJack->setChecked(false); Settings.setPlayerJACK(false); QMessageBox::warning(this, qApp->applicationName(), tr("Failed to connect to JACK.\nPlease verify that JACK is installed and running.")); } } void MainWindow::on_actionGPU_triggered(bool checked) { if (checked) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("GPU effects are experimental and may cause instability on some systems. " "Some CPU effects are incompatible with GPU effects and will be disabled. " "A project created with GPU effects can not be converted to a CPU only project later." "\n\n" "Do you want to enable GPU effects and restart Shotcut?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } else { ui->actionGPU->setChecked(false); } } else { QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("Shotcut must restart to disable GPU effects." "\n\n" "Disable GPU effects and restart?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } else { ui->actionGPU->setChecked(true); } } } void MainWindow::onExternalTriggered(QAction *action) { LOG_DEBUG() << action->data().toString(); bool isExternal = !action->data().toString().isEmpty(); Settings.setPlayerExternal(action->data().toString()); MLT.stop(); bool ok = false; int screen = action->data().toInt(&ok); if (ok || action->data().toString().isEmpty()) { m_player->moveVideoToScreen(ok? screen : -2); isExternal = false; MLT.videoWidget()->setProperty("mlt_service", QVariant()); } else { m_player->moveVideoToScreen(-2); MLT.videoWidget()->setProperty("mlt_service", action->data()); } QString profile = Settings.playerProfile(); // Automatic not permitted for SDI/HDMI if (isExternal && profile.isEmpty()) { profile = "atsc_720p_50"; Settings.setPlayerProfile(profile); setProfile(profile); MLT.restart(); foreach (QAction* a, m_profileGroup->actions()) { if (a->data() == profile) { a->setChecked(true); break; } } } else { MLT.consumerChanged(); } // Automatic not permitted for SDI/HDMI m_profileGroup->actions().at(0)->setEnabled(!isExternal); // Disable progressive option when SDI/HDMI ui->actionProgressive->setEnabled(!isExternal); bool isProgressive = isExternal ? MLT.profile().progressive() : ui->actionProgressive->isChecked(); MLT.videoWidget()->setProperty("progressive", isProgressive); if (MLT.consumer()) { MLT.consumer()->set("progressive", isProgressive); MLT.restart(); } if (m_keyerMenu) m_keyerMenu->setEnabled(action->data().toString().startsWith("decklink")); #if LIBMLT_VERSION_INT >= MLT_VERSION_PREVIEW_SCALE // Preview scaling not permitted for SDI/HDMI if (isExternal) { setPreviewScale(0); m_previewScaleGroup->setEnabled(false); } else { setPreviewScale(Settings.playerPreviewScale()); m_previewScaleGroup->setEnabled(true); } #endif } void MainWindow::onKeyerTriggered(QAction *action) { LOG_DEBUG() << action->data().toString(); MLT.videoWidget()->setProperty("keyer", action->data()); MLT.consumerChanged(); Settings.setPlayerKeyerMode(action->data().toInt()); } void MainWindow::onProfileTriggered(QAction *action) { Settings.setPlayerProfile(action->data().toString()); if (MLT.producer() && MLT.producer()->is_valid()) { // Save the XML to get correct in/out points before profile is changed. QString xml = MLT.XML(); setProfile(action->data().toString()); MLT.restart(xml); onProducerOpened(false); } else { setProfile(action->data().toString()); } } void MainWindow::onProfileChanged() { if (multitrack() && MLT.isMultitrack() && (m_timelineDock->selection().isEmpty() || m_timelineDock->currentTrack() == -1)) { emit m_timelineDock->selected(multitrack()); } } void MainWindow::on_actionAddCustomProfile_triggered() { QString xml; if (MLT.producer() && MLT.producer()->is_valid()) { // Save the XML to get correct in/out points before profile is changed. xml = MLT.XML(); } CustomProfileDialog dialog(this); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QDialog::Accepted) { QString name = dialog.profileName(); if (!name.isEmpty()) { addCustomProfile(name, customProfileMenu(), actionProfileRemove(), profileGroup()); } else if (m_profileGroup->checkedAction()) { m_profileGroup->checkedAction()->setChecked(false); } // Use the new profile. emit profileChanged(); if (!xml.isEmpty()) { MLT.restart(xml); onProducerOpened(false); } } } void MainWindow::on_actionSystemTheme_triggered() { changeTheme("system"); QApplication::setPalette(QApplication::style()->standardPalette()); Settings.setTheme("system"); } void MainWindow::on_actionFusionDark_triggered() { changeTheme("dark"); Settings.setTheme("dark"); ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); } void MainWindow::on_actionFusionLight_triggered() { changeTheme("light"); Settings.setTheme("light"); ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); } void MainWindow::on_actionTutorials_triggered() { QDesktopServices::openUrl(QUrl("https://www.shotcut.org/tutorials/")); } void MainWindow::on_actionRestoreLayout_triggered() { restoreGeometry(Settings.windowGeometryDefault()); restoreState(Settings.windowStateDefault()); on_actionLayoutTimeline_triggered(); ui->actionShowTitleBars->setChecked(true); on_actionShowTitleBars_triggered(true); ui->actionShowTextUnderIcons->setChecked(true); on_actionShowTextUnderIcons_toggled(true); ui->actionShowSmallIcons->setChecked(false); on_actionShowSmallIcons_toggled(false); } void MainWindow::on_actionShowTitleBars_triggered(bool checked) { QList <QDockWidget *> docks = findChildren<QDockWidget *>(); for (int i = 0; i < docks.count(); i++) { QDockWidget* dock = docks.at(i); if (checked) { dock->setTitleBarWidget(0); } else { if (!dock->isFloating()) { dock->setTitleBarWidget(new QWidget); } } } Settings.setShowTitleBars(checked); } void MainWindow::on_actionShowToolbar_triggered(bool checked) { ui->mainToolBar->setVisible(checked); } void MainWindow::onToolbarVisibilityChanged(bool visible) { ui->actionShowToolbar->setChecked(visible); Settings.setShowToolBar(visible); } void MainWindow::on_menuExternal_aboutToShow() { foreach (QAction* action, m_externalGroup->actions()) { bool ok = false; int i = action->data().toInt(&ok); if (ok) { if (i == QApplication::desktop()->screenNumber(this)) { if (action->isChecked()) { m_externalGroup->actions().first()->setChecked(true); Settings.setPlayerExternal(QString()); } action->setDisabled(true); } else { action->setEnabled(true); } } } } void MainWindow::on_actionUpgrade_triggered() { if (Settings.askUpgradeAutmatic()) { QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Do you want to automatically check for updates in the future?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setCheckBox(new QCheckBox(tr("Do not show this anymore.", "Automatic upgrade check dialog"))); Settings.setCheckUpgradeAutomatic(dialog.exec() == QMessageBox::Yes); if (dialog.checkBox()->isChecked()) Settings.setAskUpgradeAutomatic(false); } showStatusMessage("Checking for upgrade..."); m_network.get(QNetworkRequest(QUrl("https://check.shotcut.org/version.json"))); } void MainWindow::on_actionOpenXML_triggered() { QString path = Settings.openPath(); #ifdef Q_OS_MAC path.append("/*"); #endif QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path, tr("MLT XML (*.mlt);;All Files (*)")); if (filenames.length() > 0) { QString url = filenames.first(); MltXmlChecker checker; if (checker.check(url)) { if (!isCompatibleWithGpuMode(checker)) return; isXmlRepaired(checker, url); // Check if the locale usage differs. // Get current locale. QString localeName = QString(::setlocale(MLT_LC_CATEGORY, nullptr)).toUpper(); // Test if it is C or POSIX. bool currentlyUsingLocale = (localeName != "" && localeName != "C" && localeName != "POSIX"); if (currentlyUsingLocale != checker.usesLocale()) { // Show a warning dialog and cancel if requested. QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("The decimal point of the MLT XML file\nyou want to open is incompatible.\n\n" "Do you want to continue to open this MLT XML file?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::No); dialog.setEscapeButton(QMessageBox::No); if (dialog.exec() != QMessageBox::Yes) return; } } Settings.setOpenPath(QFileInfo(url).path()); activateWindow(); if (filenames.length() > 1) m_multipleFiles = filenames; if (!MLT.openXML(url)) { open(MLT.producer()); m_recentDock->add(url); LOG_INFO() << url; } else { showStatusMessage(tr("Failed to open ") + url); emit openFailed(url); } } } void MainWindow::on_actionGammaSRGB_triggered(bool checked) { Q_UNUSED(checked) Settings.setPlayerGamma("iec61966_2_1"); MLT.restart(); MLT.refreshConsumer(); } void MainWindow::on_actionGammaRec709_triggered(bool checked) { Q_UNUSED(checked) Settings.setPlayerGamma("bt709"); MLT.restart(); MLT.refreshConsumer(); } void MainWindow::onFocusChanged(QWidget *, QWidget * ) const { LOG_DEBUG() << "Focuswidget changed"; LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); } void MainWindow::on_actionScrubAudio_triggered(bool checked) { Settings.setPlayerScrubAudio(checked); } #if !defined(Q_OS_MAC) void MainWindow::onDrawingMethodTriggered(QAction *action) { Settings.setDrawMethod(action->data().toInt()); QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart Shotcut to change the display method.\n" "Do you want to restart now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } } #endif void MainWindow::on_actionApplicationLog_triggered() { TextViewerDialog dialog(this); QDir dir = Settings.appDataLocation(); QFile logFile(dir.filePath("shotcut-log.txt")); logFile.open(QIODevice::ReadOnly | QIODevice::Text); dialog.setText(logFile.readAll()); logFile.close(); dialog.setWindowTitle(tr("Application Log")); dialog.exec(); } void MainWindow::on_actionClose_triggered() { if (continueModified()) { LOG_DEBUG() << ""; MLT.setProjectFolder(QString()); MLT.stop(); if (multitrack()) m_timelineDock->model()->close(); if (playlist()) m_playlistDock->model()->close(); else onMultitrackClosed(); m_player->enableTab(Player::SourceTabIndex, false); MLT.purgeMemoryPool(); MLT.resetLocale(); } } void MainWindow::onPlayerTabIndexChanged(int index) { if (Player::SourceTabIndex == index) m_timelineDock->saveAndClearSelection(); else m_timelineDock->restoreSelection(); } void MainWindow::onUpgradeCheckFinished(QNetworkReply* reply) { if (!reply->error()) { QByteArray response = reply->readAll(); LOG_DEBUG() << "response: " << response; QJsonDocument json = QJsonDocument::fromJson(response); QString current = qApp->applicationVersion(); if (!json.isNull() && json.object().value("version_string").type() == QJsonValue::String) { QString latest = json.object().value("version_string").toString(); if (current != "adhoc" && QVersionNumber::fromString(current) < QVersionNumber::fromString(latest)) { QAction* action = new QAction(tr("Shotcut version %1 is available! Click here to get it.").arg(latest), 0); connect(action, SIGNAL(triggered(bool)), SLOT(onUpgradeTriggered())); if (!json.object().value("url").isUndefined()) m_upgradeUrl = json.object().value("url").toString(); showStatusMessage(action, 15 /* seconds */); } else { showStatusMessage(tr("You are running the latest version of Shotcut.")); } reply->deleteLater(); return; } else { LOG_WARNING() << "failed to parse version.json"; } } else { LOG_WARNING() << reply->errorString(); } QAction* action = new QAction(tr("Failed to read version.json when checking. Click here to go to the Web site."), 0); connect(action, SIGNAL(triggered(bool)), SLOT(onUpgradeTriggered())); showStatusMessage(action); reply->deleteLater(); } void MainWindow::onUpgradeTriggered() { QDesktopServices::openUrl(QUrl(m_upgradeUrl)); } void MainWindow::onTimelineSelectionChanged() { bool enable = (m_timelineDock->selection().size() > 0); ui->actionCut->setEnabled(enable); ui->actionCopy->setEnabled(enable); } void MainWindow::on_actionCut_triggered() { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->removeSelection(true); } void MainWindow::on_actionCopy_triggered() { m_timelineDock->show(); m_timelineDock->raise(); if (!m_timelineDock->selection().isEmpty()) m_timelineDock->copyClip(m_timelineDock->selection().first().y(), m_timelineDock->selection().first().x()); } void MainWindow::on_actionPaste_triggered() { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->insert(-1); } void MainWindow::onClipCopied() { m_player->enableTab(Player::SourceTabIndex); } void MainWindow::on_actionExportEDL_triggered() { // Dialog to get export file name. QString path = Settings.savePath(); QString caption = tr("Export EDL"); QString saveFileName = QFileDialog::getSaveFileName(this, caption, path, tr("EDL (*.edl);;All Files (*)")); if (!saveFileName.isEmpty()) { QFileInfo fi(saveFileName); if (fi.suffix() != "edl") saveFileName += ".edl"; if (Util::warnIfNotWritable(saveFileName, this, caption)) return; // Locate the JavaScript file in the filesystem. QDir qmlDir = QmlUtilities::qmlDir(); qmlDir.cd("export-edl"); QString jsFileName = qmlDir.absoluteFilePath("export-edl.js"); QFile scriptFile(jsFileName); if (scriptFile.open(QIODevice::ReadOnly)) { // Read JavaScript into a string. QTextStream stream(&scriptFile); stream.setCodec("UTF-8"); stream.setAutoDetectUnicode(true); QString contents = stream.readAll(); scriptFile.close(); // Evaluate JavaScript. QJSEngine jsEngine; QJSValue result = jsEngine.evaluate(contents, jsFileName); if (!result.isError()) { // Call the JavaScript main function. QJSValue options = jsEngine.newObject(); options.setProperty("useBaseNameForReelName", true); options.setProperty("useBaseNameForClipComment", true); options.setProperty("channelsAV", "AA/V"); QJSValueList args; args << MLT.XML(0, true, true) << options; result = result.call(args); if (!result.isError()) { // Save the result with the export file name. QFile f(saveFileName); f.open(QIODevice::WriteOnly | QIODevice::Text); f.write(result.toString().toLatin1()); f.close(); } } if (result.isError()) { LOG_ERROR() << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":" << result.toString(); showStatusMessage(tr("A JavaScript error occurred during export.")); } } else { showStatusMessage(tr("Failed to open export-edl.js")); } } } void MainWindow::on_actionExportFrame_triggered() { if (Settings.playerGPU() || Settings.playerPreviewScale()) { Mlt::GLWidget* glw = qobject_cast<Mlt::GLWidget*>(MLT.videoWidget()); connect(glw, SIGNAL(imageReady()), SLOT(onGLWidgetImageReady())); MLT.setPreviewScale(0); glw->requestImage(); MLT.refreshConsumer(); } else { onGLWidgetImageReady(); } } void MainWindow::onGLWidgetImageReady() { Mlt::GLWidget* glw = qobject_cast<Mlt::GLWidget*>(MLT.videoWidget()); QImage image = glw->image(); if (Settings.playerGPU() || Settings.playerPreviewScale()) { disconnect(glw, SIGNAL(imageReady()), this, 0); MLT.setPreviewScale(Settings.playerPreviewScale()); } if (!image.isNull()) { QString path = Settings.savePath(); QString caption = tr("Export Frame"); QString nameFilter = tr("PNG (*.png);;BMP (*.bmp);;JPEG (*.jpg *.jpeg);;PPM (*.ppm);;TIFF (*.tif *.tiff);;WebP (*.webp);;All Files (*)"); QString saveFileName = QFileDialog::getSaveFileName(this, caption, path, nameFilter); if (!saveFileName.isEmpty()) { QFileInfo fi(saveFileName); if (fi.suffix().isEmpty()) saveFileName += ".png"; if (Util::warnIfNotWritable(saveFileName, this, caption)) return; // Convert to square pixels if needed. qreal aspectRatio = (qreal) image.width() / image.height(); if (qFloor(aspectRatio * 1000) != qFloor(MLT.profile().dar() * 1000)) { image = image.scaled(qRound(image.height() * MLT.profile().dar()), image.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } image.save(saveFileName, Q_NULLPTR, (QFileInfo(saveFileName).suffix() == "webp")? 80 : -1); Settings.setSavePath(fi.path()); m_recentDock->add(saveFileName); } } else { showStatusMessage(tr("Unable to export frame.")); } } void MainWindow::on_actionAppDataSet_triggered() { QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart Shotcut to change the data directory.\n" "Do you want to continue?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() != QMessageBox::Yes) return; QString dirName = QFileDialog::getExistingDirectory(this, tr("Data Directory"), Settings.appDataLocation()); if (!dirName.isEmpty()) { // Move the data files. QDirIterator it(Settings.appDataLocation()); while (it.hasNext()) { if (!it.filePath().isEmpty() && it.fileName() != "." && it.fileName() != "..") { if (!QFile::exists(dirName + "/" + it.fileName())) { if (it.fileInfo().isDir()) { if (!QFile::rename(it.filePath(), dirName + "/" + it.fileName())) LOG_WARNING() << "Failed to move" << it.filePath() << "to" << dirName + "/" + it.fileName(); } else { if (!QFile::copy(it.filePath(), dirName + "/" + it.fileName())) LOG_WARNING() << "Failed to copy" << it.filePath() << "to" << dirName + "/" + it.fileName(); } } } it.next(); } writeSettings(); Settings.setAppDataLocally(dirName); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } } void MainWindow::on_actionAppDataShow_triggered() { Util::showInFolder(Settings.appDataLocation()); } void MainWindow::on_actionNew_triggered() { on_actionClose_triggered(); } void MainWindow::on_actionKeyboardShortcuts_triggered() { QDesktopServices::openUrl(QUrl("https://www.shotcut.org/howtos/keyboard-shortcuts/")); } void MainWindow::on_actionLayoutPlayer_triggered() { restoreState(Settings.windowStateDefault()); } void MainWindow::on_actionLayoutPlaylist_triggered() { restoreState(Settings.windowStateDefault()); m_recentDock->show(); m_recentDock->raise(); m_playlistDock->show(); m_playlistDock->raise(); } void MainWindow::on_actionLayoutTimeline_triggered() { restoreState(Settings.windowStateDefault()); QDockWidget* audioMeterDock = findChild<QDockWidget*>("AudioPeakMeterDock"); if (audioMeterDock) { audioMeterDock->show(); audioMeterDock->raise(); } m_recentDock->show(); m_recentDock->raise(); m_filtersDock->show(); m_filtersDock->raise(); m_timelineDock->show(); m_timelineDock->raise(); } void MainWindow::on_actionLayoutClip_triggered() { restoreState(Settings.windowStateDefault()); m_recentDock->show(); m_recentDock->raise(); m_filtersDock->show(); m_filtersDock->raise(); } void MainWindow::on_actionLayoutAdd_triggered() { bool ok; QString name = QInputDialog::getText(this, tr("Add Custom Layout"), tr("Name"), QLineEdit::Normal, "", &ok); if (ok && !name.isEmpty()) { if (Settings.setLayout(name, saveGeometry(), saveState())) { Settings.sync(); if (Settings.layouts().size() == 1) { ui->menuLayout->addAction(ui->actionLayoutRemove); ui->menuLayout->addSeparator(); } ui->menuLayout->addAction(addLayout(m_layoutGroup, name)); } } } void MainWindow::onLayoutTriggered(QAction* action) { restoreGeometry(Settings.layoutGeometry(action->text())); restoreState(Settings.layoutState(action->text())); } void MainWindow::on_actionProfileRemove_triggered() { QDir dir(Settings.appDataLocation()); if (dir.cd("profiles")) { // Setup the dialog. QStringList profiles = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); ListSelectionDialog dialog(profiles, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setWindowTitle(tr("Remove Video Mode")); // Show the dialog. if (dialog.exec() == QDialog::Accepted) { removeCustomProfiles(dialog.selection(), dir, customProfileMenu(), actionProfileRemove()); } } } void MainWindow::on_actionLayoutRemove_triggered() { // Setup the dialog. ListSelectionDialog dialog(Settings.layouts(), this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setWindowTitle(tr("Remove Layout")); // Show the dialog. if (dialog.exec() == QDialog::Accepted) { foreach(const QString& layout, dialog.selection()) { // Update the configuration. if (Settings.removeLayout(layout)) Settings.sync(); // Locate the menu item. foreach (QAction* action, ui->menuLayout->actions()) { if (action->text() == layout) { // Remove the menu item. delete action; break; } } } // If no more custom layouts. if (Settings.layouts().size() == 0) { // Remove the Remove action and separator. ui->menuLayout->removeAction(ui->actionLayoutRemove); bool isSecondSeparator = false; foreach (QAction* action, ui->menuLayout->actions()) { if (action->isSeparator()) { if (isSecondSeparator) { delete action; break; } else { isSecondSeparator = true; } } } } } } void MainWindow::on_actionOpenOther2_triggered() { ui->actionOpenOther2->menu()->popup(mapToGlobal(ui->mainToolBar->geometry().bottomLeft()) + QPoint(64, 0)); } void MainWindow::onOpenOtherTriggered(QWidget* widget) { QDialog dialog(this); dialog.resize(426, 288); QVBoxLayout vlayout(&dialog); vlayout.addWidget(widget); QDialogButtonBox buttonBox(&dialog); buttonBox.setOrientation(Qt::Horizontal); buttonBox.setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); vlayout.addWidget(&buttonBox); connect(&buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept())); connect(&buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject())); QString name = widget->objectName(); if (name == "NoiseWidget" || dialog.exec() == QDialog::Accepted) { open(dynamic_cast<AbstractProducerWidget*>(widget)->newProducer(MLT.profile())); if (name == "TextProducerWidget") { m_filtersDock->show(); m_filtersDock->raise(); } else { m_propertiesDock->show(); m_propertiesDock->raise(); } } delete widget; } void MainWindow::onOpenOtherTriggered() { if (sender()->objectName() == "color") onOpenOtherTriggered(new ColorProducerWidget(this)); else if (sender()->objectName() == "text") onOpenOtherTriggered(new TextProducerWidget(this)); else if (sender()->objectName() == "noise") onOpenOtherTriggered(new NoiseWidget(this)); else if (sender()->objectName() == "ising0r") onOpenOtherTriggered(new IsingWidget(this)); else if (sender()->objectName() == "lissajous0r") onOpenOtherTriggered(new LissajousWidget(this)); else if (sender()->objectName() == "plasma") onOpenOtherTriggered(new PlasmaWidget(this)); else if (sender()->objectName() == "test_pat_B") onOpenOtherTriggered(new ColorBarsWidget(this)); else if (sender()->objectName() == "tone") onOpenOtherTriggered(new ToneProducerWidget(this)); else if (sender()->objectName() == "count") onOpenOtherTriggered(new CountProducerWidget(this)); else if (sender()->objectName() == "blipflash") onOpenOtherTriggered(new BlipProducerWidget(this)); else if (sender()->objectName() == "v4l2") onOpenOtherTriggered(new Video4LinuxWidget(this)); else if (sender()->objectName() == "pulse") onOpenOtherTriggered(new PulseAudioWidget(this)); else if (sender()->objectName() == "jack") onOpenOtherTriggered(new JackProducerWidget(this)); else if (sender()->objectName() == "alsa") onOpenOtherTriggered(new AlsaWidget(this)); #if defined(Q_OS_MAC) else if (sender()->objectName() == "device") onOpenOtherTriggered(new AvfoundationProducerWidget(this)); #elif defined(Q_OS_WIN) else if (sender()->objectName() == "device") onOpenOtherTriggered(new DirectShowVideoWidget(this)); #endif else if (sender()->objectName() == "decklink") onOpenOtherTriggered(new DecklinkProducerWidget(this)); } void MainWindow::on_actionClearRecentOnExit_toggled(bool arg1) { Settings.setClearRecent(arg1); if (arg1) Settings.setRecent(QStringList()); } void MainWindow::onSceneGraphInitialized() { if (Settings.playerGPU() && Settings.playerWarnGPU()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("GPU effects are EXPERIMENTAL, UNSTABLE and UNSUPPORTED! Unsupported means do not report bugs about it.\n\n" "Do you want to disable GPU effects and restart Shotcut?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { ui->actionGPU->setChecked(false); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } else { ui->actionGPU->setVisible(true); } } else if (Settings.playerGPU()) { ui->actionGPU->setVisible(true); } } void MainWindow::on_actionShowTextUnderIcons_toggled(bool b) { ui->mainToolBar->setToolButtonStyle(b? Qt::ToolButtonTextUnderIcon : Qt::ToolButtonIconOnly); Settings.setTextUnderIcons(b); } void MainWindow::on_actionShowSmallIcons_toggled(bool b) { ui->mainToolBar->setIconSize(b? QSize(16, 16) : QSize()); Settings.setSmallIcons(b); } void MainWindow::onPlaylistInChanged(int in) { m_player->blockSignals(true); m_player->setIn(in); m_player->blockSignals(false); } void MainWindow::onPlaylistOutChanged(int out) { m_player->blockSignals(true); m_player->setOut(out); m_player->blockSignals(false); } void MainWindow::on_actionPreviewNone_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(0); setPreviewScale(0); m_player->showIdleStatus(); } } void MainWindow::on_actionPreview360_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(360); setPreviewScale(360); m_player->showIdleStatus(); } } void MainWindow::on_actionPreview540_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(540); setPreviewScale(540); m_player->showIdleStatus(); } } void MainWindow::on_actionPreview720_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(720); setPreviewScale(720); m_player->showIdleStatus(); } } QUuid MainWindow::timelineClipUuid(int trackIndex, int clipIndex) { QScopedPointer<Mlt::ClipInfo> info(m_timelineDock->getClipInfo(trackIndex, clipIndex)); if (info && info->cut && info->cut->is_valid()) return MLT.ensureHasUuid(*info->cut); return QUuid(); } void MainWindow::replaceInTimeline(const QUuid& uuid, Mlt::Producer& producer) { int trackIndex = -1; int clipIndex = -1; // lookup the current track and clip index by UUID QScopedPointer<Mlt::ClipInfo> info(MAIN.timelineClipInfoByUuid(uuid, trackIndex, clipIndex)); if (trackIndex >= 0 && clipIndex >= 0) { Util::getHash(producer); Util::applyCustomProperties(producer, *info->producer, producer.get_in(), producer.get_out()); m_timelineDock->replace(trackIndex, clipIndex, MLT.XML(&producer)); } } Mlt::ClipInfo* MainWindow::timelineClipInfoByUuid(const QUuid& uuid, int& trackIndex, int& clipIndex) { return m_timelineDock->model()->findClipByUuid(uuid, trackIndex, clipIndex); } void MainWindow::replaceAllByHash(const QString& hash, Mlt::Producer& producer, bool isProxy) { Util::getHash(producer); if (!isProxy) m_recentDock->add(producer.get("resource")); if (MLT.isClip() && MLT.producer() && Util::getHash(*MLT.producer()) == hash) { Util::applyCustomProperties(producer, *MLT.producer(), MLT.producer()->get_in(), MLT.producer()->get_out()); MLT.copyFilters(*MLT.producer(), producer); MLT.close(); m_player->setPauseAfterOpen(true); open(new Mlt::Producer(MLT.profile(), "xml-string", MLT.XML(&producer).toUtf8().constData())); } else if (MLT.savedProducer() && Util::getHash(*MLT.savedProducer()) == hash) { Util::applyCustomProperties(producer, *MLT.savedProducer(), MLT.savedProducer()->get_in(), MLT.savedProducer()->get_out()); MLT.copyFilters(*MLT.savedProducer(), producer); MLT.setSavedProducer(&producer); } if (playlist()) { if (isProxy) { m_playlistDock->replaceClipsWithHash(hash, producer); } else { // Append to playlist producer.set(kPlaylistIndexProperty, playlist()->count()); MAIN.undoStack()->push( new Playlist::AppendCommand(*m_playlistDock->model(), MLT.XML(&producer))); } } if (isMultitrackValid()) { m_timelineDock->replaceClipsWithHash(hash, producer); } } void MainWindow::on_actionTopics_triggered() { QDesktopServices::openUrl(QUrl("https://www.shotcut.org/howtos/")); } void MainWindow::on_actionSync_triggered() { auto dialog = new SystemSyncDialog(this); dialog->show(); dialog->raise(); dialog->activateWindow(); } void MainWindow::on_actionUseProxy_triggered(bool checked) { if (MLT.producer()) { QDir dir(m_currentFile.isEmpty()? QDir::tempPath() : QFileInfo(m_currentFile).dir()); QScopedPointer<QTemporaryFile> tmp(new QTemporaryFile(dir.filePath("shotcut-XXXXXX.mlt"))); tmp->open(); tmp->close(); QString fileName = tmp->fileName(); tmp->remove(); tmp.reset(); LOG_DEBUG() << fileName; if (saveXML(fileName)) { MltXmlChecker checker; Settings.setProxyEnabled(checked); checker.check(fileName); if (!isXmlRepaired(checker, fileName)) { QFile::remove(fileName); return; } if (checker.isUpdated()) { QFile::remove(fileName); fileName = checker.tempFileName(); } // Open the temporary file int result = 0; { LongUiTask longTask(checked? tr("Turn Proxy On") : tr("Turn Proxy Off")); QFuture<int> future = QtConcurrent::run([=]() { return MLT.open(QDir::fromNativeSeparators(fileName), QDir::fromNativeSeparators(m_currentFile)); }); result = longTask.wait<int>(tr("Converting"), future); } if (!result) { auto position = m_player->position(); m_undoStack->clear(); m_player->stop(); m_player->setPauseAfterOpen(true); open(MLT.producer()); MLT.seek(m_player->position()); m_player->seek(position); if (checked && (isPlaylistValid() || isMultitrackValid())) { // Prompt user if they want to create missing proxies QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Do you want to create missing proxies for every file in this project?\n\n" "You must reopen your project after all proxy jobs are finished."), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); if (dialog.exec() == QMessageBox::Yes) { Mlt::Producer producer(playlist()); if (producer.is_valid()) { ProxyManager::generateIfNotExistsAll(producer); } producer = multitrack(); if (producer.is_valid()) { ProxyManager::generateIfNotExistsAll(producer); } } } } else if (fileName != untitledFileName()) { showStatusMessage(tr("Failed to open ") + fileName); emit openFailed(fileName); } } else { ui->actionUseProxy->setChecked(!checked); showSaveError(); } QFile::remove(fileName); } else { Settings.setProxyEnabled(checked); } m_player->showIdleStatus(); } void MainWindow::on_actionProxyStorageSet_triggered() { // Present folder dialog just like App Data Directory QString dirName = QFileDialog::getExistingDirectory(this, tr("Proxy Folder"), Settings.proxyFolder()); if (!dirName.isEmpty() && dirName != Settings.proxyFolder()) { auto oldFolder = Settings.proxyFolder(); Settings.setProxyFolder(dirName); Settings.sync(); // Get a count for the progress dialog auto oldDir = QDir(oldFolder); auto dirList = oldDir.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot); auto count = dirList.size(); if (count > 0) { // Prompt user if they want to create missing proxies QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Do you want to move all files from the old folder to the new folder?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); if (dialog.exec() == QMessageBox::Yes) { // Move the existing files LongUiTask longTask(tr("Moving Files")); int i = 0; for (const auto& fileName : dirList) { if (!fileName.isEmpty() && !QFile::exists(dirName + "/" + fileName)) { LOG_DEBUG() << "moving" << oldDir.filePath(fileName) << "to" << dirName + "/" + fileName; longTask.reportProgress(fileName, i++, count); if (!QFile::rename(oldDir.filePath(fileName), dirName + "/" + fileName)) LOG_WARNING() << "Failed to move" << oldDir.filePath(fileName); } } } } } } void MainWindow::on_actionProxyStorageShow_triggered() { Util::showInFolder(ProxyManager::dir().path()); } void MainWindow::on_actionProxyUseProjectFolder_triggered(bool checked) { Settings.setProxyUseProjectFolder(checked); } void MainWindow::on_actionProxyUseHardware_triggered(bool checked) { if (checked && Settings.encodeHardware().isEmpty()) { if (!m_encodeDock->detectHardwareEncoders()) ui->actionProxyUseHardware->setChecked(false); } Settings.setProxyUseHardware(ui->actionProxyUseHardware->isChecked()); } void MainWindow::on_actionProxyConfigureHardware_triggered() { m_encodeDock->on_hwencodeButton_clicked(); if (Settings.encodeHardware().isEmpty()) { ui->actionProxyUseHardware->setChecked(false); Settings.setProxyUseHardware(false); } }
./CrossVul/dataset_final_sorted/CWE-327/cpp/good_4277_0
crossvul-cpp_data_bad_4277_0
/* * Copyright (c) 2011-2020 Meltytech, LLC * * 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 3 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, see <http://www.gnu.org/licenses/>. */ #include "mainwindow.h" #include "ui_mainwindow.h" #include "scrubbar.h" #include "openotherdialog.h" #include "player.h" #include "widgets/alsawidget.h" #include "widgets/colorbarswidget.h" #include "widgets/colorproducerwidget.h" #include "widgets/countproducerwidget.h" #include "widgets/decklinkproducerwidget.h" #include "widgets/directshowvideowidget.h" #include "widgets/isingwidget.h" #include "widgets/jackproducerwidget.h" #include "widgets/toneproducerwidget.h" #include "widgets/lissajouswidget.h" #include "widgets/networkproducerwidget.h" #include "widgets/noisewidget.h" #include "widgets/plasmawidget.h" #include "widgets/pulseaudiowidget.h" #include "widgets/video4linuxwidget.h" #include "widgets/x11grabwidget.h" #include "widgets/avformatproducerwidget.h" #include "widgets/imageproducerwidget.h" #include "widgets/webvfxproducer.h" #include "widgets/blipproducerwidget.h" #include "widgets/newprojectfolder.h" #include "docks/recentdock.h" #include "docks/encodedock.h" #include "docks/jobsdock.h" #include "jobqueue.h" #include "docks/playlistdock.h" #include "glwidget.h" #include "controllers/filtercontroller.h" #include "controllers/scopecontroller.h" #include "docks/filtersdock.h" #include "dialogs/customprofiledialog.h" #include "htmleditor/htmleditor.h" #include "settings.h" #include "leapnetworklistener.h" #include "database.h" #include "widgets/gltestwidget.h" #include "docks/timelinedock.h" #include "widgets/lumamixtransition.h" #include "qmltypes/qmlutilities.h" #include "qmltypes/qmlapplication.h" #include "autosavefile.h" #include "commands/playlistcommands.h" #include "shotcut_mlt_properties.h" #include "widgets/avfoundationproducerwidget.h" #include "dialogs/textviewerdialog.h" #include "widgets/gdigrabwidget.h" #include "models/audiolevelstask.h" #include "widgets/trackpropertieswidget.h" #include "widgets/timelinepropertieswidget.h" #include "dialogs/unlinkedfilesdialog.h" #include "docks/keyframesdock.h" #include "util.h" #include "models/keyframesmodel.h" #include "dialogs/listselectiondialog.h" #include "widgets/textproducerwidget.h" #include "qmltypes/qmlprofile.h" #include "dialogs/longuitask.h" #include "dialogs/systemsyncdialog.h" #include "proxymanager.h" #include <QtWidgets> #include <Logger.h> #include <QThreadPool> #include <QtConcurrent/QtConcurrentRun> #include <QMutexLocker> #include <QQuickItem> #include <QtNetwork> #include <QJsonDocument> #include <QJSEngine> #include <QDirIterator> #include <QQuickWindow> #include <QVersionNumber> #include <clocale> static bool eventDebugCallback(void **data) { QEvent *event = reinterpret_cast<QEvent*>(data[1]); if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QObject *receiver = reinterpret_cast<QObject*>(data[0]); LOG_DEBUG() << event << "->" << receiver; } else if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease) { QObject *receiver = reinterpret_cast<QObject*>(data[0]); LOG_DEBUG() << event << "->" << receiver; } return false; } static const int AUTOSAVE_TIMEOUT_MS = 60000; MainWindow::MainWindow() : QMainWindow(0) , ui(new Ui::MainWindow) , m_isKKeyPressed(false) , m_keyerGroup(0) , m_previewScaleGroup(0) , m_keyerMenu(0) , m_isPlaylistLoaded(false) , m_exitCode(EXIT_SUCCESS) , m_navigationPosition(0) , m_upgradeUrl("https://www.shotcut.org/download/") , m_keyframesDock(0) { #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) QLibrary libJack("libjack.so.0"); if (!libJack.load()) { QMessageBox::critical(this, qApp->applicationName(), tr("Error: This program requires the JACK 1 library.\n\nPlease install it using your package manager. It may be named libjack0, jack-audio-connection-kit, jack, or similar.")); ::exit(EXIT_FAILURE); } else { libJack.unload(); } QLibrary libSDL("libSDL2-2.0.so.0"); if (!libSDL.load()) { QMessageBox::critical(this, qApp->applicationName(), tr("Error: This program requires the SDL 2 library.\n\nPlease install it using your package manager. It may be named libsdl2-2.0-0, SDL2, or similar.")); ::exit(EXIT_FAILURE); } else { libSDL.unload(); } #endif if (!qgetenv("OBSERVE_FOCUS").isEmpty()) { connect(qApp, &QApplication::focusChanged, this, &MainWindow::onFocusChanged); connect(qApp, &QGuiApplication::focusObjectChanged, this, &MainWindow::onFocusObjectChanged); connect(qApp, &QGuiApplication::focusWindowChanged, this, &MainWindow::onFocusWindowChanged); } if (!qgetenv("EVENT_DEBUG").isEmpty()) QInternal::registerCallback(QInternal::EventNotifyCallback, eventDebugCallback); LOG_DEBUG() << "begin"; #ifndef Q_OS_WIN new GLTestWidget(this); #endif Database::singleton(this); m_autosaveTimer.setSingleShot(true); m_autosaveTimer.setInterval(AUTOSAVE_TIMEOUT_MS); connect(&m_autosaveTimer, SIGNAL(timeout()), this, SLOT(onAutosaveTimeout())); // Initialize all QML types QmlUtilities::registerCommonTypes(); // Create the UI. ui->setupUi(this); #ifdef Q_OS_MAC // Qt 5 on OS X supports the standard Full Screen window widget. ui->mainToolBar->removeAction(ui->actionFullscreen); // OS X has a standard Full Screen shortcut we should use. ui->actionEnter_Full_Screen->setShortcut(QKeySequence((Qt::CTRL + Qt::META + Qt::Key_F))); #endif setDockNestingEnabled(true); ui->statusBar->hide(); // Connect UI signals. connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openVideo())); connect(ui->actionAbout_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(this, SIGNAL(producerOpened()), this, SLOT(onProducerOpened())); if (ui->actionFullscreen) connect(ui->actionFullscreen, SIGNAL(triggered()), this, SLOT(on_actionEnter_Full_Screen_triggered())); connect(ui->mainToolBar, SIGNAL(visibilityChanged(bool)), SLOT(onToolbarVisibilityChanged(bool))); // Accept drag-n-drop of files. this->setAcceptDrops(true); // Setup the undo stack. m_undoStack = new QUndoStack(this); m_undoStack->setUndoLimit(Settings.undoLimit()); QAction *undoAction = m_undoStack->createUndoAction(this); QAction *redoAction = m_undoStack->createRedoAction(this); undoAction->setIcon(QIcon::fromTheme("edit-undo", QIcon(":/icons/oxygen/32x32/actions/edit-undo.png"))); redoAction->setIcon(QIcon::fromTheme("edit-redo", QIcon(":/icons/oxygen/32x32/actions/edit-redo.png"))); undoAction->setShortcut(QApplication::translate("MainWindow", "Ctrl+Z", 0)); #ifdef Q_OS_WIN redoAction->setShortcut(QApplication::translate("MainWindow", "Ctrl+Y", 0)); #else redoAction->setShortcut(QApplication::translate("MainWindow", "Ctrl+Shift+Z", 0)); #endif ui->menuEdit->insertAction(ui->actionCut, undoAction); ui->menuEdit->insertAction(ui->actionCut, redoAction); ui->menuEdit->insertSeparator(ui->actionCut); ui->actionUndo->setIcon(undoAction->icon()); ui->actionRedo->setIcon(redoAction->icon()); ui->actionUndo->setToolTip(undoAction->toolTip()); ui->actionRedo->setToolTip(redoAction->toolTip()); connect(m_undoStack, SIGNAL(canUndoChanged(bool)), ui->actionUndo, SLOT(setEnabled(bool))); connect(m_undoStack, SIGNAL(canRedoChanged(bool)), ui->actionRedo, SLOT(setEnabled(bool))); // Add the player widget. m_player = new Player; MLT.videoWidget()->installEventFilter(this); ui->centralWidget->layout()->addWidget(m_player); connect(this, SIGNAL(producerOpened()), m_player, SLOT(onProducerOpened())); connect(m_player, SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_player, SIGNAL(inChanged(int)), this, SLOT(onCutModified())); connect(m_player, SIGNAL(outChanged(int)), this, SLOT(onCutModified())); connect(m_player, SIGNAL(tabIndexChanged(int)), SLOT(onPlayerTabIndexChanged(int))); connect(MLT.videoWidget(), SIGNAL(started()), SLOT(processMultipleFiles())); connect(MLT.videoWidget(), SIGNAL(paused()), m_player, SLOT(showPaused())); connect(MLT.videoWidget(), SIGNAL(playing()), m_player, SLOT(showPlaying())); connect(MLT.videoWidget(), SIGNAL(toggleZoom(bool)), m_player, SLOT(toggleZoom(bool))); setupSettingsMenu(); setupOpenOtherMenu(); readPlayerSettings(); configureVideoWidget(); #ifndef SHOTCUT_NOUPGRADE if (Settings.noUpgrade() || qApp->property("noupgrade").toBool()) #endif delete ui->actionUpgrade; // Add the docks. m_scopeController = new ScopeController(this, ui->menuView); QDockWidget* audioMeterDock = findChild<QDockWidget*>("AudioPeakMeterDock"); if (audioMeterDock) { audioMeterDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1)); connect(ui->actionAudioMeter, SIGNAL(triggered()), audioMeterDock->toggleViewAction(), SLOT(trigger())); } m_propertiesDock = new QDockWidget(tr("Properties"), this); m_propertiesDock->hide(); m_propertiesDock->setObjectName("propertiesDock"); m_propertiesDock->setWindowIcon(ui->actionProperties->icon()); m_propertiesDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_2)); m_propertiesDock->toggleViewAction()->setIcon(ui->actionProperties->icon()); m_propertiesDock->setMinimumWidth(300); QScrollArea* scroll = new QScrollArea; scroll->setWidgetResizable(true); m_propertiesDock->setWidget(scroll); addDockWidget(Qt::LeftDockWidgetArea, m_propertiesDock); ui->menuView->addAction(m_propertiesDock->toggleViewAction()); connect(m_propertiesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onPropertiesDockTriggered(bool))); connect(ui->actionProperties, SIGNAL(triggered()), this, SLOT(onPropertiesDockTriggered())); m_recentDock = new RecentDock(this); m_recentDock->hide(); addDockWidget(Qt::RightDockWidgetArea, m_recentDock); m_recentDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_3)); ui->menuView->addAction(m_recentDock->toggleViewAction()); connect(m_recentDock, SIGNAL(itemActivated(QString)), this, SLOT(open(QString))); connect(m_recentDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onRecentDockTriggered(bool))); connect(ui->actionRecent, SIGNAL(triggered()), this, SLOT(onRecentDockTriggered())); connect(this, SIGNAL(openFailed(QString)), m_recentDock, SLOT(remove(QString))); connect(m_recentDock, &RecentDock::deleted, m_player->projectWidget(), &NewProjectFolder::updateRecentProjects); m_playlistDock = new PlaylistDock(this); m_playlistDock->hide(); addDockWidget(Qt::LeftDockWidgetArea, m_playlistDock); m_playlistDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_4)); ui->menuView->addAction(m_playlistDock->toggleViewAction()); connect(m_playlistDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onPlaylistDockTriggered(bool))); connect(ui->actionPlaylist, SIGNAL(triggered()), this, SLOT(onPlaylistDockTriggered())); connect(m_playlistDock, SIGNAL(clipOpened(Mlt::Producer*, bool)), this, SLOT(openCut(Mlt::Producer*, bool))); connect(m_playlistDock, SIGNAL(itemActivated(int)), this, SLOT(seekPlaylist(int))); connect(m_playlistDock, SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_playlistDock->model(), SIGNAL(created()), this, SLOT(onPlaylistCreated())); connect(m_playlistDock->model(), SIGNAL(cleared()), this, SLOT(onPlaylistCleared())); connect(m_playlistDock->model(), SIGNAL(cleared()), this, SLOT(updateAutoSave())); connect(m_playlistDock->model(), SIGNAL(closed()), this, SLOT(onPlaylistClosed())); connect(m_playlistDock->model(), SIGNAL(modified()), this, SLOT(onPlaylistModified())); connect(m_playlistDock->model(), SIGNAL(modified()), this, SLOT(updateAutoSave())); connect(m_playlistDock->model(), SIGNAL(loaded()), this, SLOT(onPlaylistLoaded())); connect(this, SIGNAL(producerOpened()), m_playlistDock, SLOT(onProducerOpened())); if (!Settings.playerGPU()) connect(m_playlistDock->model(), SIGNAL(loaded()), this, SLOT(updateThumbnails())); connect(m_player, &Player::inChanged, m_playlistDock, &PlaylistDock::onInChanged); connect(m_player, &Player::outChanged, m_playlistDock, &PlaylistDock::onOutChanged); connect(m_playlistDock->model(), &PlaylistModel::inChanged, this, &MainWindow::onPlaylistInChanged); connect(m_playlistDock->model(), &PlaylistModel::outChanged, this, &MainWindow::onPlaylistOutChanged); m_timelineDock = new TimelineDock(this); m_timelineDock->hide(); addDockWidget(Qt::BottomDockWidgetArea, m_timelineDock); m_timelineDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_5)); ui->menuView->addAction(m_timelineDock->toggleViewAction()); connect(m_timelineDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onTimelineDockTriggered(bool))); connect(ui->actionTimeline, SIGNAL(triggered()), SLOT(onTimelineDockTriggered())); connect(m_player, SIGNAL(seeked(int)), m_timelineDock, SLOT(onSeeked(int))); connect(m_timelineDock, SIGNAL(seeked(int)), SLOT(seekTimeline(int))); connect(m_timelineDock, SIGNAL(clipClicked()), SLOT(onTimelineClipSelected())); connect(m_timelineDock, SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_timelineDock->model(), SIGNAL(showStatusMessage(QString)), this, SLOT(showStatusMessage(QString))); connect(m_timelineDock->model(), SIGNAL(created()), SLOT(onMultitrackCreated())); connect(m_timelineDock->model(), SIGNAL(closed()), SLOT(onMultitrackClosed())); connect(m_timelineDock->model(), SIGNAL(modified()), SLOT(onMultitrackModified())); connect(m_timelineDock->model(), SIGNAL(modified()), SLOT(updateAutoSave())); connect(m_timelineDock->model(), SIGNAL(durationChanged()), SLOT(onMultitrackDurationChanged())); connect(m_timelineDock, SIGNAL(clipOpened(Mlt::Producer*)), SLOT(openCut(Mlt::Producer*))); connect(m_timelineDock->model(), &MultitrackModel::seeked, this, &MainWindow::seekTimeline); connect(m_timelineDock->model(), SIGNAL(scaleFactorChanged()), m_player, SLOT(pause())); connect(m_timelineDock, SIGNAL(selected(Mlt::Producer*)), SLOT(loadProducerWidget(Mlt::Producer*))); connect(m_timelineDock, SIGNAL(selectionChanged()), SLOT(onTimelineSelectionChanged())); connect(m_timelineDock, SIGNAL(clipCopied()), SLOT(onClipCopied())); connect(m_timelineDock, SIGNAL(filteredClicked()), SLOT(onFiltersDockTriggered())); connect(m_playlistDock, SIGNAL(addAllTimeline(Mlt::Playlist*)), SLOT(onTimelineDockTriggered())); connect(m_playlistDock, SIGNAL(addAllTimeline(Mlt::Playlist*, bool)), SLOT(onAddAllToTimeline(Mlt::Playlist*, bool))); connect(m_player, SIGNAL(previousSought()), m_timelineDock, SLOT(seekPreviousEdit())); connect(m_player, SIGNAL(nextSought()), m_timelineDock, SLOT(seekNextEdit())); m_filterController = new FilterController(this); m_filtersDock = new FiltersDock(m_filterController->metadataModel(), m_filterController->attachedModel(), this); m_filtersDock->setMinimumSize(400, 300); m_filtersDock->hide(); addDockWidget(Qt::LeftDockWidgetArea, m_filtersDock); m_filtersDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_6)); ui->menuView->addAction(m_filtersDock->toggleViewAction()); connect(m_filtersDock, SIGNAL(currentFilterRequested(int)), m_filterController, SLOT(setCurrentFilter(int)), Qt::QueuedConnection); connect(m_filtersDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onFiltersDockTriggered(bool))); connect(ui->actionFilters, SIGNAL(triggered()), this, SLOT(onFiltersDockTriggered())); connect(m_filterController, SIGNAL(currentFilterChanged(QmlFilter*, QmlMetadata*, int)), m_filtersDock, SLOT(setCurrentFilter(QmlFilter*, QmlMetadata*, int))); connect(this, SIGNAL(producerOpened()), m_filterController, SLOT(setProducer())); connect(m_filterController->attachedModel(), SIGNAL(changed()), SLOT(onFilterModelChanged())); connect(m_filtersDock, SIGNAL(changed()), SLOT(onFilterModelChanged())); connect(m_filterController, SIGNAL(filterChanged(Mlt::Filter*)), m_timelineDock->model(), SLOT(onFilterChanged(Mlt::Filter*))); connect(m_filterController->attachedModel(), SIGNAL(addedOrRemoved(Mlt::Producer*)), m_timelineDock->model(), SLOT(filterAddedOrRemoved(Mlt::Producer*))); connect(&QmlApplication::singleton(), SIGNAL(filtersPasted(Mlt::Producer*)), m_timelineDock->model(), SLOT(filterAddedOrRemoved(Mlt::Producer*))); connect(&QmlApplication::singleton(), &QmlApplication::filtersPasted, this, &MainWindow::onProducerModified); connect(m_filterController, SIGNAL(statusChanged(QString)), this, SLOT(showStatusMessage(QString))); connect(m_timelineDock, SIGNAL(fadeInChanged(int)), m_filterController, SLOT(onFadeInChanged())); connect(m_timelineDock, SIGNAL(fadeOutChanged(int)), m_filterController, SLOT(onFadeOutChanged())); connect(m_timelineDock, SIGNAL(selected(Mlt::Producer*)), m_filterController, SLOT(setProducer(Mlt::Producer*))); connect(m_player, SIGNAL(seeked(int)), m_filtersDock, SLOT(onSeeked(int)), Qt::QueuedConnection); connect(m_filtersDock, SIGNAL(seeked(int)), SLOT(seekKeyframes(int))); connect(MLT.videoWidget(), SIGNAL(frameDisplayed(const SharedFrame&)), m_filtersDock, SLOT(onShowFrame(const SharedFrame&))); connect(m_player, SIGNAL(inChanged(int)), m_filtersDock, SIGNAL(producerInChanged(int))); connect(m_player, SIGNAL(outChanged(int)), m_filtersDock, SIGNAL(producerOutChanged(int))); connect(m_player, SIGNAL(inChanged(int)), m_filterController, SLOT(onFilterInChanged(int))); connect(m_player, SIGNAL(outChanged(int)), m_filterController, SLOT(onFilterOutChanged(int))); connect(m_timelineDock->model(), SIGNAL(filterInChanged(int, Mlt::Filter*)), m_filterController, SLOT(onFilterInChanged(int, Mlt::Filter*))); connect(m_timelineDock->model(), SIGNAL(filterOutChanged(int, Mlt::Filter*)), m_filterController, SLOT(onFilterOutChanged(int, Mlt::Filter*))); m_keyframesDock = new KeyframesDock(m_filtersDock->qmlProducer(), this); m_keyframesDock->hide(); addDockWidget(Qt::BottomDockWidgetArea, m_keyframesDock); m_keyframesDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_7)); ui->menuView->addAction(m_keyframesDock->toggleViewAction()); connect(m_keyframesDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onKeyframesDockTriggered(bool))); connect(ui->actionKeyframes, SIGNAL(triggered()), this, SLOT(onKeyframesDockTriggered())); connect(m_filterController, SIGNAL(currentFilterChanged(QmlFilter*, QmlMetadata*, int)), m_keyframesDock, SLOT(setCurrentFilter(QmlFilter*, QmlMetadata*))); connect(m_keyframesDock, SIGNAL(visibilityChanged(bool)), m_filtersDock->qmlProducer(), SLOT(remakeAudioLevels(bool))); m_historyDock = new QDockWidget(tr("History"), this); m_historyDock->hide(); m_historyDock->setObjectName("historyDock"); m_historyDock->setWindowIcon(ui->actionHistory->icon()); m_historyDock->toggleViewAction()->setIcon(ui->actionHistory->icon()); m_historyDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_8)); m_historyDock->setMinimumWidth(150); addDockWidget(Qt::RightDockWidgetArea, m_historyDock); ui->menuView->addAction(m_historyDock->toggleViewAction()); connect(m_historyDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onHistoryDockTriggered(bool))); connect(ui->actionHistory, SIGNAL(triggered()), this, SLOT(onHistoryDockTriggered())); QUndoView* undoView = new QUndoView(m_undoStack, m_historyDock); undoView->setObjectName("historyView"); undoView->setAlternatingRowColors(true); undoView->setSpacing(2); m_historyDock->setWidget(undoView); ui->actionUndo->setDisabled(true); ui->actionRedo->setDisabled(true); m_encodeDock = new EncodeDock(this); m_encodeDock->hide(); addDockWidget(Qt::LeftDockWidgetArea, m_encodeDock); m_encodeDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_9)); ui->menuView->addAction(m_encodeDock->toggleViewAction()); connect(this, SIGNAL(producerOpened()), m_encodeDock, SLOT(onProducerOpened())); connect(ui->actionEncode, SIGNAL(triggered()), this, SLOT(onEncodeTriggered())); connect(ui->actionExportVideo, SIGNAL(triggered()), this, SLOT(onEncodeTriggered())); connect(m_encodeDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onEncodeTriggered(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_player, SLOT(onCaptureStateChanged(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_propertiesDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_recentDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_filtersDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_keyframesDock, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionOpen, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionOpenOther, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), ui->actionExit, SLOT(setDisabled(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), this, SLOT(onCaptureStateChanged(bool))); connect(m_encodeDock, SIGNAL(captureStateChanged(bool)), m_historyDock, SLOT(setDisabled(bool))); connect(this, SIGNAL(profileChanged()), m_encodeDock, SLOT(onProfileChanged())); connect(this, SIGNAL(profileChanged()), SLOT(onProfileChanged())); connect(this, SIGNAL(profileChanged()), &QmlProfile::singleton(), SIGNAL(profileChanged())); connect(this, SIGNAL(audioChannelsChanged()), m_encodeDock, SLOT(onAudioChannelsChanged())); connect(m_playlistDock->model(), SIGNAL(modified()), m_encodeDock, SLOT(onProducerOpened())); connect(m_timelineDock, SIGNAL(clipCopied()), m_encodeDock, SLOT(onProducerOpened())); m_encodeDock->onProfileChanged(); m_jobsDock = new JobsDock(this); m_jobsDock->hide(); addDockWidget(Qt::RightDockWidgetArea, m_jobsDock); m_jobsDock->toggleViewAction()->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0)); ui->menuView->addAction(m_jobsDock->toggleViewAction()); connect(&JOBS, SIGNAL(jobAdded()), m_jobsDock, SLOT(onJobAdded())); connect(m_jobsDock->toggleViewAction(), SIGNAL(triggered(bool)), this, SLOT(onJobsDockTriggered(bool))); connect(ui->actionJobs, SIGNAL(triggered()), this, SLOT(onJobsDockTriggered())); tabifyDockWidget(m_propertiesDock, m_playlistDock); tabifyDockWidget(m_playlistDock, m_filtersDock); tabifyDockWidget(m_filtersDock, m_encodeDock); QDockWidget* audioWaveformDock = findChild<QDockWidget*>("AudioWaveformDock"); splitDockWidget(m_recentDock, audioWaveformDock, Qt::Vertical); splitDockWidget(audioMeterDock, m_recentDock, Qt::Horizontal); tabifyDockWidget(m_recentDock, m_historyDock); tabifyDockWidget(m_historyDock, m_jobsDock); tabifyDockWidget(m_keyframesDock, m_timelineDock); m_recentDock->raise(); // Configure the View menu. ui->menuView->addSeparator(); ui->menuView->addAction(ui->actionApplicationLog); // connect video widget signals Mlt::GLWidget* videoWidget = (Mlt::GLWidget*) &(MLT); connect(videoWidget, SIGNAL(dragStarted()), m_playlistDock, SLOT(onPlayerDragStarted())); connect(videoWidget, SIGNAL(seekTo(int)), m_player, SLOT(seek(int))); connect(videoWidget, SIGNAL(gpuNotSupported()), this, SLOT(onGpuNotSupported())); connect(videoWidget->quickWindow(), SIGNAL(sceneGraphInitialized()), SLOT(onSceneGraphInitialized()), Qt::QueuedConnection); connect(videoWidget, SIGNAL(frameDisplayed(const SharedFrame&)), m_scopeController, SIGNAL(newFrame(const SharedFrame&))); connect(m_filterController, SIGNAL(currentFilterChanged(QmlFilter*, QmlMetadata*, int)), videoWidget, SLOT(setCurrentFilter(QmlFilter*, QmlMetadata*))); readWindowSettings(); setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea); setCorner(Qt::BottomRightCorner, Qt::BottomDockWidgetArea); setDockNestingEnabled(true); setFocus(); setCurrentFile(""); LeapNetworkListener* leap = new LeapNetworkListener(this); connect(leap, SIGNAL(shuttle(float)), SLOT(onShuttle(float))); connect(leap, SIGNAL(jogRightFrame()), SLOT(stepRightOneFrame())); connect(leap, SIGNAL(jogRightSecond()), SLOT(stepRightOneSecond())); connect(leap, SIGNAL(jogLeftFrame()), SLOT(stepLeftOneFrame())); connect(leap, SIGNAL(jogLeftSecond()), SLOT(stepLeftOneSecond())); connect(&m_network, SIGNAL(finished(QNetworkReply*)), SLOT(onUpgradeCheckFinished(QNetworkReply*))); QThreadPool::globalInstance()->setMaxThreadCount(qMin(4, QThreadPool::globalInstance()->maxThreadCount())); ProxyManager::removePending(); LOG_DEBUG() << "end"; } void MainWindow::onFocusWindowChanged(QWindow *) const { LOG_DEBUG() << "Focuswindow changed"; LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); } void MainWindow::onFocusObjectChanged(QObject *) const { LOG_DEBUG() << "Focusobject changed"; LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); } void MainWindow::onTimelineClipSelected() { // Synchronize navigation position with timeline selection. TimelineDock * t = m_timelineDock; if (t->selection().isEmpty()) return; m_navigationPosition = t->centerOfClip(t->selection().first().y(), t->selection().first().x()); // Switch to Project player. if (m_player->tabIndex() != Player::ProjectTabIndex) { t->saveAndClearSelection(); m_player->onTabBarClicked(Player::ProjectTabIndex); } } void MainWindow::onAddAllToTimeline(Mlt::Playlist* playlist, bool skipProxy) { // We stop the player because of a bug on Windows that results in some // strange memory leak when using Add All To Timeline, more noticeable // with (high res?) still image files. if (MLT.isSeekable()) m_player->pause(); else m_player->stop(); m_timelineDock->appendFromPlaylist(playlist, skipProxy); } MainWindow& MainWindow::singleton() { static MainWindow* instance = new MainWindow; return *instance; } MainWindow::~MainWindow() { delete ui; Mlt::Controller::destroy(); } void MainWindow::setupSettingsMenu() { LOG_DEBUG() << "begin"; QActionGroup* group = new QActionGroup(this); group->addAction(ui->actionChannels1); group->addAction(ui->actionChannels2); group->addAction(ui->actionChannels6); group = new QActionGroup(this); group->addAction(ui->actionOneField); group->addAction(ui->actionLinearBlend); #if LIBMLT_VERSION_INT >= MLT_VERSION_PREVIEW_SCALE m_previewScaleGroup = new QActionGroup(this); m_previewScaleGroup->addAction(ui->actionPreviewNone); m_previewScaleGroup->addAction(ui->actionPreview360); m_previewScaleGroup->addAction(ui->actionPreview540); m_previewScaleGroup->addAction(ui->actionPreview720); #else delete ui->menuPreviewScaling; #endif //XXX workaround yadif crashing with mlt_transition // group->addAction(ui->actionYadifTemporal); // group->addAction(ui->actionYadifSpatial); ui->actionYadifTemporal->setVisible(false); ui->actionYadifSpatial->setVisible(false); group = new QActionGroup(this); group->addAction(ui->actionNearest); group->addAction(ui->actionBilinear); group->addAction(ui->actionBicubic); group->addAction(ui->actionHyper); if (Settings.playerGPU()) { group = new QActionGroup(this); group->addAction(ui->actionGammaRec709); group->addAction(ui->actionGammaSRGB); } else { delete ui->menuGamma; } m_profileGroup = new QActionGroup(this); m_profileGroup->addAction(ui->actionProfileAutomatic); ui->actionProfileAutomatic->setData(QString()); buildVideoModeMenu(ui->menuProfile, m_customProfileMenu, m_profileGroup, ui->actionAddCustomProfile, ui->actionProfileRemove); // Add the SDI and HDMI devices to the Settings menu. m_externalGroup = new QActionGroup(this); ui->actionExternalNone->setData(QString()); m_externalGroup->addAction(ui->actionExternalNone); QList<QScreen*> screens = QGuiApplication::screens(); int n = screens.size(); for (int i = 0; n > 1 && i < n; i++) { QAction* action = new QAction(tr("Screen %1 (%2 x %3 @ %4 Hz)").arg(i) .arg(screens[i]->size().width() * screens[i]->devicePixelRatio()) .arg(screens[i]->size().height() * screens[i]->devicePixelRatio()) .arg(screens[i]->refreshRate()), this); action->setCheckable(true); action->setData(i); m_externalGroup->addAction(action); } Mlt::Profile profile; Mlt::Consumer decklink(profile, "decklink:"); if (decklink.is_valid()) { decklink.set("list_devices", 1); int n = decklink.get_int("devices"); for (int i = 0; i < n; ++i) { QString device(decklink.get(QString("device.%1").arg(i).toLatin1().constData())); if (!device.isEmpty()) { QAction* action = new QAction(device, this); action->setCheckable(true); action->setData(QString("decklink:%1").arg(i)); m_externalGroup->addAction(action); if (!m_keyerGroup) { m_keyerGroup = new QActionGroup(this); action = new QAction(tr("Off"), m_keyerGroup); action->setData(QVariant(0)); action->setCheckable(true); action = new QAction(tr("Internal"), m_keyerGroup); action->setData(QVariant(1)); action->setCheckable(true); action = new QAction(tr("External"), m_keyerGroup); action->setData(QVariant(2)); action->setCheckable(true); } } } } if (m_externalGroup->actions().count() > 1) ui->menuExternal->addActions(m_externalGroup->actions()); else { delete ui->menuExternal; ui->menuExternal = 0; } if (m_keyerGroup) { m_keyerMenu = ui->menuExternal->addMenu(tr("DeckLink Keyer")); m_keyerMenu->addActions(m_keyerGroup->actions()); m_keyerMenu->setDisabled(true); connect(m_keyerGroup, SIGNAL(triggered(QAction*)), this, SLOT(onKeyerTriggered(QAction*))); } connect(m_externalGroup, SIGNAL(triggered(QAction*)), this, SLOT(onExternalTriggered(QAction*))); connect(m_profileGroup, SIGNAL(triggered(QAction*)), this, SLOT(onProfileTriggered(QAction*))); // Setup the language menu actions m_languagesGroup = new QActionGroup(this); QAction* a; a = new QAction(QLocale::languageToString(QLocale::Arabic), m_languagesGroup); a->setCheckable(true); a->setData("ar"); a = new QAction(QLocale::languageToString(QLocale::Catalan), m_languagesGroup); a->setCheckable(true); a->setData("ca"); a = new QAction(QLocale::languageToString(QLocale::Chinese).append(" (China)"), m_languagesGroup); a->setCheckable(true); a->setData("zh_CN"); a = new QAction(QLocale::languageToString(QLocale::Chinese).append(" (Taiwan)"), m_languagesGroup); a->setCheckable(true); a->setData("zh_TW"); a = new QAction(QLocale::languageToString(QLocale::Czech), m_languagesGroup); a->setCheckable(true); a->setData("cs"); a = new QAction(QLocale::languageToString(QLocale::Danish), m_languagesGroup); a->setCheckable(true); a->setData("da"); a = new QAction(QLocale::languageToString(QLocale::Dutch), m_languagesGroup); a->setCheckable(true); a->setData("nl"); a = new QAction(QLocale::languageToString(QLocale::English).append(" (Great Britain)"), m_languagesGroup); a->setCheckable(true); a->setData("en_GB"); a = new QAction(QLocale::languageToString(QLocale::English).append(" (United States)"), m_languagesGroup); a->setCheckable(true); a->setData("en_US"); a = new QAction(QLocale::languageToString(QLocale::Estonian), m_languagesGroup); a->setCheckable(true); a->setData("et"); a = new QAction(QLocale::languageToString(QLocale::Finnish), m_languagesGroup); a->setCheckable(true); a->setData("fi"); a = new QAction(QLocale::languageToString(QLocale::French), m_languagesGroup); a->setCheckable(true); a->setData("fr"); a = new QAction(QLocale::languageToString(QLocale::Gaelic), m_languagesGroup); a->setCheckable(true); a->setData("gd"); a = new QAction(QLocale::languageToString(QLocale::Galician), m_languagesGroup); a->setCheckable(true); a->setData("gl"); a = new QAction(QLocale::languageToString(QLocale::German), m_languagesGroup); a->setCheckable(true); a->setData("de"); a = new QAction(QLocale::languageToString(QLocale::Greek), m_languagesGroup); a->setCheckable(true); a->setData("el"); a = new QAction(QLocale::languageToString(QLocale::Hungarian), m_languagesGroup); a->setCheckable(true); a->setData("hu"); a = new QAction(QLocale::languageToString(QLocale::Italian), m_languagesGroup); a->setCheckable(true); a->setData("it"); a = new QAction(QLocale::languageToString(QLocale::Japanese), m_languagesGroup); a->setCheckable(true); a->setData("ja"); a = new QAction(QLocale::languageToString(QLocale::Korean), m_languagesGroup); a->setCheckable(true); a->setData("ko"); a = new QAction(QLocale::languageToString(QLocale::Nepali), m_languagesGroup); a->setCheckable(true); a->setData("ne"); a = new QAction(QLocale::languageToString(QLocale::NorwegianBokmal), m_languagesGroup); a->setCheckable(true); a->setData("nb"); a = new QAction(QLocale::languageToString(QLocale::NorwegianNynorsk), m_languagesGroup); a->setCheckable(true); a->setData("nn"); a = new QAction(QLocale::languageToString(QLocale::Occitan), m_languagesGroup); a->setCheckable(true); a->setData("oc"); a = new QAction(QLocale::languageToString(QLocale::Polish), m_languagesGroup); a->setCheckable(true); a->setData("pl"); a = new QAction(QLocale::languageToString(QLocale::Portuguese).append(" (Brazil)"), m_languagesGroup); a->setCheckable(true); a->setData("pt_BR"); a = new QAction(QLocale::languageToString(QLocale::Portuguese).append(" (Portugal)"), m_languagesGroup); a->setCheckable(true); a->setData("pt_PT"); a = new QAction(QLocale::languageToString(QLocale::Russian), m_languagesGroup); a->setCheckable(true); a->setData("ru"); a = new QAction(QLocale::languageToString(QLocale::Slovak), m_languagesGroup); a->setCheckable(true); a->setData("sk"); a = new QAction(QLocale::languageToString(QLocale::Slovenian), m_languagesGroup); a->setCheckable(true); a->setData("sl"); a = new QAction(QLocale::languageToString(QLocale::Spanish), m_languagesGroup); a->setCheckable(true); a->setData("es"); a = new QAction(QLocale::languageToString(QLocale::Swedish), m_languagesGroup); a->setCheckable(true); a->setData("sv"); a = new QAction(QLocale::languageToString(QLocale::Thai), m_languagesGroup); a->setCheckable(true); a->setData("th"); a = new QAction(QLocale::languageToString(QLocale::Turkish), m_languagesGroup); a->setCheckable(true); a->setData("tr"); a = new QAction(QLocale::languageToString(QLocale::Ukrainian), m_languagesGroup); a->setCheckable(true); a->setData("uk"); ui->menuLanguage->addActions(m_languagesGroup->actions()); const QString locale = Settings.language(); foreach (QAction* action, m_languagesGroup->actions()) { if (action->data().toString().startsWith(locale)) { action->setChecked(true); break; } } connect(m_languagesGroup, SIGNAL(triggered(QAction*)), this, SLOT(onLanguageTriggered(QAction*))); // Setup the themes actions group = new QActionGroup(this); group->addAction(ui->actionSystemTheme); group->addAction(ui->actionFusionDark); group->addAction(ui->actionFusionLight); if (Settings.theme() == "dark") ui->actionFusionDark->setChecked(true); else if (Settings.theme() == "light") ui->actionFusionLight->setChecked(true); else ui->actionSystemTheme->setChecked(true); #ifdef Q_OS_WIN // On Windows, if there is no JACK or it is not running // then Shotcut crashes inside MLT's call to jack_client_open(). // Therefore, the JACK option for Shotcut is banned on Windows. delete ui->actionJack; ui->actionJack = 0; #endif #if !defined(Q_OS_MAC) // Setup the display method actions. if (!Settings.playerGPU()) { group = new QActionGroup(this); #if defined(Q_OS_WIN) ui->actionDrawingAutomatic->setData(0); group->addAction(ui->actionDrawingAutomatic); ui->actionDrawingDirectX->setData(Qt::AA_UseOpenGLES); group->addAction(ui->actionDrawingDirectX); #else delete ui->actionDrawingAutomatic; delete ui->actionDrawingDirectX; #endif ui->actionDrawingOpenGL->setData(Qt::AA_UseDesktopOpenGL); group->addAction(ui->actionDrawingOpenGL); ui->actionDrawingSoftware->setData(Qt::AA_UseSoftwareOpenGL); group->addAction(ui->actionDrawingSoftware); connect(group, SIGNAL(triggered(QAction*)), this, SLOT(onDrawingMethodTriggered(QAction*))); switch (Settings.drawMethod()) { case Qt::AA_UseDesktopOpenGL: ui->actionDrawingOpenGL->setChecked(true); break; #if defined(Q_OS_WIN) case Qt::AA_UseOpenGLES: ui->actionDrawingDirectX->setChecked(true); break; #endif case Qt::AA_UseSoftwareOpenGL: ui->actionDrawingSoftware->setChecked(true); break; #if defined(Q_OS_WIN) default: ui->actionDrawingAutomatic->setChecked(true); break; #else default: ui->actionDrawingOpenGL->setChecked(true); break; #endif } } else { // GPU mode only works with OpenGL. delete ui->menuDrawingMethod; ui->menuDrawingMethod = 0; } #else // Q_OS_MAC delete ui->menuDrawingMethod; ui->menuDrawingMethod = 0; #endif // Add custom layouts to View > Layout submenu. m_layoutGroup = new QActionGroup(this); connect(m_layoutGroup, SIGNAL(triggered(QAction*)), SLOT(onLayoutTriggered(QAction*))); if (Settings.layouts().size() > 0) { ui->menuLayout->addAction(ui->actionLayoutRemove); ui->menuLayout->addSeparator(); } foreach (QString name, Settings.layouts()) ui->menuLayout->addAction(addLayout(m_layoutGroup, name)); if (qApp->property("clearRecent").toBool()) { ui->actionClearRecentOnExit->setVisible(false); Settings.setRecent(QStringList()); Settings.setClearRecent(true); } else { ui->actionClearRecentOnExit->setChecked(Settings.clearRecent()); } // Initialze the proxy submenu ui->actionUseProxy->setChecked(Settings.proxyEnabled()); ui->actionProxyUseProjectFolder->setChecked(Settings.proxyUseProjectFolder()); ui->actionProxyUseHardware->setChecked(Settings.proxyUseHardware()); LOG_DEBUG() << "end"; } void MainWindow::setupOpenOtherMenu() { // Open Other toolbar menu button QScopedPointer<Mlt::Properties> mltProducers(MLT.repository()->producers()); QScopedPointer<Mlt::Properties> mltFilters(MLT.repository()->filters()); QMenu* otherMenu = new QMenu(this); ui->actionOpenOther2->setMenu(otherMenu); // populate the generators if (mltProducers->get_data("color")) { otherMenu->addAction(tr("Color"), this, SLOT(onOpenOtherTriggered()))->setObjectName("color"); if (!Settings.playerGPU() && mltProducers->get_data("qtext") && mltFilters->get_data("dynamictext")) otherMenu->addAction(tr("Text"), this, SLOT(onOpenOtherTriggered()))->setObjectName("text"); } if (mltProducers->get_data("noise")) otherMenu->addAction(tr("Noise"), this, SLOT(onOpenOtherTriggered()))->setObjectName("noise"); if (mltProducers->get_data("frei0r.ising0r")) otherMenu->addAction(tr("Ising"), this, SLOT(onOpenOtherTriggered()))->setObjectName("ising0r"); if (mltProducers->get_data("frei0r.lissajous0r")) otherMenu->addAction(tr("Lissajous"), this, SLOT(onOpenOtherTriggered()))->setObjectName("lissajous0r"); if (mltProducers->get_data("frei0r.plasma")) otherMenu->addAction(tr("Plasma"), this, SLOT(onOpenOtherTriggered()))->setObjectName("plasma"); if (mltProducers->get_data("frei0r.test_pat_B")) otherMenu->addAction(tr("Color Bars"), this, SLOT(onOpenOtherTriggered()))->setObjectName("test_pat_B"); if (mltProducers->get_data("tone")) otherMenu->addAction(tr("Audio Tone"), this, SLOT(onOpenOtherTriggered()))->setObjectName("tone"); if (mltProducers->get_data("count")) otherMenu->addAction(tr("Count"), this, SLOT(onOpenOtherTriggered()))->setObjectName("count"); if (mltProducers->get_data("blipflash")) otherMenu->addAction(tr("Blip Flash"), this, SLOT(onOpenOtherTriggered()))->setObjectName("blipflash"); #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) otherMenu->addAction(tr("Video4Linux"), this, SLOT(onOpenOtherTriggered()))->setObjectName("v4l2"); otherMenu->addAction(tr("PulseAudio"), this, SLOT(onOpenOtherTriggered()))->setObjectName("pulse"); otherMenu->addAction(tr("JACK Audio"), this, SLOT(onOpenOtherTriggered()))->setObjectName("jack"); otherMenu->addAction(tr("ALSA Audio"), this, SLOT(onOpenOtherTriggered()))->setObjectName("alsa"); #elif defined(Q_OS_WIN) || defined(Q_OS_MAC) otherMenu->addAction(tr("Audio/Video Device"), this, SLOT(onOpenOtherTriggered()))->setObjectName("device"); #endif if (mltProducers->get_data("decklink")) otherMenu->addAction(tr("SDI/HDMI"), this, SLOT(onOpenOtherTriggered()))->setObjectName("decklink"); } QAction* MainWindow::addProfile(QActionGroup* actionGroup, const QString& desc, const QString& name) { QAction* action = new QAction(desc, this); action->setCheckable(true); action->setData(name); actionGroup->addAction(action); return action; } QAction*MainWindow::addLayout(QActionGroup* actionGroup, const QString& name) { QAction* action = new QAction(name, this); actionGroup->addAction(action); return action; } void MainWindow::open(Mlt::Producer* producer) { if (!producer->is_valid()) showStatusMessage(tr("Failed to open ")); else if (producer->get_int("error")) showStatusMessage(tr("Failed to open ") + producer->get("resource")); bool ok = false; int screen = Settings.playerExternal().toInt(&ok); if (ok && screen != QApplication::desktop()->screenNumber(this)) m_player->moveVideoToScreen(screen); // no else here because open() will delete the producer if open fails if (!MLT.setProducer(producer)) { emit producerOpened(); if (!MLT.profile().is_explicit() || MLT.URL().endsWith(".mlt") || MLT.URL().endsWith(".xml")) emit profileChanged(); } m_player->setFocus(); m_playlistDock->setUpdateButtonEnabled(false); // Needed on Windows. Upon first file open, window is deactivated, perhaps OpenGL-related. activateWindow(); } bool MainWindow::isCompatibleWithGpuMode(MltXmlChecker& checker) { if (checker.needsGPU() && !Settings.playerGPU() && Settings.playerWarnGPU()) { LOG_INFO() << "file uses GPU but GPU not enabled"; QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("The file you opened uses GPU effects, but GPU effects are not enabled.\n\n" "GPU effects are EXPERIMENTAL, UNSTABLE and UNSUPPORTED! Unsupported means do not report bugs about it.\n\n" "Do you want to enable GPU effects and restart?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); int r = dialog.exec(); if (r == QMessageBox::Yes) { ui->actionGPU->setChecked(true); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } return false; } else if (checker.needsCPU() && Settings.playerGPU()) { LOG_INFO() << "file uses GPU incompatible filters but GPU is enabled"; QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("The file you opened uses CPU effects that are incompatible with GPU effects, but GPU effects are enabled.\n" "Do you want to disable GPU effects and restart?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); int r = dialog.exec(); if (r == QMessageBox::Yes) { ui->actionGPU->setChecked(false); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } return false; } return true; } bool MainWindow::saveRepairedXmlFile(MltXmlChecker& checker, QString& fileName) { QFileInfo fi(fileName); QFile repaired(QString("%1/%2 - %3.%4").arg(fi.path()) .arg(fi.completeBaseName()).arg(tr("Repaired")).arg(fi.suffix())); repaired.open(QIODevice::WriteOnly); LOG_INFO() << "repaired MLT XML file name" << repaired.fileName(); QFile temp(checker.tempFileName()); if (temp.exists() && repaired.exists()) { temp.open(QIODevice::ReadOnly); QByteArray xml = temp.readAll(); temp.close(); qint64 n = repaired.write(xml); while (n > 0 && n < xml.size()) { qint64 x = repaired.write(xml.right(xml.size() - n)); if (x > 0) n += x; else n = x; } repaired.close(); if (n == xml.size()) { fileName = repaired.fileName(); return true; } } QMessageBox::warning(this, qApp->applicationName(), tr("Repairing the project failed.")); LOG_WARNING() << "repairing failed"; return false; } bool MainWindow::isXmlRepaired(MltXmlChecker& checker, QString& fileName) { bool result = true; if (checker.isCorrected()) { LOG_WARNING() << fileName; QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Shotcut noticed some problems in your project.\n" "Do you want Shotcut to try to repair it?\n\n" "If you choose Yes, Shotcut will create a copy of your project\n" "with \"- Repaired\" in the file name and open it."), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); int r = dialog.exec(); if (r == QMessageBox::Yes) result = saveRepairedXmlFile(checker, fileName); } else if (checker.unlinkedFilesModel().rowCount() > 0) { UnlinkedFilesDialog dialog(this); dialog.setModel(checker.unlinkedFilesModel()); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QDialog::Accepted) { if (checker.check(fileName) && checker.isCorrected()) result = saveRepairedXmlFile(checker, fileName); } else { result = false; } } return result; } bool MainWindow::checkAutoSave(QString &url) { QMutexLocker locker(&m_autosaveMutex); // check whether autosave files exist: QSharedPointer<AutoSaveFile> stale(AutoSaveFile::getFile(url)); if (stale) { QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Auto-saved files exist. Do you want to recover them now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); int r = dialog.exec(); if (r == QMessageBox::Yes) { if (!stale->open(QIODevice::ReadWrite)) { LOG_WARNING() << "failed to recover autosave file" << url; } else { m_autosaveFile = stale; url = stale->fileName(); return true; } } } // create new autosave object m_autosaveFile.reset(new AutoSaveFile(url)); return false; } void MainWindow::stepLeftBySeconds(int sec) { m_player->seek(m_player->position() + sec * qRound(MLT.profile().fps())); } void MainWindow::doAutosave() { QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile) { bool success = false; if (m_autosaveFile->isOpen() || m_autosaveFile->open(QIODevice::ReadWrite)) { m_autosaveFile->close(); success = saveXML(m_autosaveFile->fileName(), false /* without relative paths */); m_autosaveFile->open(QIODevice::ReadWrite); } if (!success) { LOG_ERROR() << "failed to open autosave file for writing" << m_autosaveFile->fileName(); } } } void MainWindow::setFullScreen(bool isFullScreen) { if (isFullScreen) { #ifdef Q_OS_WIN showMaximized(); #else showFullScreen(); #endif ui->actionEnter_Full_Screen->setVisible(false); ui->actionFullscreen->setVisible(false); } } QString MainWindow::untitledFileName() const { QDir dir = Settings.appDataLocation(); if (!dir.exists()) dir.mkpath(dir.path()); return dir.filePath("__untitled__.mlt"); } void MainWindow::setProfile(const QString &profile_name) { LOG_DEBUG() << profile_name; MLT.setProfile(profile_name); emit profileChanged(); } bool MainWindow::isSourceClipMyProject(QString resource) { if (m_player->tabIndex() == Player::ProjectTabIndex && MLT.savedProducer() && MLT.savedProducer()->is_valid()) resource = QString::fromUtf8(MLT.savedProducer()->get("resource")); if (!resource.isEmpty() && QDir(resource) == QDir(fileName())) { QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You cannot add a project to itself!"), QMessageBox::Ok, this); dialog.setDefaultButton(QMessageBox::Ok); dialog.setEscapeButton(QMessageBox::Ok); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.exec(); return true; } return false; } bool MainWindow::keyframesDockIsVisible() const { return m_keyframesDock && m_keyframesDock->isVisible(); } void MainWindow::setAudioChannels(int channels) { LOG_DEBUG() << channels; MLT.videoWidget()->setProperty("audio_channels", channels); MLT.setAudioChannels(channels); if (channels == 1) ui->actionChannels1->setChecked(true); else if (channels == 2) ui->actionChannels2->setChecked(true); else if (channels == 6) ui->actionChannels6->setChecked(true); emit audioChannelsChanged(); } void MainWindow::showSaveError() { QMessageBox dialog(QMessageBox::Critical, qApp->applicationName(), tr("There was an error saving. Please try again."), QMessageBox::Ok, this); dialog.setDefaultButton(QMessageBox::Ok); dialog.setEscapeButton(QMessageBox::Ok); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.exec(); } void MainWindow::setPreviewScale(int scale) { LOG_DEBUG() << scale; switch (scale) { case 360: ui->actionPreview360->setChecked(true); break; case 540: ui->actionPreview540->setChecked(true); break; case 720: ui->actionPreview720->setChecked(true); break; default: ui->actionPreviewNone->setChecked(true); break; } MLT.setPreviewScale(scale); MLT.refreshConsumer(); } void MainWindow::setVideoModeMenu() { // Find a matching video mode for (const auto action : m_profileGroup->actions()) { auto s = action->data().toString(); Mlt::Profile profile(s.toUtf8().constData()); if (MLT.profile().width() == profile.width() && MLT.profile().height() == profile.height() && MLT.profile().sample_aspect_num() == profile.sample_aspect_num() && MLT.profile().sample_aspect_den() == profile.sample_aspect_den() && MLT.profile().frame_rate_num() == profile.frame_rate_num() && MLT.profile().frame_rate_den() == profile.frame_rate_den() && MLT.profile().colorspace() == profile.colorspace() && MLT.profile().progressive() == profile.progressive()) { // Select it action->setChecked(true); return; } } // Choose Automatic if nothing found m_profileGroup->actions().first()->setChecked(true); } void MainWindow::resetVideoModeMenu() { // Change selected Video Mode back to Settings for (const auto action : m_profileGroup->actions()) { if (action->data().toString() == Settings.playerProfile()) { action->setChecked(true); break; } } } static void autosaveTask(MainWindow* p) { LOG_DEBUG_TIME(); p->doAutosave(); } void MainWindow::onAutosaveTimeout() { if (isWindowModified()) QtConcurrent::run(autosaveTask, this); } void MainWindow::updateAutoSave() { if (!m_autosaveTimer.isActive()) m_autosaveTimer.start(); } void MainWindow::open(QString url, const Mlt::Properties* properties, bool play) { LOG_DEBUG() << url; bool modified = false; MltXmlChecker checker; QFileInfo info(url); if (info.isRelative()) { QDir pwd(QDir::currentPath()); url = pwd.filePath(url); } if (url.endsWith(".mlt") || url.endsWith(".xml")) { if (url != untitledFileName()) { showStatusMessage(tr("Opening %1").arg(url)); QCoreApplication::processEvents(); } } if (checker.check(url)) { if (!isCompatibleWithGpuMode(checker)) return; } if (url.endsWith(".mlt") || url.endsWith(".xml")) { // only check for a modified project when loading a project, not a simple producer if (!continueModified()) return; QCoreApplication::processEvents(); // close existing project if (playlist()) m_playlistDock->model()->close(); if (multitrack()) m_timelineDock->model()->close(); MLT.purgeMemoryPool(); if (!isXmlRepaired(checker, url)) return; modified = checkAutoSave(url); if (modified) { if (checker.check(url)) { if (!isCompatibleWithGpuMode(checker)) return; } if (!isXmlRepaired(checker, url)) return; } // let the new project change the profile if (modified || QFile::exists(url)) { MLT.profile().set_explicit(false); setWindowModified(modified); } } if (!playlist() && !multitrack()) { if (!modified && !continueModified()) return; setCurrentFile(""); setWindowModified(modified); MLT.resetURL(); // Return to automatic video mode if selected. if (m_profileGroup->checkedAction() && m_profileGroup->checkedAction()->data().toString().isEmpty()) MLT.profile().set_explicit(false); } if (url.endsWith(".mlt") || url.endsWith(".xml")) { checker.setLocale(); LOG_INFO() << "decimal point" << MLT.decimalPoint(); } QString urlToOpen = checker.isUpdated()? checker.tempFileName() : url; if (!MLT.open(QDir::fromNativeSeparators(urlToOpen), QDir::fromNativeSeparators(url)) && MLT.producer() && MLT.producer()->is_valid()) { Mlt::Properties* props = const_cast<Mlt::Properties*>(properties); if (props && props->is_valid()) mlt_properties_inherit(MLT.producer()->get_properties(), props->get_properties()); m_player->setPauseAfterOpen(!play || !MLT.isClip()); setAudioChannels(MLT.audioChannels()); if (url.endsWith(".mlt") || url.endsWith(".xml")) { setVideoModeMenu(); } open(MLT.producer()); if (url.startsWith(AutoSaveFile::path())) { QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile && m_autosaveFile->managedFileName() != untitledFileName()) { m_recentDock->add(m_autosaveFile->managedFileName()); LOG_INFO() << m_autosaveFile->managedFileName(); } } else { m_recentDock->add(url); LOG_INFO() << url; } } else if (url != untitledFileName()) { showStatusMessage(tr("Failed to open ") + url); emit openFailed(url); } } void MainWindow::openMultiple(const QStringList& paths) { if (paths.size() > 1) { QList<QUrl> urls; foreach (const QString& s, paths) urls << s; openMultiple(urls); } else if (!paths.isEmpty()) { open(paths.first()); } } void MainWindow::openMultiple(const QList<QUrl>& urls) { if (urls.size() > 1) { m_multipleFiles = Util::sortedFileList(Util::expandDirectories(urls)); open(m_multipleFiles.first()); } else { QUrl url = urls.first(); open(Util::removeFileScheme(url)); } } void MainWindow::openVideo() { QString path = Settings.openPath(); #ifdef Q_OS_MAC path.append("/*"); #endif QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path, tr("All Files (*);;MLT XML (*.mlt)")); if (filenames.length() > 0) { Settings.setOpenPath(QFileInfo(filenames.first()).path()); activateWindow(); if (filenames.length() > 1) m_multipleFiles = filenames; open(filenames.first()); } else { // If file invalid, then on some platforms the dialog messes up SDL. MLT.onWindowResize(); activateWindow(); } } void MainWindow::openCut(Mlt::Producer* producer, bool play) { m_player->setPauseAfterOpen(!play); open(producer); MLT.seek(producer->get_in()); } void MainWindow::hideProducer() { // This is a hack to release references to the old producer, but it // probably leaves a reference to the new color producer somewhere not // yet identified (root cause). openCut(new Mlt::Producer(MLT.profile(), "color:_hide")); QCoreApplication::processEvents(); openCut(new Mlt::Producer(MLT.profile(), "color:_hide")); QCoreApplication::processEvents(); QScrollArea* scrollArea = (QScrollArea*) m_propertiesDock->widget(); delete scrollArea->widget(); scrollArea->setWidget(nullptr); m_player->reset(); QCoreApplication::processEvents(); } void MainWindow::closeProducer() { hideProducer(); MLT.stop(); MLT.close(); MLT.setSavedProducer(0); } void MainWindow::showStatusMessage(QAction* action, int timeoutSeconds) { // This object takes ownership of the passed action. // This version does not currently log its message. m_statusBarAction.reset(action); action->setParent(0); m_player->setStatusLabel(action->text(), timeoutSeconds, action); } void MainWindow::showStatusMessage(const QString& message, int timeoutSeconds) { LOG_INFO() << message; m_player->setStatusLabel(message, timeoutSeconds, 0 /* QAction */); m_statusBarAction.reset(); } void MainWindow::seekPlaylist(int start) { if (!playlist()) return; // we bypass this->open() to prevent sending producerOpened signal to self, which causes to reload playlist if (!MLT.producer() || (void*) MLT.producer()->get_producer() != (void*) playlist()->get_playlist()) MLT.setProducer(new Mlt::Producer(*playlist())); m_player->setIn(-1); m_player->setOut(-1); // since we do not emit producerOpened, these components need updating on_actionJack_triggered(ui->actionJack && ui->actionJack->isChecked()); m_player->onProducerOpened(false); m_encodeDock->onProducerOpened(); m_filterController->setProducer(); updateMarkers(); MLT.seek(start); m_player->setFocus(); m_player->switchToTab(Player::ProjectTabIndex); } void MainWindow::seekTimeline(int position, bool seekPlayer) { if (!multitrack()) return; // we bypass this->open() to prevent sending producerOpened signal to self, which causes to reload playlist if (MLT.producer() && (void*) MLT.producer()->get_producer() != (void*) multitrack()->get_producer()) { MLT.setProducer(new Mlt::Producer(*multitrack())); m_player->setIn(-1); m_player->setOut(-1); // since we do not emit producerOpened, these components need updating on_actionJack_triggered(ui->actionJack && ui->actionJack->isChecked()); m_player->onProducerOpened(false); m_encodeDock->onProducerOpened(); m_filterController->setProducer(); updateMarkers(); m_player->setFocus(); m_player->switchToTab(Player::ProjectTabIndex); m_timelineDock->emitSelectedFromSelection(); } if (seekPlayer) m_player->seek(position); else m_player->pause(); } void MainWindow::seekKeyframes(int position) { m_player->seek(position); } void MainWindow::readPlayerSettings() { LOG_DEBUG() << "begin"; ui->actionRealtime->setChecked(Settings.playerRealtime()); ui->actionProgressive->setChecked(Settings.playerProgressive()); ui->actionScrubAudio->setChecked(Settings.playerScrubAudio()); if (ui->actionJack) ui->actionJack->setChecked(Settings.playerJACK()); if (ui->actionGPU) { MLT.videoWidget()->setProperty("gpu", ui->actionGPU->isChecked()); ui->actionGPU->setChecked(Settings.playerGPU()); } QString external = Settings.playerExternal(); bool ok = false; external.toInt(&ok); auto isExternalPeripheral = !external.isEmpty() && !ok; setAudioChannels(Settings.playerAudioChannels()); #if LIBMLT_VERSION_INT >= MLT_VERSION_PREVIEW_SCALE if (isExternalPeripheral) { setPreviewScale(0); m_previewScaleGroup->setEnabled(false); } else { setPreviewScale(Settings.playerPreviewScale()); m_previewScaleGroup->setEnabled(true); } #endif QString deinterlacer = Settings.playerDeinterlacer(); QString interpolation = Settings.playerInterpolation(); if (deinterlacer == "onefield") ui->actionOneField->setChecked(true); else if (deinterlacer == "linearblend") ui->actionLinearBlend->setChecked(true); else if (deinterlacer == "yadif-nospatial") ui->actionYadifTemporal->setChecked(true); else ui->actionYadifSpatial->setChecked(true); if (interpolation == "nearest") ui->actionNearest->setChecked(true); else if (interpolation == "bilinear") ui->actionBilinear->setChecked(true); else if (interpolation == "bicubic") ui->actionBicubic->setChecked(true); else ui->actionHyper->setChecked(true); foreach (QAction* a, m_externalGroup->actions()) { if (a->data() == external) { a->setChecked(true); if (a->data().toString().startsWith("decklink") && m_keyerMenu) m_keyerMenu->setEnabled(true); break; } } if (m_keyerGroup) { int keyer = Settings.playerKeyerMode(); foreach (QAction* a, m_keyerGroup->actions()) { if (a->data() == keyer) { a->setChecked(true); break; } } } QString profile = Settings.playerProfile(); // Automatic not permitted for SDI/HDMI if (isExternalPeripheral && profile.isEmpty()) profile = "atsc_720p_50"; foreach (QAction* a, m_profileGroup->actions()) { // Automatic not permitted for SDI/HDMI if (a->data().toString().isEmpty() && !external.isEmpty() && !ok) a->setDisabled(true); if (a->data().toString() == profile) { a->setChecked(true); break; } } QString gamma = Settings.playerGamma(); if (gamma == "bt709") ui->actionGammaRec709->setChecked(true); else ui->actionGammaSRGB->setChecked(true); LOG_DEBUG() << "end"; } void MainWindow::readWindowSettings() { LOG_DEBUG() << "begin"; Settings.setWindowGeometryDefault(saveGeometry()); Settings.setWindowStateDefault(saveState()); Settings.sync(); if (!Settings.windowGeometry().isEmpty()) { restoreGeometry(Settings.windowGeometry()); restoreState(Settings.windowState()); #ifdef Q_OS_MAC m_filtersDock->setFloating(false); #endif } else { on_actionLayoutTimeline_triggered(); } LOG_DEBUG() << "end"; } void MainWindow::writeSettings() { #ifndef Q_OS_MAC if (isFullScreen()) showNormal(); #endif Settings.setPlayerGPU(ui->actionGPU->isChecked()); Settings.setWindowGeometry(saveGeometry()); Settings.setWindowState(saveState()); Settings.sync(); } void MainWindow::configureVideoWidget() { LOG_DEBUG() << "begin"; if (m_profileGroup->checkedAction()) setProfile(m_profileGroup->checkedAction()->data().toString()); MLT.videoWidget()->setProperty("realtime", ui->actionRealtime->isChecked()); bool ok = false; m_externalGroup->checkedAction()->data().toInt(&ok); if (!ui->menuExternal || m_externalGroup->checkedAction()->data().toString().isEmpty() || ok) { MLT.videoWidget()->setProperty("progressive", ui->actionProgressive->isChecked()); } else { MLT.videoWidget()->setProperty("mlt_service", m_externalGroup->checkedAction()->data()); MLT.videoWidget()->setProperty("progressive", MLT.profile().progressive()); ui->actionProgressive->setEnabled(false); } if (ui->actionChannels1->isChecked()) setAudioChannels(1); else if (ui->actionChannels2->isChecked()) setAudioChannels(2); else setAudioChannels(6); if (ui->actionOneField->isChecked()) MLT.videoWidget()->setProperty("deinterlace_method", "onefield"); else if (ui->actionLinearBlend->isChecked()) MLT.videoWidget()->setProperty("deinterlace_method", "linearblend"); else if (ui->actionYadifTemporal->isChecked()) MLT.videoWidget()->setProperty("deinterlace_method", "yadif-nospatial"); else MLT.videoWidget()->setProperty("deinterlace_method", "yadif"); if (ui->actionNearest->isChecked()) MLT.videoWidget()->setProperty("rescale", "nearest"); else if (ui->actionBilinear->isChecked()) MLT.videoWidget()->setProperty("rescale", "bilinear"); else if (ui->actionBicubic->isChecked()) MLT.videoWidget()->setProperty("rescale", "bicubic"); else MLT.videoWidget()->setProperty("rescale", "hyper"); if (m_keyerGroup) MLT.videoWidget()->setProperty("keyer", m_keyerGroup->checkedAction()->data()); LOG_DEBUG() << "end"; } void MainWindow::setCurrentFile(const QString &filename) { QString shownName = tr("Untitled"); if (filename == untitledFileName()) m_currentFile.clear(); else m_currentFile = filename; if (!m_currentFile.isEmpty()) shownName = QFileInfo(m_currentFile).fileName(); #ifdef Q_OS_MAC setWindowTitle(QString("%1 - %2").arg(shownName).arg(qApp->applicationName())); #else setWindowTitle(QString("%1[*] - %2").arg(shownName).arg(qApp->applicationName())); #endif } void MainWindow::on_actionAbout_Shotcut_triggered() { QMessageBox::about(this, tr("About Shotcut"), tr("<h1>Shotcut version %1</h1>" "<p><a href=\"https://www.shotcut.org/\">Shotcut</a> is a free, open source, cross platform video editor.</p>" "<small><p>Copyright &copy; 2011-2020 <a href=\"https://www.meltytech.com/\">Meltytech</a>, LLC</p>" "<p>Licensed under the <a href=\"https://www.gnu.org/licenses/gpl.html\">GNU General Public License v3.0</a></p>" "<p>This program proudly uses the following projects:<ul>" "<li><a href=\"https://www.qt.io/\">Qt</a> application and UI framework</li>" "<li><a href=\"https://www.mltframework.org/\">MLT</a> multimedia authoring framework</li>" "<li><a href=\"https://www.ffmpeg.org/\">FFmpeg</a> multimedia format and codec libraries</li>" "<li><a href=\"https://www.videolan.org/developers/x264.html\">x264</a> H.264 encoder</li>" "<li><a href=\"https://www.webmproject.org/\">WebM</a> VP8 and VP9 encoders</li>" "<li><a href=\"http://lame.sourceforge.net/\">LAME</a> MP3 encoder</li>" "<li><a href=\"https://www.dyne.org/software/frei0r/\">Frei0r</a> video plugins</li>" "<li><a href=\"https://www.ladspa.org/\">LADSPA</a> audio plugins</li>" "<li><a href=\"http://www.defaulticon.com/\">DefaultIcon</a> icon collection by <a href=\"http://www.interactivemania.com/\">interactivemania</a></li>" "<li><a href=\"http://www.oxygen-icons.org/\">Oxygen</a> icon collection</li>" "</ul></p>" "<p>The source code used to build this program can be downloaded from " "<a href=\"https://www.shotcut.org/\">shotcut.org</a>.</p>" "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.</small>" ).arg(qApp->applicationVersion())); } void MainWindow::keyPressEvent(QKeyEvent* event) { if (event->isAccepted() && event->key() != Qt::Key_F12) return; bool handled = true; switch (event->key()) { case Qt::Key_Home: m_player->seek(0); break; case Qt::Key_End: if (MLT.producer()) m_player->seek(MLT.producer()->get_length() - 1); break; case Qt::Key_Left: if ((event->modifiers() & Qt::ControlModifier) && m_timelineDock->isVisible()) { if (m_timelineDock->selection().isEmpty()) { m_timelineDock->selectClipUnderPlayhead(); } else if (m_timelineDock->selection().size() == 1) { int newIndex = m_timelineDock->selection().first().x() - 1; if (newIndex < 0) break; m_timelineDock->setSelection(QList<QPoint>() << QPoint(newIndex, m_timelineDock->selection().first().y())); m_navigationPosition = m_timelineDock->centerOfClip(m_timelineDock->currentTrack(), newIndex); } } else { stepLeftOneFrame(); } break; case Qt::Key_Right: if ((event->modifiers() & Qt::ControlModifier) && m_timelineDock->isVisible()) { if (m_timelineDock->selection().isEmpty()) { m_timelineDock->selectClipUnderPlayhead(); } else if (m_timelineDock->selection().size() == 1) { int newIndex = m_timelineDock->selection().first().x() + 1; if (newIndex >= m_timelineDock->clipCount(-1)) break; m_timelineDock->setSelection(QList<QPoint>() << QPoint(newIndex, m_timelineDock->selection().first().y())); m_navigationPosition = m_timelineDock->centerOfClip(m_timelineDock->currentTrack(), newIndex); } } else { stepRightOneFrame(); } break; case Qt::Key_PageUp: case Qt::Key_PageDown: { int directionMultiplier = event->key() == Qt::Key_PageUp ? -1 : 1; int seconds = 1; if (event->modifiers() & Qt::ControlModifier) seconds *= 5; if (event->modifiers() & Qt::ShiftModifier) seconds *= 2; stepLeftBySeconds(seconds * directionMultiplier); } break; case Qt::Key_Space: #ifdef Q_OS_MAC // Spotlight defaults to Cmd+Space, so also accept Ctrl+Space. if ((event->modifiers() == Qt::MetaModifier || (event->modifiers() & Qt::ControlModifier)) && m_timelineDock->isVisible()) #else if (event->modifiers() == Qt::ControlModifier && m_timelineDock->isVisible()) #endif m_timelineDock->selectClipUnderPlayhead(); else handled = false; break; case Qt::Key_A: if (event->modifiers() == Qt::ShiftModifier) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionAppendCut_triggered(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::ShiftModifier)) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionSelectAll_triggered(); } else if (event->modifiers() == Qt::ControlModifier) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->selectAll(); } else if (event->modifiers() == Qt::NoModifier) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->append(-1); } break; case Qt::Key_C: if (event->modifiers() == Qt::ShiftModifier && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionCopy_triggered(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::AltModifier)) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->copyToSource(); } else if (isMultitrackValid()) { m_timelineDock->show(); m_timelineDock->raise(); if (m_timelineDock->selection().isEmpty()) { m_timelineDock->copyClip(-1, -1); } else { auto& selected = m_timelineDock->selection().first(); m_timelineDock->copyClip(selected.y(), selected.x()); } } break; case Qt::Key_D: if (event->modifiers() == Qt::ControlModifier) { m_timelineDock->setSelection(); m_timelineDock->model()->reload(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::ShiftModifier)) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionSelectNone_triggered(); } else { handled = false; } break; case Qt::Key_F: if (event->modifiers() == Qt::NoModifier || event->modifiers() == Qt::ControlModifier) { m_filtersDock->show(); m_filtersDock->raise(); m_filtersDock->widget()->setFocus(); m_filtersDock->openFilterMenu(); } else if (event->modifiers() == Qt::ShiftModifier) { filterController()->removeCurrent(); } else { handled = false; } break; case Qt::Key_H: #ifdef Q_OS_MAC // OS X uses Cmd+H to hide an app. if (event->modifiers() & Qt::MetaModifier && isMultitrackValid()) #else if (event->modifiers() & Qt::ControlModifier && isMultitrackValid()) #endif m_timelineDock->toggleTrackHidden(m_timelineDock->currentTrack()); break; case Qt::Key_J: if (m_isKKeyPressed) m_player->seek(m_player->position() - 1); else m_player->rewind(false); break; case Qt::Key_K: m_player->pause(); m_isKKeyPressed = true; break; case Qt::Key_L: #ifdef Q_OS_MAC // OS X uses Cmd+H to hide an app and Cmd+M to minimize. Therefore, we force // it to be the apple keyboard control key aka meta. Therefore, to be // consistent with all track header toggles, we make the lock toggle also use // meta. if (event->modifiers() & Qt::MetaModifier && isMultitrackValid()) #else if (event->modifiers() & Qt::ControlModifier && isMultitrackValid()) #endif m_timelineDock->setTrackLock(m_timelineDock->currentTrack(), !m_timelineDock->isTrackLocked(m_timelineDock->currentTrack())); else if (m_isKKeyPressed) m_player->seek(m_player->position() + 1); else m_player->fastForward(false); break; case Qt::Key_M: #ifdef Q_OS_MAC // OS X uses Cmd+M to minimize an app. if (event->modifiers() & Qt::MetaModifier && isMultitrackValid()) #else if (event->modifiers() & Qt::ControlModifier && isMultitrackValid()) #endif m_timelineDock->toggleTrackMute(m_timelineDock->currentTrack()); break; case Qt::Key_I: if (event->modifiers() == Qt::ControlModifier) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->addVideoTrack(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::AltModifier)) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->insertTrack(); } else { setInToCurrent(event->modifiers() & Qt::ShiftModifier); } break; case Qt::Key_O: setOutToCurrent(event->modifiers() & Qt::ShiftModifier); break; case Qt::Key_P: if (event->modifiers() == Qt::ControlModifier) { Settings.setTimelineSnap(!Settings.timelineSnap()); } break; case Qt::Key_R: if (event->modifiers() & Qt::ControlModifier) { if (event->modifiers() & Qt::AltModifier) { Settings.setTimelineRippleAllTracks(!Settings.timelineRippleAllTracks()); } else if (event->modifiers() & Qt::ShiftModifier) { Settings.setTimelineRippleAllTracks(!Settings.timelineRipple()); Settings.setTimelineRipple(!Settings.timelineRipple()); } else { Settings.setTimelineRipple(!Settings.timelineRipple()); } } else if (isMultitrackValid()) { m_timelineDock->show(); m_timelineDock->raise(); if (MLT.isClip() || m_timelineDock->selection().isEmpty()) { m_timelineDock->replace(-1, -1); } else { auto& selected = m_timelineDock->selection().first(); m_timelineDock->replace(selected.y(), selected.x()); } } break; case Qt::Key_S: if (isMultitrackValid()) m_timelineDock->splitClip(); break; case Qt::Key_U: if (event->modifiers() == Qt::ControlModifier) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->addAudioTrack(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::AltModifier)) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->removeTrack(); } break; case Qt::Key_V: // Avid Splice In if (event->modifiers() == Qt::ShiftModifier) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionInsertCut_triggered(); } else { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->insert(-1); } break; case Qt::Key_B: if (event->modifiers() & Qt::ControlModifier && event->modifiers() & Qt::AltModifier) { // Toggle track blending. int trackIndex = m_timelineDock->currentTrack(); bool isBottomVideo = m_timelineDock->model()->data(m_timelineDock->model()->index(trackIndex), MultitrackModel::IsBottomVideoRole).toBool(); if (!isBottomVideo) { bool isComposite = m_timelineDock->model()->data(m_timelineDock->model()->index(trackIndex), MultitrackModel::IsCompositeRole).toBool(); m_timelineDock->setTrackComposite(trackIndex, !isComposite); } } else if (event->modifiers() == Qt::ShiftModifier) { if (m_playlistDock->model()->rowCount() > 0) { // Update playlist item. m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_actionUpdate_triggered(); } } else { // Overwrite on timeline. m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->overwrite(-1); } break; case Qt::Key_Escape: // Avid Toggle Active Monitor if (MLT.isPlaylist()) { if (isMultitrackValid()) m_player->onTabBarClicked(Player::ProjectTabIndex); else if (MLT.savedProducer()) m_player->onTabBarClicked(Player::SourceTabIndex); else m_playlistDock->on_actionOpen_triggered(); } else if (MLT.isMultitrack()) { if (MLT.savedProducer()) m_player->onTabBarClicked(Player::SourceTabIndex); // TODO else open clip under playhead of current track if available } else { if (isMultitrackValid() || (playlist() && playlist()->count() > 0)) m_player->onTabBarClicked(Player::ProjectTabIndex); } break; case Qt::Key_Up: if (m_playlistDock->isVisible() && event->modifiers() & Qt::AltModifier && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->decrementIndex(); m_playlistDock->on_actionOpen_triggered(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::ShiftModifier)) { if (m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->moveClipUp(); m_playlistDock->decrementIndex(); } } else if (isMultitrackValid()) { int newClipIndex = -1; int trackIndex = m_timelineDock->currentTrack() - 1; if ((event->modifiers() & Qt::ControlModifier) && !m_timelineDock->selection().isEmpty() && trackIndex > -1) { newClipIndex = m_timelineDock->clipIndexAtPosition(trackIndex, m_navigationPosition); } m_timelineDock->incrementCurrentTrack(-1); if (newClipIndex >= 0) { newClipIndex = qMin(newClipIndex, m_timelineDock->clipCount(trackIndex) - 1); m_timelineDock->setSelection(QList<QPoint>() << QPoint(newClipIndex, trackIndex)); } } break; case Qt::Key_Down: if (m_playlistDock->isVisible() && event->modifiers() & Qt::AltModifier && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->incrementIndex(); m_playlistDock->on_actionOpen_triggered(); } else if ((event->modifiers() & Qt::ControlModifier) && (event->modifiers() & Qt::ShiftModifier)) { if (m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->moveClipDown(); m_playlistDock->incrementIndex(); } } else if (isMultitrackValid()) { int newClipIndex = -1; int trackIndex = m_timelineDock->currentTrack() + 1; if ((event->modifiers() & Qt::ControlModifier) && !m_timelineDock->selection().isEmpty() && trackIndex < m_timelineDock->model()->trackList().count()) { newClipIndex = m_timelineDock->clipIndexAtPosition(trackIndex, m_navigationPosition); } m_timelineDock->incrementCurrentTrack(1); if (newClipIndex >= 0) { newClipIndex = qMin(newClipIndex, m_timelineDock->clipCount(trackIndex) - 1); m_timelineDock->setSelection(QList<QPoint>() << QPoint(newClipIndex, trackIndex)); } } break; case Qt::Key_1: case Qt::Key_2: case Qt::Key_3: case Qt::Key_4: case Qt::Key_5: case Qt::Key_6: case Qt::Key_7: case Qt::Key_8: case Qt::Key_9: if (!event->modifiers() && m_playlistDock->isVisible() && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->setIndex(event->key() - Qt::Key_1); } break; case Qt::Key_0: if (!event->modifiers() ) { if (m_timelineDock->isVisible()) { m_timelineDock->resetZoom(); } else if (m_playlistDock->isVisible() && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->raise(); m_playlistDock->setIndex(9); } } if (m_keyframesDock->isVisible() && (event->modifiers() & Qt::AltModifier)) { emit m_keyframesDock->resetZoom(); } break; case Qt::Key_X: // Avid Extract if (event->modifiers() == Qt::ShiftModifier && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_removeButton_clicked(); } else if (isMultitrackValid()) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->removeSelection(); } break; case Qt::Key_Backspace: case Qt::Key_Delete: if (isMultitrackValid()) { m_timelineDock->show(); m_timelineDock->raise(); if (event->modifiers() == Qt::ShiftModifier) m_timelineDock->removeSelection(); else m_timelineDock->liftSelection(); } else if (m_playlistDock->model()->rowCount() > 0) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_removeButton_clicked(); } break; case Qt::Key_Z: // Avid Lift if (event->modifiers() == Qt::ShiftModifier && m_playlistDock->model()->rowCount() > 0) { m_playlistDock->show(); m_playlistDock->raise(); m_playlistDock->on_removeButton_clicked(); } else if (isMultitrackValid() && event->modifiers() == Qt::NoModifier) { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->liftSelection(); } break; case Qt::Key_Minus: if (m_timelineDock->isVisible() && !(event->modifiers() & Qt::AltModifier)) { if (event->modifiers() & Qt::ControlModifier) m_timelineDock->makeTracksShorter(); else m_timelineDock->zoomOut(); } if (m_keyframesDock->isVisible() && (event->modifiers() & Qt::AltModifier)) { emit m_keyframesDock->zoomOut(); } break; case Qt::Key_Equal: case Qt::Key_Plus: if (m_timelineDock->isVisible() && !(event->modifiers() & Qt::AltModifier)) { if (event->modifiers() & Qt::ControlModifier) m_timelineDock->makeTracksTaller(); else m_timelineDock->zoomIn(); } if (m_keyframesDock->isVisible() && (event->modifiers() & Qt::AltModifier)) { emit m_keyframesDock->zoomIn(); } break; case Qt::Key_Enter: // Seek to current playlist item case Qt::Key_Return: if (m_playlistDock->isVisible() && m_playlistDock->position() >= 0) { if (event->modifiers() == Qt::ShiftModifier) seekPlaylist(m_playlistDock->position()); else if (event->modifiers() == Qt::ControlModifier) m_playlistDock->on_actionOpen_triggered(); } break; case Qt::Key_F2: onPropertiesDockTriggered(true); emit renameRequested(); break; case Qt::Key_F3: onRecentDockTriggered(true); m_recentDock->find(); break; case Qt::Key_F5: m_timelineDock->model()->reload(); m_keyframesDock->model().reload(); break; case Qt::Key_F12: LOG_DEBUG() << "event isAccepted:" << event->isAccepted(); LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); break; case Qt::Key_BracketLeft: if (filterController()->currentFilter() && m_filtersDock->qmlProducer()) { if (event->modifiers() == Qt::AltModifier) { emit m_keyframesDock->seekPreviousSimple(); } else { int i = m_filtersDock->qmlProducer()->position() + m_filtersDock->qmlProducer()->in(); filterController()->currentFilter()->setIn(i); } } break; case Qt::Key_BracketRight: if (filterController()->currentFilter() && m_filtersDock->qmlProducer()) { if (event->modifiers() == Qt::AltModifier) { emit m_keyframesDock->seekNextSimple(); } else { int i = m_filtersDock->qmlProducer()->position() + m_filtersDock->qmlProducer()->in(); filterController()->currentFilter()->setOut(i); } } break; case Qt::Key_BraceLeft: if (filterController()->currentFilter() && m_filtersDock->qmlProducer()) { int i = m_filtersDock->qmlProducer()->position() + m_filtersDock->qmlProducer()->in() - filterController()->currentFilter()->in(); filterController()->currentFilter()->setAnimateIn(i); } break; case Qt::Key_BraceRight: if (filterController()->currentFilter() && m_filtersDock->qmlProducer()) { int i = filterController()->currentFilter()->out() - (m_filtersDock->qmlProducer()->position() + m_filtersDock->qmlProducer()->in()); filterController()->currentFilter()->setAnimateOut(i); } break; case Qt::Key_Semicolon: if (filterController()->currentFilter() && m_filtersDock->qmlProducer() && m_keyframesDock->currentParameter() >= 0) { auto position = m_filtersDock->qmlProducer()->position() - (filterController()->currentFilter()->in() - m_filtersDock->qmlProducer()->in()); auto parameterIndex = m_keyframesDock->currentParameter(); if (m_keyframesDock->model().isKeyframe(parameterIndex, position)) { auto keyframeIndex = m_keyframesDock->model().keyframeIndex(parameterIndex, position); m_keyframesDock->model().remove(parameterIndex, keyframeIndex); } else { m_keyframesDock->model().addKeyframe(parameterIndex, position); } } break; default: handled = false; break; } if (handled) event->setAccepted(handled); else QMainWindow::keyPressEvent(event); } void MainWindow::keyReleaseEvent(QKeyEvent* event) { if (event->key() == Qt::Key_K) { m_isKKeyPressed = false; event->setAccepted(true); } else { QMainWindow::keyReleaseEvent(event); } } void MainWindow::hideSetDataDirectory() { delete ui->actionAppDataSet; } QAction *MainWindow::actionAddCustomProfile() const { return ui->actionAddCustomProfile; } QAction *MainWindow::actionProfileRemove() const { return ui->actionProfileRemove; } void MainWindow::buildVideoModeMenu(QMenu* topMenu, QMenu*& customMenu, QActionGroup* group, QAction* addAction, QAction* removeAction) { topMenu->addAction(addProfile(group, "HD 720p 50 fps", "atsc_720p_50")); topMenu->addAction(addProfile(group, "HD 720p 59.94 fps", "atsc_720p_5994")); topMenu->addAction(addProfile(group, "HD 720p 60 fps", "atsc_720p_60")); topMenu->addAction(addProfile(group, "HD 1080i 25 fps", "atsc_1080i_50")); topMenu->addAction(addProfile(group, "HD 1080i 29.97 fps", "atsc_1080i_5994")); topMenu->addAction(addProfile(group, "HD 1080p 23.98 fps", "atsc_1080p_2398")); topMenu->addAction(addProfile(group, "HD 1080p 24 fps", "atsc_1080p_24")); topMenu->addAction(addProfile(group, "HD 1080p 25 fps", "atsc_1080p_25")); topMenu->addAction(addProfile(group, "HD 1080p 29.97 fps", "atsc_1080p_2997")); topMenu->addAction(addProfile(group, "HD 1080p 30 fps", "atsc_1080p_30")); topMenu->addAction(addProfile(group, "HD 1080p 59.94 fps", "atsc_1080p_5994")); topMenu->addAction(addProfile(group, "HD 1080p 50 fps", "atsc_1080p_50")); topMenu->addAction(addProfile(group, "HD 1080p 60 fps", "atsc_1080p_60")); topMenu->addAction(addProfile(group, "SD NTSC", "dv_ntsc")); topMenu->addAction(addProfile(group, "SD PAL", "dv_pal")); topMenu->addAction(addProfile(group, "UHD 2160p 23.98 fps", "uhd_2160p_2398")); topMenu->addAction(addProfile(group, "UHD 2160p 24 fps", "uhd_2160p_24")); topMenu->addAction(addProfile(group, "UHD 2160p 25 fps", "uhd_2160p_25")); topMenu->addAction(addProfile(group, "UHD 2160p 29.97 fps", "uhd_2160p_2997")); topMenu->addAction(addProfile(group, "UHD 2160p 30 fps", "uhd_2160p_30")); topMenu->addAction(addProfile(group, "UHD 2160p 50 fps", "uhd_2160p_50")); topMenu->addAction(addProfile(group, "UHD 2160p 59.94 fps", "uhd_2160p_5994")); topMenu->addAction(addProfile(group, "UHD 2160p 60 fps", "uhd_2160p_60")); QMenu* menu = topMenu->addMenu(tr("Non-Broadcast")); menu->addAction(addProfile(group, "640x480 4:3 NTSC", "square_ntsc")); menu->addAction(addProfile(group, "768x576 4:3 PAL", "square_pal")); menu->addAction(addProfile(group, "854x480 16:9 NTSC", "square_ntsc_wide")); menu->addAction(addProfile(group, "1024x576 16:9 PAL", "square_pal_wide")); menu->addAction(addProfile(group, tr("DVD Widescreen NTSC"), "dv_ntsc_wide")); menu->addAction(addProfile(group, tr("DVD Widescreen PAL"), "dv_pal_wide")); menu->addAction(addProfile(group, "HD 720p 23.98 fps", "atsc_720p_2398")); menu->addAction(addProfile(group, "HD 720p 24 fps", "atsc_720p_24")); menu->addAction(addProfile(group, "HD 720p 25 fps", "atsc_720p_25")); menu->addAction(addProfile(group, "HD 720p 29.97 fps", "atsc_720p_2997")); menu->addAction(addProfile(group, "HD 720p 30 fps", "atsc_720p_30")); menu->addAction(addProfile(group, "HD 1080i 60 fps", "atsc_1080i_60")); menu->addAction(addProfile(group, "HDV 1080i 25 fps", "hdv_1080_50i")); menu->addAction(addProfile(group, "HDV 1080i 29.97 fps", "hdv_1080_60i")); menu->addAction(addProfile(group, "HDV 1080p 25 fps", "hdv_1080_25p")); menu->addAction(addProfile(group, "HDV 1080p 29.97 fps", "hdv_1080_30p")); menu->addAction(addProfile(group, tr("Square 1080p 30 fps"), "square_1080p_30")); menu->addAction(addProfile(group, tr("Square 1080p 60 fps"), "square_1080p_60")); menu->addAction(addProfile(group, tr("Vertical HD 30 fps"), "vertical_hd_30")); menu->addAction(addProfile(group, tr("Vertical HD 60 fps"), "vertical_hd_60")); customMenu = topMenu->addMenu(tr("Custom")); customMenu->addAction(addAction); // Load custom profiles QDir dir(Settings.appDataLocation()); if (dir.cd("profiles")) { QStringList profiles = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); if (profiles.length() > 0) { customMenu->addAction(removeAction); customMenu->addSeparator(); } foreach (QString name, profiles) customMenu->addAction(addProfile(group, name, dir.filePath(name))); } } void MainWindow::newProject(const QString &filename, bool isProjectFolder) { if (isProjectFolder) { QFileInfo info(filename); MLT.setProjectFolder(info.absolutePath()); } if (saveXML(filename)) { QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile) m_autosaveFile->changeManagedFile(filename); else m_autosaveFile.reset(new AutoSaveFile(filename)); setCurrentFile(filename); setWindowModified(false); if (MLT.producer()) showStatusMessage(tr("Saved %1").arg(m_currentFile)); m_undoStack->setClean(); m_recentDock->add(filename); } else { showSaveError(); } } void MainWindow::addCustomProfile(const QString &name, QMenu *menu, QAction *action, QActionGroup *group) { // Add new profile to the menu. QDir dir(Settings.appDataLocation()); if (dir.cd("profiles")) { QStringList profiles = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); if (profiles.length() == 1) { menu->addAction(action); menu->addSeparator(); } action = addProfile(group, name, dir.filePath(name)); action->setChecked(true); menu->addAction(action); Settings.setPlayerProfile(dir.filePath(name)); Settings.sync(); } } void MainWindow::removeCustomProfiles(const QStringList &profiles, QDir& dir, QMenu *menu, QAction *action) { foreach(const QString& profile, profiles) { // Remove the file. dir.remove(profile); // Locate the menu item. foreach (QAction* a, menu->actions()) { if (a->text() == profile) { // Remove the menu item. delete a; break; } } } // If no more custom video modes. if (menu->actions().size() == 3) { // Remove the Remove action and separator. menu->removeAction(action); foreach (QAction* a, menu->actions()) { if (a->isSeparator()) { delete a; break; } } } } // Drag-n-drop events bool MainWindow::eventFilter(QObject* target, QEvent* event) { if (event->type() == QEvent::DragEnter && target == MLT.videoWidget()) { dragEnterEvent(static_cast<QDragEnterEvent*>(event)); return true; } else if (event->type() == QEvent::Drop && target == MLT.videoWidget()) { dropEvent(static_cast<QDropEvent*>(event)); return true; } else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { if (QEvent::KeyPress == event->type()) { // Let Shift+Escape be a global hook to defocus a widget (assign global player focus). auto keyEvent = static_cast<QKeyEvent*>(event); if (Qt::Key_Escape == keyEvent->key() && Qt::ShiftModifier == keyEvent->modifiers()) { m_player->setFocus(); return true; } } QQuickWidget * focusedQuickWidget = qobject_cast<QQuickWidget*>(qApp->focusWidget()); if (focusedQuickWidget && focusedQuickWidget->quickWindow()->activeFocusItem()) { event->accept(); focusedQuickWidget->quickWindow()->sendEvent(focusedQuickWidget->quickWindow()->activeFocusItem(), event); QWidget * w = focusedQuickWidget->parentWidget(); if (!event->isAccepted()) qApp->sendEvent(w, event); return true; } } return QMainWindow::eventFilter(target, event); } void MainWindow::dragEnterEvent(QDragEnterEvent *event) { // Simulate the player firing a dragStarted even to make the playlist close // its help text view. This lets one drop a clip directly into the playlist // from a fresh start. Mlt::GLWidget* videoWidget = (Mlt::GLWidget*) &Mlt::Controller::singleton(); emit videoWidget->dragStarted(); event->acceptProposedAction(); } void MainWindow::dropEvent(QDropEvent *event) { const QMimeData *mimeData = event->mimeData(); if (mimeData->hasFormat("application/x-qabstractitemmodeldatalist")) { QByteArray encoded = mimeData->data("application/x-qabstractitemmodeldatalist"); QDataStream stream(&encoded, QIODevice::ReadOnly); QMap<int, QVariant> roleDataMap; while (!stream.atEnd()) { int row, col; stream >> row >> col >> roleDataMap; } if (roleDataMap.contains(Qt::ToolTipRole)) { // DisplayRole is just basename, ToolTipRole contains full path open(roleDataMap[Qt::ToolTipRole].toString()); event->acceptProposedAction(); } } else if (mimeData->hasUrls()) { openMultiple(mimeData->urls()); event->acceptProposedAction(); } else if (mimeData->hasFormat(Mlt::XmlMimeType )) { m_playlistDock->on_actionOpen_triggered(); event->acceptProposedAction(); } } void MainWindow::closeEvent(QCloseEvent* event) { if (continueJobsRunning() && continueModified()) { if (!m_htmlEditor || m_htmlEditor->close()) { LOG_DEBUG() << "begin"; JOBS.cleanup(); writeSettings(); if (m_exitCode == EXIT_SUCCESS) { MLT.stop(); } else { if (multitrack()) m_timelineDock->model()->close(); if (playlist()) m_playlistDock->model()->close(); else onMultitrackClosed(); } QThreadPool::globalInstance()->clear(); AudioLevelsTask::closeAll(); event->accept(); emit aboutToShutDown(); if (m_exitCode == EXIT_SUCCESS) { QApplication::quit(); LOG_DEBUG() << "end"; ::_Exit(0); } else { QApplication::exit(m_exitCode); LOG_DEBUG() << "end"; } return; } } event->ignore(); } void MainWindow::showEvent(QShowEvent* event) { // This is needed to prevent a crash on windows on startup when timeline // is visible and dock title bars are hidden. Q_UNUSED(event) ui->actionShowTitleBars->setChecked(Settings.showTitleBars()); on_actionShowTitleBars_triggered(Settings.showTitleBars()); ui->actionShowToolbar->setChecked(Settings.showToolBar()); on_actionShowToolbar_triggered(Settings.showToolBar()); ui->actionShowTextUnderIcons->setChecked(Settings.textUnderIcons()); on_actionShowTextUnderIcons_toggled(Settings.textUnderIcons()); ui->actionShowSmallIcons->setChecked(Settings.smallIcons()); on_actionShowSmallIcons_toggled(Settings.smallIcons()); windowHandle()->installEventFilter(this); #ifndef SHOTCUT_NOUPGRADE if (!Settings.noUpgrade() && !qApp->property("noupgrade").toBool()) QTimer::singleShot(0, this, SLOT(showUpgradePrompt())); #endif } void MainWindow::on_actionOpenOther_triggered() { // these static are used to open dialog with previous configuration OpenOtherDialog dialog(this); if (MLT.producer()) dialog.load(MLT.producer()); if (dialog.exec() == QDialog::Accepted) { closeProducer(); open(dialog.newProducer(MLT.profile())); } } void MainWindow::onProducerOpened(bool withReopen) { QWidget* w = loadProducerWidget(MLT.producer()); if (withReopen && w && !MLT.producer()->get(kMultitrackItemProperty)) { if (-1 != w->metaObject()->indexOfSignal("producerReopened()")) connect(w, SIGNAL(producerReopened()), m_player, SLOT(onProducerOpened())); } else if (MLT.isPlaylist()) { m_playlistDock->model()->load(); if (playlist()) { m_isPlaylistLoaded = true; m_player->setIn(-1); m_player->setOut(-1); m_playlistDock->setVisible(true); m_playlistDock->raise(); m_player->enableTab(Player::ProjectTabIndex); m_player->switchToTab(Player::ProjectTabIndex); } } else if (MLT.isMultitrack()) { m_timelineDock->blockSelection(true); m_timelineDock->model()->load(); m_timelineDock->blockSelection(false); if (isMultitrackValid()) { m_player->setIn(-1); m_player->setOut(-1); m_timelineDock->setVisible(true); m_timelineDock->raise(); m_player->enableTab(Player::ProjectTabIndex); m_player->switchToTab(Player::ProjectTabIndex); m_timelineDock->selectMultitrack(); QTimer::singleShot(0, [=]() { m_timelineDock->setSelection(); }); } } if (MLT.isClip()) { m_player->enableTab(Player::SourceTabIndex); m_player->switchToTab(Player::SourceTabIndex); Util::getHash(*MLT.producer()); ui->actionPaste->setEnabled(true); } QMutexLocker locker(&m_autosaveMutex); if (m_autosaveFile) setCurrentFile(m_autosaveFile->managedFileName()); else if (!MLT.URL().isEmpty()) setCurrentFile(MLT.URL()); on_actionJack_triggered(ui->actionJack && ui->actionJack->isChecked()); } void MainWindow::onProducerChanged() { MLT.refreshConsumer(); if (playlist() && MLT.producer() && MLT.producer()->is_valid() && MLT.producer()->get_int(kPlaylistIndexProperty)) m_playlistDock->setUpdateButtonEnabled(true); } bool MainWindow::on_actionSave_triggered() { if (m_currentFile.isEmpty()) { return on_actionSave_As_triggered(); } else { if (Util::warnIfNotWritable(m_currentFile, this, tr("Save XML"))) return false; bool success = saveXML(m_currentFile); QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(new AutoSaveFile(m_currentFile)); setCurrentFile(m_currentFile); setWindowModified(false); if (success) { showStatusMessage(tr("Saved %1").arg(m_currentFile)); } else { showSaveError(); } m_undoStack->setClean(); return true; } } bool MainWindow::on_actionSave_As_triggered() { QString path = Settings.savePath(); if (!m_currentFile.isEmpty()) path = m_currentFile; QString caption = tr("Save XML"); QString filename = QFileDialog::getSaveFileName(this, caption, path, tr("MLT XML (*.mlt)")); if (!filename.isEmpty()) { QFileInfo fi(filename); Settings.setSavePath(fi.path()); if (fi.suffix() != "mlt") filename += ".mlt"; if (Util::warnIfNotWritable(filename, this, caption)) return false; newProject(filename); } return !filename.isEmpty(); } bool MainWindow::continueModified() { if (isWindowModified()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("The project has been modified.\n" "Do you want to save your changes?"), QMessageBox::No | QMessageBox::Cancel | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::Cancel); int r = dialog.exec(); if (r == QMessageBox::Yes || r == QMessageBox::No) { if (r == QMessageBox::Yes) { return on_actionSave_triggered(); } else { QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(); } } else if (r == QMessageBox::Cancel) { return false; } } return true; } bool MainWindow::continueJobsRunning() { if (JOBS.hasIncomplete()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("There are incomplete jobs.\n" "Do you want to still want to exit?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); return (dialog.exec() == QMessageBox::Yes); } if (m_encodeDock->isExportInProgress()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("An export is in progress.\n" "Do you want to still want to exit?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); return (dialog.exec() == QMessageBox::Yes); } return true; } QUndoStack* MainWindow::undoStack() const { return m_undoStack; } void MainWindow::onEncodeTriggered(bool checked) { if (checked) { m_encodeDock->show(); m_encodeDock->raise(); } } void MainWindow::onCaptureStateChanged(bool started) { if (started && (MLT.resource().startsWith("x11grab:") || MLT.resource().startsWith("gdigrab:") || MLT.resource().startsWith("avfoundation")) && !MLT.producer()->get_int(kBackgroundCaptureProperty)) showMinimized(); } void MainWindow::onJobsDockTriggered(bool checked) { if (checked) { m_jobsDock->show(); m_jobsDock->raise(); } } void MainWindow::onRecentDockTriggered(bool checked) { if (checked) { m_recentDock->show(); m_recentDock->raise(); } } void MainWindow::onPropertiesDockTriggered(bool checked) { if (checked) { m_propertiesDock->show(); m_propertiesDock->raise(); } } void MainWindow::onPlaylistDockTriggered(bool checked) { if (checked) { m_playlistDock->show(); m_playlistDock->raise(); } } void MainWindow::onTimelineDockTriggered(bool checked) { if (checked) { m_timelineDock->show(); m_timelineDock->raise(); } } void MainWindow::onHistoryDockTriggered(bool checked) { if (checked) { m_historyDock->show(); m_historyDock->raise(); } } void MainWindow::onFiltersDockTriggered(bool checked) { if (checked) { m_filtersDock->show(); m_filtersDock->raise(); } } void MainWindow::onKeyframesDockTriggered(bool checked) { if (checked) { m_keyframesDock->show(); m_keyframesDock->raise(); } } void MainWindow::onPlaylistCreated() { if (!playlist() || playlist()->count() == 0) return; m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onPlaylistLoaded() { updateMarkers(); m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onPlaylistCleared() { m_player->onTabBarClicked(Player::SourceTabIndex); setWindowModified(true); } void MainWindow::onPlaylistClosed() { closeProducer(); setProfile(Settings.playerProfile()); resetVideoModeMenu(); setAudioChannels(Settings.playerAudioChannels()); setCurrentFile(""); setWindowModified(false); m_undoStack->clear(); MLT.resetURL(); QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(new AutoSaveFile(untitledFileName())); if (!isMultitrackValid()) m_player->enableTab(Player::ProjectTabIndex, false); } void MainWindow::onPlaylistModified() { setWindowModified(true); if (MLT.producer() && playlist() && (void*) MLT.producer()->get_producer() == (void*) playlist()->get_playlist()) m_player->onDurationChanged(); updateMarkers(); m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onMultitrackCreated() { m_player->enableTab(Player::ProjectTabIndex, true); } void MainWindow::onMultitrackClosed() { setAudioChannels(Settings.playerAudioChannels()); closeProducer(); setProfile(Settings.playerProfile()); resetVideoModeMenu(); setCurrentFile(""); setWindowModified(false); m_undoStack->clear(); MLT.resetURL(); QMutexLocker locker(&m_autosaveMutex); m_autosaveFile.reset(new AutoSaveFile(untitledFileName())); if (!playlist() || playlist()->count() == 0) m_player->enableTab(Player::ProjectTabIndex, false); } void MainWindow::onMultitrackModified() { setWindowModified(true); // Reflect this playlist info onto the producer for keyframes dock. if (!m_timelineDock->selection().isEmpty()) { int trackIndex = m_timelineDock->selection().first().y(); int clipIndex = m_timelineDock->selection().first().x(); QScopedPointer<Mlt::ClipInfo> info(m_timelineDock->getClipInfo(trackIndex, clipIndex)); if (info && info->producer && info->producer->is_valid()) { int expected = info->frame_in; QScopedPointer<Mlt::ClipInfo> info2(m_timelineDock->getClipInfo(trackIndex, clipIndex - 1)); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition left of the clip. expected -= info2->frame_count; info->producer->set(kPlaylistStartProperty, info2->start); } else { info->producer->set(kPlaylistStartProperty, info->start); } if (expected != info->producer->get_int(kFilterInProperty)) { int delta = expected - info->producer->get_int(kFilterInProperty); info->producer->set(kFilterInProperty, expected); emit m_filtersDock->producerInChanged(delta); } expected = info->frame_out; info2.reset(m_timelineDock->getClipInfo(trackIndex, clipIndex + 1)); if (info2 && info2->producer && info2->producer->is_valid() && info2->producer->get(kShotcutTransitionProperty)) { // Factor in a transition right of the clip. expected += info2->frame_count; } if (expected != info->producer->get_int(kFilterOutProperty)) { int delta = expected - info->producer->get_int(kFilterOutProperty); info->producer->set(kFilterOutProperty, expected); emit m_filtersDock->producerOutChanged(delta); } } } } void MainWindow::onMultitrackDurationChanged() { if (MLT.producer() && (void*) MLT.producer()->get_producer() == (void*) multitrack()->get_producer()) m_player->onDurationChanged(); } void MainWindow::onCutModified() { if (!playlist() && !multitrack()) { setWindowModified(true); updateAutoSave(); } if (playlist()) m_playlistDock->setUpdateButtonEnabled(true); } void MainWindow::onProducerModified() { setWindowModified(true); updateAutoSave(); } void MainWindow::onFilterModelChanged() { MLT.refreshConsumer(); setWindowModified(true); updateAutoSave(); if (playlist()) m_playlistDock->setUpdateButtonEnabled(true); } void MainWindow::updateMarkers() { if (playlist() && MLT.isPlaylist()) { QList<int> markers; int n = playlist()->count(); for (int i = 0; i < n; i++) markers.append(playlist()->clip_start(i)); m_player->setMarkers(markers); } } void MainWindow::updateThumbnails() { if (Settings.playlistThumbnails() != "hidden") m_playlistDock->model()->refreshThumbnails(); } void MainWindow::on_actionUndo_triggered() { TimelineSelectionBlocker blocker(*m_timelineDock); m_undoStack->undo(); } void MainWindow::on_actionRedo_triggered() { TimelineSelectionBlocker blocker(*m_timelineDock); m_undoStack->redo(); } void MainWindow::on_actionFAQ_triggered() { QDesktopServices::openUrl(QUrl("https://www.shotcut.org/FAQ/")); } void MainWindow::on_actionForum_triggered() { QDesktopServices::openUrl(QUrl("https://forum.shotcut.org/")); } bool MainWindow::saveXML(const QString &filename, bool withRelativePaths) { bool result; if (m_timelineDock->model()->rowCount() > 0) { result = MLT.saveXML(filename, multitrack(), withRelativePaths); } else if (m_playlistDock->model()->rowCount() > 0) { int in = MLT.producer()->get_in(); int out = MLT.producer()->get_out(); MLT.producer()->set_in_and_out(0, MLT.producer()->get_length() - 1); result = MLT.saveXML(filename, playlist(), withRelativePaths); MLT.producer()->set_in_and_out(in, out); } else if (MLT.producer()) { result = MLT.saveXML(filename, (MLT.isMultitrack() || MLT.isPlaylist())? MLT.savedProducer() : 0, withRelativePaths); } else { // Save an empty playlist, which is accepted by both MLT and Shotcut. Mlt::Playlist playlist(MLT.profile()); result = MLT.saveXML(filename, &playlist, withRelativePaths); } return result; } void MainWindow::changeTheme(const QString &theme) { LOG_DEBUG() << "begin"; if (theme == "dark") { QApplication::setStyle("Fusion"); QPalette palette; palette.setColor(QPalette::Window, QColor(50,50,50)); palette.setColor(QPalette::WindowText, QColor(220,220,220)); palette.setColor(QPalette::Base, QColor(30,30,30)); palette.setColor(QPalette::AlternateBase, QColor(40,40,40)); palette.setColor(QPalette::Highlight, QColor(23,92,118)); palette.setColor(QPalette::HighlightedText, Qt::white); palette.setColor(QPalette::ToolTipBase, palette.color(QPalette::Highlight)); palette.setColor(QPalette::ToolTipText, palette.color(QPalette::WindowText)); palette.setColor(QPalette::Text, palette.color(QPalette::WindowText)); palette.setColor(QPalette::BrightText, Qt::red); palette.setColor(QPalette::Button, palette.color(QPalette::Window)); palette.setColor(QPalette::ButtonText, palette.color(QPalette::WindowText)); palette.setColor(QPalette::Link, palette.color(QPalette::Highlight).lighter()); palette.setColor(QPalette::LinkVisited, palette.color(QPalette::Highlight)); palette.setColor(QPalette::Disabled, QPalette::Text, Qt::darkGray); palette.setColor(QPalette::Disabled, QPalette::ButtonText, Qt::darkGray); QApplication::setPalette(palette); QIcon::setThemeName("dark"); } else if (theme == "light") { QStyle* style = QStyleFactory::create("Fusion"); QApplication::setStyle(style); QApplication::setPalette(style->standardPalette()); QIcon::setThemeName("light"); } else { QApplication::setStyle(qApp->property("system-style").toString()); QIcon::setThemeName("oxygen"); } emit QmlApplication::singleton().paletteChanged(); LOG_DEBUG() << "end"; } Mlt::Playlist* MainWindow::playlist() const { return m_playlistDock->model()->playlist(); } bool MainWindow::isPlaylistValid() const { return m_playlistDock->model()->playlist() && m_playlistDock->model()->rowCount() > 0; } Mlt::Producer *MainWindow::multitrack() const { return m_timelineDock->model()->tractor(); } bool MainWindow::isMultitrackValid() const { return m_timelineDock->model()->tractor() && !m_timelineDock->model()->trackList().empty(); } QWidget *MainWindow::loadProducerWidget(Mlt::Producer* producer) { QWidget* w = 0; QScrollArea* scrollArea = (QScrollArea*) m_propertiesDock->widget(); if (!producer || !producer->is_valid()) { if (scrollArea->widget()) scrollArea->widget()->deleteLater(); return w; } else { scrollArea->show(); } QString service(producer->get("mlt_service")); QString resource = QString::fromUtf8(producer->get("resource")); QString shotcutProducer(producer->get(kShotcutProducerProperty)); if (resource.startsWith("video4linux2:") || QString::fromUtf8(producer->get("resource1")).startsWith("video4linux2:")) w = new Video4LinuxWidget(this); else if (resource.startsWith("pulse:")) w = new PulseAudioWidget(this); else if (resource.startsWith("jack:")) w = new JackProducerWidget(this); else if (resource.startsWith("alsa:")) w = new AlsaWidget(this); else if (resource.startsWith("dshow:") || QString::fromUtf8(producer->get("resource1")).startsWith("dshow:")) w = new DirectShowVideoWidget(this); else if (resource.startsWith("avfoundation:")) w = new AvfoundationProducerWidget(this); else if (resource.startsWith("x11grab:")) w = new X11grabWidget(this); else if (resource.startsWith("gdigrab:")) w = new GDIgrabWidget(this); else if (service.startsWith("avformat") || shotcutProducer == "avformat") w = new AvformatProducerWidget(this); else if (MLT.isImageProducer(producer)) { w = new ImageProducerWidget(this); connect(m_player, SIGNAL(outChanged(int)), w, SLOT(updateDuration())); } else if (service == "decklink" || resource.contains("decklink")) w = new DecklinkProducerWidget(this); else if (service == "color") w = new ColorProducerWidget(this); else if (service == "noise") w = new NoiseWidget(this); else if (service == "frei0r.ising0r") w = new IsingWidget(this); else if (service == "frei0r.lissajous0r") w = new LissajousWidget(this); else if (service == "frei0r.plasma") w = new PlasmaWidget(this); else if (service == "frei0r.test_pat_B") w = new ColorBarsWidget(this); else if (service == "webvfx") w = new WebvfxProducer(this); else if (service == "tone") w = new ToneProducerWidget(this); else if (service == "count") w = new CountProducerWidget(this); else if (service == "blipflash") w = new BlipProducerWidget(this); else if (producer->parent().get(kShotcutTransitionProperty)) { w = new LumaMixTransition(producer->parent(), this); scrollArea->setWidget(w); if (-1 != w->metaObject()->indexOfSignal("modified()")) connect(w, SIGNAL(modified()), SLOT(onProducerModified())); return w; } else if (playlist_type == producer->type()) { int trackIndex = m_timelineDock->currentTrack(); bool isBottomVideo = m_timelineDock->model()->data(m_timelineDock->model()->index(trackIndex), MultitrackModel::IsBottomVideoRole).toBool(); if (!isBottomVideo) { w = new TrackPropertiesWidget(*producer, this); scrollArea->setWidget(w); return w; } } else if (tractor_type == producer->type()) { w = new TimelinePropertiesWidget(*producer, this); scrollArea->setWidget(w); return w; } if (w) { dynamic_cast<AbstractProducerWidget*>(w)->setProducer(producer); if (-1 != w->metaObject()->indexOfSignal("producerChanged(Mlt::Producer*)")) { connect(w, SIGNAL(producerChanged(Mlt::Producer*)), SLOT(onProducerChanged())); connect(w, SIGNAL(producerChanged(Mlt::Producer*)), m_filterController, SLOT(setProducer(Mlt::Producer*))); connect(w, SIGNAL(producerChanged(Mlt::Producer*)), m_playlistDock, SLOT(onProducerChanged(Mlt::Producer*))); if (producer->get(kMultitrackItemProperty)) connect(w, SIGNAL(producerChanged(Mlt::Producer*)), m_timelineDock, SLOT(onProducerChanged(Mlt::Producer*))); } if (-1 != w->metaObject()->indexOfSignal("modified()")) { connect(w, SIGNAL(modified()), SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_playlistDock, SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_timelineDock, SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_keyframesDock, SLOT(onProducerModified())); connect(w, SIGNAL(modified()), m_filterController, SLOT(onProducerChanged())); } if (-1 != w->metaObject()->indexOfSlot("updateDuration()")) { connect(m_timelineDock, SIGNAL(durationChanged()), w, SLOT(updateDuration())); } if (-1 != w->metaObject()->indexOfSlot("rename()")) { connect(this, SIGNAL(renameRequested()), w, SLOT(rename())); } scrollArea->setWidget(w); onProducerChanged(); } else if (scrollArea->widget()) { scrollArea->widget()->deleteLater(); } return w; } void MainWindow::on_actionEnter_Full_Screen_triggered() { #ifdef Q_OS_WIN bool isFull = isMaximized(); #else bool isFull = isFullScreen(); #endif if (isFull) { showNormal(); ui->actionEnter_Full_Screen->setText(tr("Enter Full Screen")); } else { #ifdef Q_OS_WIN showMaximized(); #else showFullScreen(); #endif ui->actionEnter_Full_Screen->setText(tr("Enter Full Screen")); } } void MainWindow::onGpuNotSupported() { Settings.setPlayerGPU(false); if (ui->actionGPU) { ui->actionGPU->setChecked(false); ui->actionGPU->setDisabled(true); } LOG_WARNING() << ""; QMessageBox::critical(this, qApp->applicationName(), tr("GPU effects are not supported")); } void MainWindow::editHTML(const QString &fileName) { bool isNew = !m_htmlEditor; if (isNew) { m_htmlEditor.reset(new HtmlEditor); m_htmlEditor->setWindowIcon(windowIcon()); } m_htmlEditor->load(fileName); m_htmlEditor->show(); m_htmlEditor->raise(); bool isExternal = false; int screen = Settings.playerExternal().toInt(&isExternal); isExternal = isExternal && (screen != QApplication::desktop()->screenNumber(this)); if (!isExternal) { if (Settings.playerZoom() >= 1.0f) { m_htmlEditor->changeZoom(100 * m_player->videoSize().width() / MLT.profile().width()); m_htmlEditor->resizeWebView(m_player->videoSize().width(), m_player->videoSize().height()); } else { m_htmlEditor->changeZoom(100 * MLT.displayWidth() / MLT.profile().width()); m_htmlEditor->resizeWebView(MLT.displayWidth(), MLT.displayHeight()); } } else { m_htmlEditor->changeZoom(100); } if (isNew) { // Center the new window over the main window. QPoint point = pos(); QPoint halfSize(width(), height()); halfSize /= 2; point += halfSize; halfSize = QPoint(m_htmlEditor->width(), m_htmlEditor->height()); halfSize /= 2; point -= halfSize; m_htmlEditor->move(point); } } void MainWindow::stepLeftOneFrame() { m_player->seek(m_player->position() - 1); } void MainWindow::stepRightOneFrame() { m_player->seek(m_player->position() + 1); } void MainWindow::stepLeftOneSecond() { stepLeftBySeconds(-1); } void MainWindow::stepRightOneSecond() { stepLeftBySeconds(1); } void MainWindow::setInToCurrent(bool ripple) { if (m_player->tabIndex() == Player::ProjectTabIndex && isMultitrackValid()) { m_timelineDock->trimClipAtPlayhead(TimelineDock::TrimInPoint, ripple); } else if (MLT.isSeekable() && MLT.isClip()) { m_player->setIn(m_player->position()); int delta = m_player->position() - MLT.producer()->get_in(); emit m_player->inChanged(delta); } } void MainWindow::setOutToCurrent(bool ripple) { if (m_player->tabIndex() == Player::ProjectTabIndex && isMultitrackValid()) { m_timelineDock->trimClipAtPlayhead(TimelineDock::TrimOutPoint, ripple); } else if (MLT.isSeekable() && MLT.isClip()) { m_player->setOut(m_player->position()); int delta = m_player->position() - MLT.producer()->get_out(); emit m_player->outChanged(delta); } } void MainWindow::onShuttle(float x) { if (x == 0) { m_player->pause(); } else if (x > 0) { m_player->play(10.0 * x); } else { m_player->play(20.0 * x); } } void MainWindow::showUpgradePrompt() { if (Settings.checkUpgradeAutomatic()) { showStatusMessage("Checking for upgrade..."); QNetworkRequest request(QUrl("https://check.shotcut.org/version.json")); QSslConfiguration sslConfig = request.sslConfiguration(); sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); request.setSslConfiguration(sslConfig); m_network.get(request); } else { m_network.setStrictTransportSecurityEnabled(false); QAction* action = new QAction(tr("Click here to check for a new version of Shotcut."), 0); connect(action, SIGNAL(triggered(bool)), SLOT(on_actionUpgrade_triggered())); showStatusMessage(action, 15 /* seconds */); } } void MainWindow::on_actionRealtime_triggered(bool checked) { Settings.setPlayerRealtime(checked); if (Settings.playerGPU()) MLT.pause(); if (MLT.consumer()) { MLT.restart(); } } void MainWindow::on_actionProgressive_triggered(bool checked) { MLT.videoWidget()->setProperty("progressive", checked); if (Settings.playerGPU()) MLT.pause(); if (MLT.consumer()) { MLT.profile().set_progressive(checked); MLT.updatePreviewProfile(); MLT.restart(); } Settings.setPlayerProgressive(checked); } void MainWindow::changeAudioChannels(bool checked, int channels) { if( checked ) { Settings.setPlayerAudioChannels(channels); setAudioChannels(Settings.playerAudioChannels()); } } void MainWindow::on_actionChannels1_triggered(bool checked) { changeAudioChannels(checked, 1); } void MainWindow::on_actionChannels2_triggered(bool checked) { changeAudioChannels(checked, 2); } void MainWindow::on_actionChannels6_triggered(bool checked) { changeAudioChannels(checked, 6); } void MainWindow::changeDeinterlacer(bool checked, const char* method) { if (checked) { MLT.videoWidget()->setProperty("deinterlace_method", method); if (MLT.consumer()) { MLT.consumer()->set("deinterlace_method", method); MLT.refreshConsumer(); } } Settings.setPlayerDeinterlacer(method); } void MainWindow::on_actionOneField_triggered(bool checked) { changeDeinterlacer(checked, "onefield"); } void MainWindow::on_actionLinearBlend_triggered(bool checked) { changeDeinterlacer(checked, "linearblend"); } void MainWindow::on_actionYadifTemporal_triggered(bool checked) { changeDeinterlacer(checked, "yadif-nospatial"); } void MainWindow::on_actionYadifSpatial_triggered(bool checked) { changeDeinterlacer(checked, "yadif"); } void MainWindow::changeInterpolation(bool checked, const char* method) { if (checked) { MLT.videoWidget()->setProperty("rescale", method); if (MLT.consumer()) { MLT.consumer()->set("rescale", method); MLT.refreshConsumer(); } } Settings.setPlayerInterpolation(method); } void MainWindow::processMultipleFiles() { if (m_multipleFiles.length() <= 0) return; QStringList multipleFiles = m_multipleFiles; m_multipleFiles.clear(); int count = multipleFiles.length(); if (count > 1) { LongUiTask longTask(tr("Open Files")); m_playlistDock->show(); m_playlistDock->raise(); for (int i = 0; i < count; i++) { QString filename = multipleFiles.takeFirst(); LOG_DEBUG() << filename; longTask.reportProgress(QFileInfo(filename).fileName(), i, count); Mlt::Producer p(MLT.profile(), filename.toUtf8().constData()); if (p.is_valid()) { // Convert avformat to avformat-novalidate so that XML loads faster. if (!qstrcmp(p.get("mlt_service"), "avformat")) { p.set("mlt_service", "avformat-novalidate"); p.set("mute_on_pause", 0); } if (QDir::toNativeSeparators(filename) == QDir::toNativeSeparators(MAIN.fileName())) { MAIN.showStatusMessage(QObject::tr("You cannot add a project to itself!")); continue; } MLT.setImageDurationFromDefault(&p); MLT.lockCreationTime(&p); p.get_length_time(mlt_time_clock); Util::getHash(p); ProxyManager::generateIfNotExists(p); undoStack()->push(new Playlist::AppendCommand(*m_playlistDock->model(), MLT.XML(&p), false)); m_recentDock->add(filename.toUtf8().constData()); } } emit m_playlistDock->model()->modified(); } if (m_isPlaylistLoaded && Settings.playerGPU()) { updateThumbnails(); m_isPlaylistLoaded = false; } } void MainWindow::onLanguageTriggered(QAction* action) { Settings.setLanguage(action->data().toString()); QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart Shotcut to switch to the new language.\n" "Do you want to restart now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } } void MainWindow::on_actionNearest_triggered(bool checked) { changeInterpolation(checked, "nearest"); } void MainWindow::on_actionBilinear_triggered(bool checked) { changeInterpolation(checked, "bilinear"); } void MainWindow::on_actionBicubic_triggered(bool checked) { changeInterpolation(checked, "bicubic"); } void MainWindow::on_actionHyper_triggered(bool checked) { changeInterpolation(checked, "hyper"); } void MainWindow::on_actionJack_triggered(bool checked) { Settings.setPlayerJACK(checked); if (!MLT.enableJack(checked)) { if (ui->actionJack) ui->actionJack->setChecked(false); Settings.setPlayerJACK(false); QMessageBox::warning(this, qApp->applicationName(), tr("Failed to connect to JACK.\nPlease verify that JACK is installed and running.")); } } void MainWindow::on_actionGPU_triggered(bool checked) { if (checked) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("GPU effects are experimental and may cause instability on some systems. " "Some CPU effects are incompatible with GPU effects and will be disabled. " "A project created with GPU effects can not be converted to a CPU only project later." "\n\n" "Do you want to enable GPU effects and restart Shotcut?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } else { ui->actionGPU->setChecked(false); } } else { QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("Shotcut must restart to disable GPU effects." "\n\n" "Disable GPU effects and restart?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } else { ui->actionGPU->setChecked(true); } } } void MainWindow::onExternalTriggered(QAction *action) { LOG_DEBUG() << action->data().toString(); bool isExternal = !action->data().toString().isEmpty(); Settings.setPlayerExternal(action->data().toString()); MLT.stop(); bool ok = false; int screen = action->data().toInt(&ok); if (ok || action->data().toString().isEmpty()) { m_player->moveVideoToScreen(ok? screen : -2); isExternal = false; MLT.videoWidget()->setProperty("mlt_service", QVariant()); } else { m_player->moveVideoToScreen(-2); MLT.videoWidget()->setProperty("mlt_service", action->data()); } QString profile = Settings.playerProfile(); // Automatic not permitted for SDI/HDMI if (isExternal && profile.isEmpty()) { profile = "atsc_720p_50"; Settings.setPlayerProfile(profile); setProfile(profile); MLT.restart(); foreach (QAction* a, m_profileGroup->actions()) { if (a->data() == profile) { a->setChecked(true); break; } } } else { MLT.consumerChanged(); } // Automatic not permitted for SDI/HDMI m_profileGroup->actions().at(0)->setEnabled(!isExternal); // Disable progressive option when SDI/HDMI ui->actionProgressive->setEnabled(!isExternal); bool isProgressive = isExternal ? MLT.profile().progressive() : ui->actionProgressive->isChecked(); MLT.videoWidget()->setProperty("progressive", isProgressive); if (MLT.consumer()) { MLT.consumer()->set("progressive", isProgressive); MLT.restart(); } if (m_keyerMenu) m_keyerMenu->setEnabled(action->data().toString().startsWith("decklink")); #if LIBMLT_VERSION_INT >= MLT_VERSION_PREVIEW_SCALE // Preview scaling not permitted for SDI/HDMI if (isExternal) { setPreviewScale(0); m_previewScaleGroup->setEnabled(false); } else { setPreviewScale(Settings.playerPreviewScale()); m_previewScaleGroup->setEnabled(true); } #endif } void MainWindow::onKeyerTriggered(QAction *action) { LOG_DEBUG() << action->data().toString(); MLT.videoWidget()->setProperty("keyer", action->data()); MLT.consumerChanged(); Settings.setPlayerKeyerMode(action->data().toInt()); } void MainWindow::onProfileTriggered(QAction *action) { Settings.setPlayerProfile(action->data().toString()); if (MLT.producer() && MLT.producer()->is_valid()) { // Save the XML to get correct in/out points before profile is changed. QString xml = MLT.XML(); setProfile(action->data().toString()); MLT.restart(xml); onProducerOpened(false); } else { setProfile(action->data().toString()); } } void MainWindow::onProfileChanged() { if (multitrack() && MLT.isMultitrack() && (m_timelineDock->selection().isEmpty() || m_timelineDock->currentTrack() == -1)) { emit m_timelineDock->selected(multitrack()); } } void MainWindow::on_actionAddCustomProfile_triggered() { QString xml; if (MLT.producer() && MLT.producer()->is_valid()) { // Save the XML to get correct in/out points before profile is changed. xml = MLT.XML(); } CustomProfileDialog dialog(this); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QDialog::Accepted) { QString name = dialog.profileName(); if (!name.isEmpty()) { addCustomProfile(name, customProfileMenu(), actionProfileRemove(), profileGroup()); } else if (m_profileGroup->checkedAction()) { m_profileGroup->checkedAction()->setChecked(false); } // Use the new profile. emit profileChanged(); if (!xml.isEmpty()) { MLT.restart(xml); onProducerOpened(false); } } } void MainWindow::on_actionSystemTheme_triggered() { changeTheme("system"); QApplication::setPalette(QApplication::style()->standardPalette()); Settings.setTheme("system"); } void MainWindow::on_actionFusionDark_triggered() { changeTheme("dark"); Settings.setTheme("dark"); ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); } void MainWindow::on_actionFusionLight_triggered() { changeTheme("light"); Settings.setTheme("light"); ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); } void MainWindow::on_actionTutorials_triggered() { QDesktopServices::openUrl(QUrl("https://www.shotcut.org/tutorials/")); } void MainWindow::on_actionRestoreLayout_triggered() { restoreGeometry(Settings.windowGeometryDefault()); restoreState(Settings.windowStateDefault()); on_actionLayoutTimeline_triggered(); ui->actionShowTitleBars->setChecked(true); on_actionShowTitleBars_triggered(true); ui->actionShowTextUnderIcons->setChecked(true); on_actionShowTextUnderIcons_toggled(true); ui->actionShowSmallIcons->setChecked(false); on_actionShowSmallIcons_toggled(false); } void MainWindow::on_actionShowTitleBars_triggered(bool checked) { QList <QDockWidget *> docks = findChildren<QDockWidget *>(); for (int i = 0; i < docks.count(); i++) { QDockWidget* dock = docks.at(i); if (checked) { dock->setTitleBarWidget(0); } else { if (!dock->isFloating()) { dock->setTitleBarWidget(new QWidget); } } } Settings.setShowTitleBars(checked); } void MainWindow::on_actionShowToolbar_triggered(bool checked) { ui->mainToolBar->setVisible(checked); } void MainWindow::onToolbarVisibilityChanged(bool visible) { ui->actionShowToolbar->setChecked(visible); Settings.setShowToolBar(visible); } void MainWindow::on_menuExternal_aboutToShow() { foreach (QAction* action, m_externalGroup->actions()) { bool ok = false; int i = action->data().toInt(&ok); if (ok) { if (i == QApplication::desktop()->screenNumber(this)) { if (action->isChecked()) { m_externalGroup->actions().first()->setChecked(true); Settings.setPlayerExternal(QString()); } action->setDisabled(true); } else { action->setEnabled(true); } } } } void MainWindow::on_actionUpgrade_triggered() { if (Settings.askUpgradeAutmatic()) { QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Do you want to automatically check for updates in the future?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setCheckBox(new QCheckBox(tr("Do not show this anymore.", "Automatic upgrade check dialog"))); Settings.setCheckUpgradeAutomatic(dialog.exec() == QMessageBox::Yes); if (dialog.checkBox()->isChecked()) Settings.setAskUpgradeAutomatic(false); } showStatusMessage("Checking for upgrade..."); m_network.get(QNetworkRequest(QUrl("http://check.shotcut.org/version.json"))); } void MainWindow::on_actionOpenXML_triggered() { QString path = Settings.openPath(); #ifdef Q_OS_MAC path.append("/*"); #endif QStringList filenames = QFileDialog::getOpenFileNames(this, tr("Open File"), path, tr("MLT XML (*.mlt);;All Files (*)")); if (filenames.length() > 0) { QString url = filenames.first(); MltXmlChecker checker; if (checker.check(url)) { if (!isCompatibleWithGpuMode(checker)) return; isXmlRepaired(checker, url); // Check if the locale usage differs. // Get current locale. QString localeName = QString(::setlocale(MLT_LC_CATEGORY, nullptr)).toUpper(); // Test if it is C or POSIX. bool currentlyUsingLocale = (localeName != "" && localeName != "C" && localeName != "POSIX"); if (currentlyUsingLocale != checker.usesLocale()) { // Show a warning dialog and cancel if requested. QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("The decimal point of the MLT XML file\nyou want to open is incompatible.\n\n" "Do you want to continue to open this MLT XML file?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::No); dialog.setEscapeButton(QMessageBox::No); if (dialog.exec() != QMessageBox::Yes) return; } } Settings.setOpenPath(QFileInfo(url).path()); activateWindow(); if (filenames.length() > 1) m_multipleFiles = filenames; if (!MLT.openXML(url)) { open(MLT.producer()); m_recentDock->add(url); LOG_INFO() << url; } else { showStatusMessage(tr("Failed to open ") + url); emit openFailed(url); } } } void MainWindow::on_actionGammaSRGB_triggered(bool checked) { Q_UNUSED(checked) Settings.setPlayerGamma("iec61966_2_1"); MLT.restart(); MLT.refreshConsumer(); } void MainWindow::on_actionGammaRec709_triggered(bool checked) { Q_UNUSED(checked) Settings.setPlayerGamma("bt709"); MLT.restart(); MLT.refreshConsumer(); } void MainWindow::onFocusChanged(QWidget *, QWidget * ) const { LOG_DEBUG() << "Focuswidget changed"; LOG_DEBUG() << "Current focusWidget:" << QApplication::focusWidget(); LOG_DEBUG() << "Current focusObject:" << QApplication::focusObject(); LOG_DEBUG() << "Current focusWindow:" << QApplication::focusWindow(); } void MainWindow::on_actionScrubAudio_triggered(bool checked) { Settings.setPlayerScrubAudio(checked); } #if !defined(Q_OS_MAC) void MainWindow::onDrawingMethodTriggered(QAction *action) { Settings.setDrawMethod(action->data().toInt()); QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart Shotcut to change the display method.\n" "Do you want to restart now?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } } #endif void MainWindow::on_actionApplicationLog_triggered() { TextViewerDialog dialog(this); QDir dir = Settings.appDataLocation(); QFile logFile(dir.filePath("shotcut-log.txt")); logFile.open(QIODevice::ReadOnly | QIODevice::Text); dialog.setText(logFile.readAll()); logFile.close(); dialog.setWindowTitle(tr("Application Log")); dialog.exec(); } void MainWindow::on_actionClose_triggered() { if (continueModified()) { LOG_DEBUG() << ""; MLT.setProjectFolder(QString()); MLT.stop(); if (multitrack()) m_timelineDock->model()->close(); if (playlist()) m_playlistDock->model()->close(); else onMultitrackClosed(); m_player->enableTab(Player::SourceTabIndex, false); MLT.purgeMemoryPool(); MLT.resetLocale(); } } void MainWindow::onPlayerTabIndexChanged(int index) { if (Player::SourceTabIndex == index) m_timelineDock->saveAndClearSelection(); else m_timelineDock->restoreSelection(); } void MainWindow::onUpgradeCheckFinished(QNetworkReply* reply) { if (!reply->error()) { QByteArray response = reply->readAll(); LOG_DEBUG() << "response: " << response; QJsonDocument json = QJsonDocument::fromJson(response); QString current = qApp->applicationVersion(); if (!json.isNull() && json.object().value("version_string").type() == QJsonValue::String) { QString latest = json.object().value("version_string").toString(); if (current != "adhoc" && QVersionNumber::fromString(current) < QVersionNumber::fromString(latest)) { QAction* action = new QAction(tr("Shotcut version %1 is available! Click here to get it.").arg(latest), 0); connect(action, SIGNAL(triggered(bool)), SLOT(onUpgradeTriggered())); if (!json.object().value("url").isUndefined()) m_upgradeUrl = json.object().value("url").toString(); showStatusMessage(action, 15 /* seconds */); } else { showStatusMessage(tr("You are running the latest version of Shotcut.")); } reply->deleteLater(); return; } else { LOG_WARNING() << "failed to parse version.json"; } } else { LOG_WARNING() << reply->errorString(); } QAction* action = new QAction(tr("Failed to read version.json when checking. Click here to go to the Web site."), 0); connect(action, SIGNAL(triggered(bool)), SLOT(onUpgradeTriggered())); showStatusMessage(action); reply->deleteLater(); } void MainWindow::onUpgradeTriggered() { QDesktopServices::openUrl(QUrl(m_upgradeUrl)); } void MainWindow::onTimelineSelectionChanged() { bool enable = (m_timelineDock->selection().size() > 0); ui->actionCut->setEnabled(enable); ui->actionCopy->setEnabled(enable); } void MainWindow::on_actionCut_triggered() { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->removeSelection(true); } void MainWindow::on_actionCopy_triggered() { m_timelineDock->show(); m_timelineDock->raise(); if (!m_timelineDock->selection().isEmpty()) m_timelineDock->copyClip(m_timelineDock->selection().first().y(), m_timelineDock->selection().first().x()); } void MainWindow::on_actionPaste_triggered() { m_timelineDock->show(); m_timelineDock->raise(); m_timelineDock->insert(-1); } void MainWindow::onClipCopied() { m_player->enableTab(Player::SourceTabIndex); } void MainWindow::on_actionExportEDL_triggered() { // Dialog to get export file name. QString path = Settings.savePath(); QString caption = tr("Export EDL"); QString saveFileName = QFileDialog::getSaveFileName(this, caption, path, tr("EDL (*.edl);;All Files (*)")); if (!saveFileName.isEmpty()) { QFileInfo fi(saveFileName); if (fi.suffix() != "edl") saveFileName += ".edl"; if (Util::warnIfNotWritable(saveFileName, this, caption)) return; // Locate the JavaScript file in the filesystem. QDir qmlDir = QmlUtilities::qmlDir(); qmlDir.cd("export-edl"); QString jsFileName = qmlDir.absoluteFilePath("export-edl.js"); QFile scriptFile(jsFileName); if (scriptFile.open(QIODevice::ReadOnly)) { // Read JavaScript into a string. QTextStream stream(&scriptFile); stream.setCodec("UTF-8"); stream.setAutoDetectUnicode(true); QString contents = stream.readAll(); scriptFile.close(); // Evaluate JavaScript. QJSEngine jsEngine; QJSValue result = jsEngine.evaluate(contents, jsFileName); if (!result.isError()) { // Call the JavaScript main function. QJSValue options = jsEngine.newObject(); options.setProperty("useBaseNameForReelName", true); options.setProperty("useBaseNameForClipComment", true); options.setProperty("channelsAV", "AA/V"); QJSValueList args; args << MLT.XML(0, true, true) << options; result = result.call(args); if (!result.isError()) { // Save the result with the export file name. QFile f(saveFileName); f.open(QIODevice::WriteOnly | QIODevice::Text); f.write(result.toString().toLatin1()); f.close(); } } if (result.isError()) { LOG_ERROR() << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":" << result.toString(); showStatusMessage(tr("A JavaScript error occurred during export.")); } } else { showStatusMessage(tr("Failed to open export-edl.js")); } } } void MainWindow::on_actionExportFrame_triggered() { if (Settings.playerGPU() || Settings.playerPreviewScale()) { Mlt::GLWidget* glw = qobject_cast<Mlt::GLWidget*>(MLT.videoWidget()); connect(glw, SIGNAL(imageReady()), SLOT(onGLWidgetImageReady())); MLT.setPreviewScale(0); glw->requestImage(); MLT.refreshConsumer(); } else { onGLWidgetImageReady(); } } void MainWindow::onGLWidgetImageReady() { Mlt::GLWidget* glw = qobject_cast<Mlt::GLWidget*>(MLT.videoWidget()); QImage image = glw->image(); if (Settings.playerGPU() || Settings.playerPreviewScale()) { disconnect(glw, SIGNAL(imageReady()), this, 0); MLT.setPreviewScale(Settings.playerPreviewScale()); } if (!image.isNull()) { QString path = Settings.savePath(); QString caption = tr("Export Frame"); QString nameFilter = tr("PNG (*.png);;BMP (*.bmp);;JPEG (*.jpg *.jpeg);;PPM (*.ppm);;TIFF (*.tif *.tiff);;WebP (*.webp);;All Files (*)"); QString saveFileName = QFileDialog::getSaveFileName(this, caption, path, nameFilter); if (!saveFileName.isEmpty()) { QFileInfo fi(saveFileName); if (fi.suffix().isEmpty()) saveFileName += ".png"; if (Util::warnIfNotWritable(saveFileName, this, caption)) return; // Convert to square pixels if needed. qreal aspectRatio = (qreal) image.width() / image.height(); if (qFloor(aspectRatio * 1000) != qFloor(MLT.profile().dar() * 1000)) { image = image.scaled(qRound(image.height() * MLT.profile().dar()), image.height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } image.save(saveFileName, Q_NULLPTR, (QFileInfo(saveFileName).suffix() == "webp")? 80 : -1); Settings.setSavePath(fi.path()); m_recentDock->add(saveFileName); } } else { showStatusMessage(tr("Unable to export frame.")); } } void MainWindow::on_actionAppDataSet_triggered() { QMessageBox dialog(QMessageBox::Information, qApp->applicationName(), tr("You must restart Shotcut to change the data directory.\n" "Do you want to continue?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() != QMessageBox::Yes) return; QString dirName = QFileDialog::getExistingDirectory(this, tr("Data Directory"), Settings.appDataLocation()); if (!dirName.isEmpty()) { // Move the data files. QDirIterator it(Settings.appDataLocation()); while (it.hasNext()) { if (!it.filePath().isEmpty() && it.fileName() != "." && it.fileName() != "..") { if (!QFile::exists(dirName + "/" + it.fileName())) { if (it.fileInfo().isDir()) { if (!QFile::rename(it.filePath(), dirName + "/" + it.fileName())) LOG_WARNING() << "Failed to move" << it.filePath() << "to" << dirName + "/" + it.fileName(); } else { if (!QFile::copy(it.filePath(), dirName + "/" + it.fileName())) LOG_WARNING() << "Failed to copy" << it.filePath() << "to" << dirName + "/" + it.fileName(); } } } it.next(); } writeSettings(); Settings.setAppDataLocally(dirName); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } } void MainWindow::on_actionAppDataShow_triggered() { Util::showInFolder(Settings.appDataLocation()); } void MainWindow::on_actionNew_triggered() { on_actionClose_triggered(); } void MainWindow::on_actionKeyboardShortcuts_triggered() { QDesktopServices::openUrl(QUrl("https://www.shotcut.org/howtos/keyboard-shortcuts/")); } void MainWindow::on_actionLayoutPlayer_triggered() { restoreState(Settings.windowStateDefault()); } void MainWindow::on_actionLayoutPlaylist_triggered() { restoreState(Settings.windowStateDefault()); m_recentDock->show(); m_recentDock->raise(); m_playlistDock->show(); m_playlistDock->raise(); } void MainWindow::on_actionLayoutTimeline_triggered() { restoreState(Settings.windowStateDefault()); QDockWidget* audioMeterDock = findChild<QDockWidget*>("AudioPeakMeterDock"); if (audioMeterDock) { audioMeterDock->show(); audioMeterDock->raise(); } m_recentDock->show(); m_recentDock->raise(); m_filtersDock->show(); m_filtersDock->raise(); m_timelineDock->show(); m_timelineDock->raise(); } void MainWindow::on_actionLayoutClip_triggered() { restoreState(Settings.windowStateDefault()); m_recentDock->show(); m_recentDock->raise(); m_filtersDock->show(); m_filtersDock->raise(); } void MainWindow::on_actionLayoutAdd_triggered() { bool ok; QString name = QInputDialog::getText(this, tr("Add Custom Layout"), tr("Name"), QLineEdit::Normal, "", &ok); if (ok && !name.isEmpty()) { if (Settings.setLayout(name, saveGeometry(), saveState())) { Settings.sync(); if (Settings.layouts().size() == 1) { ui->menuLayout->addAction(ui->actionLayoutRemove); ui->menuLayout->addSeparator(); } ui->menuLayout->addAction(addLayout(m_layoutGroup, name)); } } } void MainWindow::onLayoutTriggered(QAction* action) { restoreGeometry(Settings.layoutGeometry(action->text())); restoreState(Settings.layoutState(action->text())); } void MainWindow::on_actionProfileRemove_triggered() { QDir dir(Settings.appDataLocation()); if (dir.cd("profiles")) { // Setup the dialog. QStringList profiles = dir.entryList(QDir::Files | QDir::NoDotAndDotDot | QDir::Readable); ListSelectionDialog dialog(profiles, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setWindowTitle(tr("Remove Video Mode")); // Show the dialog. if (dialog.exec() == QDialog::Accepted) { removeCustomProfiles(dialog.selection(), dir, customProfileMenu(), actionProfileRemove()); } } } void MainWindow::on_actionLayoutRemove_triggered() { // Setup the dialog. ListSelectionDialog dialog(Settings.layouts(), this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setWindowTitle(tr("Remove Layout")); // Show the dialog. if (dialog.exec() == QDialog::Accepted) { foreach(const QString& layout, dialog.selection()) { // Update the configuration. if (Settings.removeLayout(layout)) Settings.sync(); // Locate the menu item. foreach (QAction* action, ui->menuLayout->actions()) { if (action->text() == layout) { // Remove the menu item. delete action; break; } } } // If no more custom layouts. if (Settings.layouts().size() == 0) { // Remove the Remove action and separator. ui->menuLayout->removeAction(ui->actionLayoutRemove); bool isSecondSeparator = false; foreach (QAction* action, ui->menuLayout->actions()) { if (action->isSeparator()) { if (isSecondSeparator) { delete action; break; } else { isSecondSeparator = true; } } } } } } void MainWindow::on_actionOpenOther2_triggered() { ui->actionOpenOther2->menu()->popup(mapToGlobal(ui->mainToolBar->geometry().bottomLeft()) + QPoint(64, 0)); } void MainWindow::onOpenOtherTriggered(QWidget* widget) { QDialog dialog(this); dialog.resize(426, 288); QVBoxLayout vlayout(&dialog); vlayout.addWidget(widget); QDialogButtonBox buttonBox(&dialog); buttonBox.setOrientation(Qt::Horizontal); buttonBox.setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); vlayout.addWidget(&buttonBox); connect(&buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept())); connect(&buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject())); QString name = widget->objectName(); if (name == "NoiseWidget" || dialog.exec() == QDialog::Accepted) { open(dynamic_cast<AbstractProducerWidget*>(widget)->newProducer(MLT.profile())); if (name == "TextProducerWidget") { m_filtersDock->show(); m_filtersDock->raise(); } else { m_propertiesDock->show(); m_propertiesDock->raise(); } } delete widget; } void MainWindow::onOpenOtherTriggered() { if (sender()->objectName() == "color") onOpenOtherTriggered(new ColorProducerWidget(this)); else if (sender()->objectName() == "text") onOpenOtherTriggered(new TextProducerWidget(this)); else if (sender()->objectName() == "noise") onOpenOtherTriggered(new NoiseWidget(this)); else if (sender()->objectName() == "ising0r") onOpenOtherTriggered(new IsingWidget(this)); else if (sender()->objectName() == "lissajous0r") onOpenOtherTriggered(new LissajousWidget(this)); else if (sender()->objectName() == "plasma") onOpenOtherTriggered(new PlasmaWidget(this)); else if (sender()->objectName() == "test_pat_B") onOpenOtherTriggered(new ColorBarsWidget(this)); else if (sender()->objectName() == "tone") onOpenOtherTriggered(new ToneProducerWidget(this)); else if (sender()->objectName() == "count") onOpenOtherTriggered(new CountProducerWidget(this)); else if (sender()->objectName() == "blipflash") onOpenOtherTriggered(new BlipProducerWidget(this)); else if (sender()->objectName() == "v4l2") onOpenOtherTriggered(new Video4LinuxWidget(this)); else if (sender()->objectName() == "pulse") onOpenOtherTriggered(new PulseAudioWidget(this)); else if (sender()->objectName() == "jack") onOpenOtherTriggered(new JackProducerWidget(this)); else if (sender()->objectName() == "alsa") onOpenOtherTriggered(new AlsaWidget(this)); #if defined(Q_OS_MAC) else if (sender()->objectName() == "device") onOpenOtherTriggered(new AvfoundationProducerWidget(this)); #elif defined(Q_OS_WIN) else if (sender()->objectName() == "device") onOpenOtherTriggered(new DirectShowVideoWidget(this)); #endif else if (sender()->objectName() == "decklink") onOpenOtherTriggered(new DecklinkProducerWidget(this)); } void MainWindow::on_actionClearRecentOnExit_toggled(bool arg1) { Settings.setClearRecent(arg1); if (arg1) Settings.setRecent(QStringList()); } void MainWindow::onSceneGraphInitialized() { if (Settings.playerGPU() && Settings.playerWarnGPU()) { QMessageBox dialog(QMessageBox::Warning, qApp->applicationName(), tr("GPU effects are EXPERIMENTAL, UNSTABLE and UNSUPPORTED! Unsupported means do not report bugs about it.\n\n" "Do you want to disable GPU effects and restart Shotcut?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); dialog.setWindowModality(QmlApplication::dialogModality()); if (dialog.exec() == QMessageBox::Yes) { ui->actionGPU->setChecked(false); m_exitCode = EXIT_RESTART; QApplication::closeAllWindows(); } else { ui->actionGPU->setVisible(true); } } else if (Settings.playerGPU()) { ui->actionGPU->setVisible(true); } } void MainWindow::on_actionShowTextUnderIcons_toggled(bool b) { ui->mainToolBar->setToolButtonStyle(b? Qt::ToolButtonTextUnderIcon : Qt::ToolButtonIconOnly); Settings.setTextUnderIcons(b); } void MainWindow::on_actionShowSmallIcons_toggled(bool b) { ui->mainToolBar->setIconSize(b? QSize(16, 16) : QSize()); Settings.setSmallIcons(b); } void MainWindow::onPlaylistInChanged(int in) { m_player->blockSignals(true); m_player->setIn(in); m_player->blockSignals(false); } void MainWindow::onPlaylistOutChanged(int out) { m_player->blockSignals(true); m_player->setOut(out); m_player->blockSignals(false); } void MainWindow::on_actionPreviewNone_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(0); setPreviewScale(0); m_player->showIdleStatus(); } } void MainWindow::on_actionPreview360_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(360); setPreviewScale(360); m_player->showIdleStatus(); } } void MainWindow::on_actionPreview540_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(540); setPreviewScale(540); m_player->showIdleStatus(); } } void MainWindow::on_actionPreview720_triggered(bool checked) { if (checked) { Settings.setPlayerPreviewScale(720); setPreviewScale(720); m_player->showIdleStatus(); } } QUuid MainWindow::timelineClipUuid(int trackIndex, int clipIndex) { QScopedPointer<Mlt::ClipInfo> info(m_timelineDock->getClipInfo(trackIndex, clipIndex)); if (info && info->cut && info->cut->is_valid()) return MLT.ensureHasUuid(*info->cut); return QUuid(); } void MainWindow::replaceInTimeline(const QUuid& uuid, Mlt::Producer& producer) { int trackIndex = -1; int clipIndex = -1; // lookup the current track and clip index by UUID QScopedPointer<Mlt::ClipInfo> info(MAIN.timelineClipInfoByUuid(uuid, trackIndex, clipIndex)); if (trackIndex >= 0 && clipIndex >= 0) { Util::getHash(producer); Util::applyCustomProperties(producer, *info->producer, producer.get_in(), producer.get_out()); m_timelineDock->replace(trackIndex, clipIndex, MLT.XML(&producer)); } } Mlt::ClipInfo* MainWindow::timelineClipInfoByUuid(const QUuid& uuid, int& trackIndex, int& clipIndex) { return m_timelineDock->model()->findClipByUuid(uuid, trackIndex, clipIndex); } void MainWindow::replaceAllByHash(const QString& hash, Mlt::Producer& producer, bool isProxy) { Util::getHash(producer); if (!isProxy) m_recentDock->add(producer.get("resource")); if (MLT.isClip() && MLT.producer() && Util::getHash(*MLT.producer()) == hash) { Util::applyCustomProperties(producer, *MLT.producer(), MLT.producer()->get_in(), MLT.producer()->get_out()); MLT.copyFilters(*MLT.producer(), producer); MLT.close(); m_player->setPauseAfterOpen(true); open(new Mlt::Producer(MLT.profile(), "xml-string", MLT.XML(&producer).toUtf8().constData())); } else if (MLT.savedProducer() && Util::getHash(*MLT.savedProducer()) == hash) { Util::applyCustomProperties(producer, *MLT.savedProducer(), MLT.savedProducer()->get_in(), MLT.savedProducer()->get_out()); MLT.copyFilters(*MLT.savedProducer(), producer); MLT.setSavedProducer(&producer); } if (playlist()) { if (isProxy) { m_playlistDock->replaceClipsWithHash(hash, producer); } else { // Append to playlist producer.set(kPlaylistIndexProperty, playlist()->count()); MAIN.undoStack()->push( new Playlist::AppendCommand(*m_playlistDock->model(), MLT.XML(&producer))); } } if (isMultitrackValid()) { m_timelineDock->replaceClipsWithHash(hash, producer); } } void MainWindow::on_actionTopics_triggered() { QDesktopServices::openUrl(QUrl("https://www.shotcut.org/howtos/")); } void MainWindow::on_actionSync_triggered() { auto dialog = new SystemSyncDialog(this); dialog->show(); dialog->raise(); dialog->activateWindow(); } void MainWindow::on_actionUseProxy_triggered(bool checked) { if (MLT.producer()) { QDir dir(m_currentFile.isEmpty()? QDir::tempPath() : QFileInfo(m_currentFile).dir()); QScopedPointer<QTemporaryFile> tmp(new QTemporaryFile(dir.filePath("shotcut-XXXXXX.mlt"))); tmp->open(); tmp->close(); QString fileName = tmp->fileName(); tmp->remove(); tmp.reset(); LOG_DEBUG() << fileName; if (saveXML(fileName)) { MltXmlChecker checker; Settings.setProxyEnabled(checked); checker.check(fileName); if (!isXmlRepaired(checker, fileName)) { QFile::remove(fileName); return; } if (checker.isUpdated()) { QFile::remove(fileName); fileName = checker.tempFileName(); } // Open the temporary file int result = 0; { LongUiTask longTask(checked? tr("Turn Proxy On") : tr("Turn Proxy Off")); QFuture<int> future = QtConcurrent::run([=]() { return MLT.open(QDir::fromNativeSeparators(fileName), QDir::fromNativeSeparators(m_currentFile)); }); result = longTask.wait<int>(tr("Converting"), future); } if (!result) { auto position = m_player->position(); m_undoStack->clear(); m_player->stop(); m_player->setPauseAfterOpen(true); open(MLT.producer()); MLT.seek(m_player->position()); m_player->seek(position); if (checked && (isPlaylistValid() || isMultitrackValid())) { // Prompt user if they want to create missing proxies QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Do you want to create missing proxies for every file in this project?\n\n" "You must reopen your project after all proxy jobs are finished."), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); if (dialog.exec() == QMessageBox::Yes) { Mlt::Producer producer(playlist()); if (producer.is_valid()) { ProxyManager::generateIfNotExistsAll(producer); } producer = multitrack(); if (producer.is_valid()) { ProxyManager::generateIfNotExistsAll(producer); } } } } else if (fileName != untitledFileName()) { showStatusMessage(tr("Failed to open ") + fileName); emit openFailed(fileName); } } else { ui->actionUseProxy->setChecked(!checked); showSaveError(); } QFile::remove(fileName); } else { Settings.setProxyEnabled(checked); } m_player->showIdleStatus(); } void MainWindow::on_actionProxyStorageSet_triggered() { // Present folder dialog just like App Data Directory QString dirName = QFileDialog::getExistingDirectory(this, tr("Proxy Folder"), Settings.proxyFolder()); if (!dirName.isEmpty() && dirName != Settings.proxyFolder()) { auto oldFolder = Settings.proxyFolder(); Settings.setProxyFolder(dirName); Settings.sync(); // Get a count for the progress dialog auto oldDir = QDir(oldFolder); auto dirList = oldDir.entryList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot); auto count = dirList.size(); if (count > 0) { // Prompt user if they want to create missing proxies QMessageBox dialog(QMessageBox::Question, qApp->applicationName(), tr("Do you want to move all files from the old folder to the new folder?"), QMessageBox::No | QMessageBox::Yes, this); dialog.setWindowModality(QmlApplication::dialogModality()); dialog.setDefaultButton(QMessageBox::Yes); dialog.setEscapeButton(QMessageBox::No); if (dialog.exec() == QMessageBox::Yes) { // Move the existing files LongUiTask longTask(tr("Moving Files")); int i = 0; for (const auto& fileName : dirList) { if (!fileName.isEmpty() && !QFile::exists(dirName + "/" + fileName)) { LOG_DEBUG() << "moving" << oldDir.filePath(fileName) << "to" << dirName + "/" + fileName; longTask.reportProgress(fileName, i++, count); if (!QFile::rename(oldDir.filePath(fileName), dirName + "/" + fileName)) LOG_WARNING() << "Failed to move" << oldDir.filePath(fileName); } } } } } } void MainWindow::on_actionProxyStorageShow_triggered() { Util::showInFolder(ProxyManager::dir().path()); } void MainWindow::on_actionProxyUseProjectFolder_triggered(bool checked) { Settings.setProxyUseProjectFolder(checked); } void MainWindow::on_actionProxyUseHardware_triggered(bool checked) { if (checked && Settings.encodeHardware().isEmpty()) { if (!m_encodeDock->detectHardwareEncoders()) ui->actionProxyUseHardware->setChecked(false); } Settings.setProxyUseHardware(ui->actionProxyUseHardware->isChecked()); } void MainWindow::on_actionProxyConfigureHardware_triggered() { m_encodeDock->on_hwencodeButton_clicked(); if (Settings.encodeHardware().isEmpty()) { ui->actionProxyUseHardware->setChecked(false); Settings.setProxyUseHardware(false); } }
./CrossVul/dataset_final_sorted/CWE-327/cpp/bad_4277_0
crossvul-cpp_data_good_1336_0
/* signature.c * * Copyright (C) 2006-2019 wolfSSL Inc. * * This file is part of wolfSSL. * * wolfSSL 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. * * wolfSSL 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-1335, USA */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <wolfssl/wolfcrypt/settings.h> #include <wolfssl/wolfcrypt/signature.h> #include <wolfssl/wolfcrypt/error-crypt.h> #include <wolfssl/wolfcrypt/logging.h> #ifndef NO_ASN #include <wolfssl/wolfcrypt/asn.h> #endif #ifdef HAVE_ECC #include <wolfssl/wolfcrypt/ecc.h> #endif #ifndef NO_RSA #include <wolfssl/wolfcrypt/rsa.h> #endif /* If ECC and RSA are disabled then disable signature wrapper */ #if (!defined(HAVE_ECC) || (defined(HAVE_ECC) && !defined(HAVE_ECC_SIGN) \ && !defined(HAVE_ECC_VERIFY))) && defined(NO_RSA) #undef NO_SIG_WRAPPER #define NO_SIG_WRAPPER #endif /* Signature wrapper disabled check */ #ifndef NO_SIG_WRAPPER #if !defined(NO_RSA) && !defined(NO_ASN) static int wc_SignatureDerEncode(enum wc_HashType hash_type, byte* hash_data, word32 hash_len, word32* hash_enc_len) { int ret, oid; ret = wc_HashGetOID(hash_type); if (ret < 0) { return ret; } oid = ret; ret = wc_EncodeSignature(hash_data, hash_data, hash_len, oid); if (ret > 0) { *hash_enc_len = ret; ret = 0; } return ret; } #endif /* !NO_RSA && !NO_ASN */ int wc_SignatureGetSize(enum wc_SignatureType sig_type, const void* key, word32 key_len) { int sig_len = BAD_FUNC_ARG; /* Suppress possible unused args if all signature types are disabled */ (void)key; (void)key_len; switch(sig_type) { case WC_SIGNATURE_TYPE_ECC: #ifdef HAVE_ECC /* Sanity check that void* key is at least ecc_key in size */ if (key_len >= sizeof(ecc_key)) { sig_len = wc_ecc_sig_size((ecc_key*)key); } else { WOLFSSL_MSG("wc_SignatureGetSize: Invalid ECC key size"); } #else sig_len = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_RSA_W_ENC: case WC_SIGNATURE_TYPE_RSA: #ifndef NO_RSA /* Sanity check that void* key is at least RsaKey in size */ if (key_len >= sizeof(RsaKey)) { sig_len = wc_RsaEncryptSize((RsaKey*)key); } else { WOLFSSL_MSG("wc_SignatureGetSize: Invalid RsaKey key size"); } #else sig_len = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_NONE: default: sig_len = BAD_FUNC_ARG; break; } return sig_len; } int wc_SignatureVerifyHash( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* hash_data, word32 hash_len, const byte* sig, word32 sig_len, const void* key, word32 key_len) { int ret; /* Check arguments */ if (hash_data == NULL || hash_len <= 0 || sig == NULL || sig_len <= 0 || key == NULL || key_len <= 0) { return BAD_FUNC_ARG; } /* Validate signature len (1 to max is okay) */ if ((int)sig_len > wc_SignatureGetSize(sig_type, key, key_len)) { WOLFSSL_MSG("wc_SignatureVerify: Invalid sig type/len"); return BAD_FUNC_ARG; } /* Validate hash size */ ret = wc_HashGetDigestSize(hash_type); if (ret < 0) { WOLFSSL_MSG("wc_SignatureVerify: Invalid hash type/len"); return ret; } ret = 0; /* Verify signature using hash */ switch (sig_type) { case WC_SIGNATURE_TYPE_ECC: { #if defined(HAVE_ECC) && defined(HAVE_ECC_VERIFY) int is_valid_sig = 0; /* Perform verification of signature using provided ECC key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((ecc_key*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_ecc_verify_hash(sig, sig_len, hash_data, hash_len, &is_valid_sig, (ecc_key*)key); } while (ret == WC_PENDING_E); if (ret != 0 || is_valid_sig != 1) { ret = SIG_VERIFY_E; } #else ret = SIG_TYPE_E; #endif break; } case WC_SIGNATURE_TYPE_RSA_W_ENC: case WC_SIGNATURE_TYPE_RSA: { #ifndef NO_RSA #if defined(WOLFSSL_CRYPTOCELL) /* the signature must propagate to the cryptocell to get verfied */ ret = wc_RsaSSL_Verify(hash_data, hash_len, (byte*)sig, sig_len, (RsaKey*)key); if (ret != 0) { WOLFSSL_MSG("RSA Signature Verify difference!"); ret = SIG_VERIFY_E; } #else /* WOLFSSL_CRYPTOCELL */ word32 plain_len = hash_len; byte *plain_data; /* Make sure the plain text output is at least key size */ if (plain_len < sig_len) { plain_len = sig_len; } plain_data = (byte*)XMALLOC(plain_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (plain_data) { /* Perform verification of signature using provided RSA key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((RsaKey*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_RsaSSL_Verify(sig, sig_len, plain_data, plain_len, (RsaKey*)key); } while (ret == WC_PENDING_E); if (ret >= 0) { if ((word32)ret == hash_len && XMEMCMP(plain_data, hash_data, hash_len) == 0) { ret = 0; /* Success */ } else { WOLFSSL_MSG("RSA Signature Verify difference!"); ret = SIG_VERIFY_E; } } XFREE(plain_data, NULL, DYNAMIC_TYPE_TMP_BUFFER); } else { ret = MEMORY_E; } #endif /* !WOLFSSL_CRYPTOCELL */ #else ret = SIG_TYPE_E; #endif break; } case WC_SIGNATURE_TYPE_NONE: default: ret = BAD_FUNC_ARG; break; } return ret; } int wc_SignatureVerify( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* data, word32 data_len, const byte* sig, word32 sig_len, const void* key, word32 key_len) { int ret; word32 hash_len, hash_enc_len; #ifdef WOLFSSL_SMALL_STACK byte *hash_data; #else byte hash_data[MAX_DER_DIGEST_SZ]; #endif /* Check arguments */ if (data == NULL || data_len <= 0 || sig == NULL || sig_len <= 0 || key == NULL || key_len <= 0) { return BAD_FUNC_ARG; } /* Validate signature len (1 to max is okay) */ if ((int)sig_len > wc_SignatureGetSize(sig_type, key, key_len)) { WOLFSSL_MSG("wc_SignatureVerify: Invalid sig type/len"); return BAD_FUNC_ARG; } /* Validate hash size */ ret = wc_HashGetDigestSize(hash_type); if (ret < 0) { WOLFSSL_MSG("wc_SignatureVerify: Invalid hash type/len"); return ret; } hash_enc_len = hash_len = ret; #ifndef NO_RSA if (sig_type == WC_SIGNATURE_TYPE_RSA_W_ENC) { /* For RSA with ASN.1 encoding include room */ hash_enc_len += MAX_DER_DIGEST_ASN_SZ; } #endif #ifdef WOLFSSL_SMALL_STACK /* Allocate temporary buffer for hash data */ hash_data = (byte*)XMALLOC(hash_enc_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (hash_data == NULL) { return MEMORY_E; } #endif /* Perform hash of data */ ret = wc_Hash(hash_type, data, data_len, hash_data, hash_len); if (ret == 0) { /* Handle RSA with DER encoding */ if (sig_type == WC_SIGNATURE_TYPE_RSA_W_ENC) { #if defined(NO_RSA) || defined(NO_ASN) ret = SIG_TYPE_E; #else ret = wc_SignatureDerEncode(hash_type, hash_data, hash_len, &hash_enc_len); #endif } if (ret == 0) { /* Verify signature using hash */ ret = wc_SignatureVerifyHash(hash_type, sig_type, hash_data, hash_enc_len, sig, sig_len, key, key_len); } } #ifdef WOLFSSL_SMALL_STACK XFREE(hash_data, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return ret; } int wc_SignatureGenerateHash( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* hash_data, word32 hash_len, byte* sig, word32 *sig_len, const void* key, word32 key_len, WC_RNG* rng) { return wc_SignatureGenerateHash_ex(hash_type, sig_type, hash_data, hash_len, sig, sig_len, key, key_len, rng, 1); } int wc_SignatureGenerateHash_ex( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* hash_data, word32 hash_len, byte* sig, word32 *sig_len, const void* key, word32 key_len, WC_RNG* rng, int verify) { int ret; /* Suppress possible unused arg if all signature types are disabled */ (void)rng; /* Check arguments */ if (hash_data == NULL || hash_len <= 0 || sig == NULL || sig_len == NULL || *sig_len <= 0 || key == NULL || key_len <= 0) { return BAD_FUNC_ARG; } /* Validate signature len (needs to be at least max) */ if ((int)*sig_len < wc_SignatureGetSize(sig_type, key, key_len)) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid sig type/len"); return BAD_FUNC_ARG; } /* Validate hash size */ ret = wc_HashGetDigestSize(hash_type); if (ret < 0) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid hash type/len"); return ret; } ret = 0; /* Create signature using hash as data */ switch (sig_type) { case WC_SIGNATURE_TYPE_ECC: #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN) /* Create signature using provided ECC key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((ecc_key*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_ecc_sign_hash(hash_data, hash_len, sig, sig_len, rng, (ecc_key*)key); } while (ret == WC_PENDING_E); #else ret = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_RSA_W_ENC: case WC_SIGNATURE_TYPE_RSA: #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) /* Create signature using provided RSA key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((RsaKey*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_RsaSSL_Sign(hash_data, hash_len, sig, *sig_len, (RsaKey*)key, rng); } while (ret == WC_PENDING_E); if (ret >= 0) { *sig_len = ret; ret = 0; /* Success */ } #else ret = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_NONE: default: ret = BAD_FUNC_ARG; break; } if (ret == 0 && verify) { ret = wc_SignatureVerifyHash(hash_type, sig_type, hash_data, hash_len, sig, *sig_len, key, key_len); } return ret; } int wc_SignatureGenerate( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* data, word32 data_len, byte* sig, word32 *sig_len, const void* key, word32 key_len, WC_RNG* rng) { return wc_SignatureGenerate_ex(hash_type, sig_type, data, data_len, sig, sig_len, key, key_len, rng, 1); } int wc_SignatureGenerate_ex( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* data, word32 data_len, byte* sig, word32 *sig_len, const void* key, word32 key_len, WC_RNG* rng, int verify) { int ret; word32 hash_len, hash_enc_len; #ifdef WOLFSSL_SMALL_STACK byte *hash_data; #else byte hash_data[MAX_DER_DIGEST_SZ]; #endif /* Check arguments */ if (data == NULL || data_len <= 0 || sig == NULL || sig_len == NULL || *sig_len <= 0 || key == NULL || key_len <= 0) { return BAD_FUNC_ARG; } /* Validate signature len (needs to be at least max) */ if ((int)*sig_len < wc_SignatureGetSize(sig_type, key, key_len)) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid sig type/len"); return BAD_FUNC_ARG; } /* Validate hash size */ ret = wc_HashGetDigestSize(hash_type); if (ret < 0) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid hash type/len"); return ret; } hash_enc_len = hash_len = ret; #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) if (sig_type == WC_SIGNATURE_TYPE_RSA_W_ENC) { /* For RSA with ASN.1 encoding include room */ hash_enc_len += MAX_DER_DIGEST_ASN_SZ; } #endif #ifdef WOLFSSL_SMALL_STACK /* Allocate temporary buffer for hash data */ hash_data = (byte*)XMALLOC(hash_enc_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (hash_data == NULL) { return MEMORY_E; } #endif /* Perform hash of data */ ret = wc_Hash(hash_type, data, data_len, hash_data, hash_len); if (ret == 0) { /* Handle RSA with DER encoding */ if (sig_type == WC_SIGNATURE_TYPE_RSA_W_ENC) { #if defined(NO_RSA) || defined(NO_ASN) || \ defined(WOLFSSL_RSA_PUBLIC_ONLY) ret = SIG_TYPE_E; #else ret = wc_SignatureDerEncode(hash_type, hash_data, hash_len, &hash_enc_len); #endif } if (ret == 0) { /* Generate signature using hash */ ret = wc_SignatureGenerateHash(hash_type, sig_type, hash_data, hash_enc_len, sig, sig_len, key, key_len, rng); } } if (ret == 0 && verify) { ret = wc_SignatureVerifyHash(hash_type, sig_type, hash_data, hash_enc_len, sig, *sig_len, key, key_len); } #ifdef WOLFSSL_SMALL_STACK XFREE(hash_data, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return ret; } #endif /* NO_SIG_WRAPPER */
./CrossVul/dataset_final_sorted/CWE-327/c/good_1336_0
crossvul-cpp_data_bad_1336_0
/* signature.c * * Copyright (C) 2006-2019 wolfSSL Inc. * * This file is part of wolfSSL. * * wolfSSL 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. * * wolfSSL 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-1335, USA */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <wolfssl/wolfcrypt/settings.h> #include <wolfssl/wolfcrypt/signature.h> #include <wolfssl/wolfcrypt/error-crypt.h> #include <wolfssl/wolfcrypt/logging.h> #ifndef NO_ASN #include <wolfssl/wolfcrypt/asn.h> #endif #ifdef HAVE_ECC #include <wolfssl/wolfcrypt/ecc.h> #endif #ifndef NO_RSA #include <wolfssl/wolfcrypt/rsa.h> #endif /* If ECC and RSA are disabled then disable signature wrapper */ #if (!defined(HAVE_ECC) || (defined(HAVE_ECC) && !defined(HAVE_ECC_SIGN) \ && !defined(HAVE_ECC_VERIFY))) && defined(NO_RSA) #undef NO_SIG_WRAPPER #define NO_SIG_WRAPPER #endif /* Signature wrapper disabled check */ #ifndef NO_SIG_WRAPPER #if !defined(NO_RSA) && !defined(NO_ASN) static int wc_SignatureDerEncode(enum wc_HashType hash_type, byte* hash_data, word32 hash_len, word32* hash_enc_len) { int ret, oid; ret = wc_HashGetOID(hash_type); if (ret < 0) { return ret; } oid = ret; ret = wc_EncodeSignature(hash_data, hash_data, hash_len, oid); if (ret > 0) { *hash_enc_len = ret; ret = 0; } return ret; } #endif /* !NO_RSA && !NO_ASN */ int wc_SignatureGetSize(enum wc_SignatureType sig_type, const void* key, word32 key_len) { int sig_len = BAD_FUNC_ARG; /* Suppress possible unused args if all signature types are disabled */ (void)key; (void)key_len; switch(sig_type) { case WC_SIGNATURE_TYPE_ECC: #ifdef HAVE_ECC /* Sanity check that void* key is at least ecc_key in size */ if (key_len >= sizeof(ecc_key)) { sig_len = wc_ecc_sig_size((ecc_key*)key); } else { WOLFSSL_MSG("wc_SignatureGetSize: Invalid ECC key size"); } #else sig_len = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_RSA_W_ENC: case WC_SIGNATURE_TYPE_RSA: #ifndef NO_RSA /* Sanity check that void* key is at least RsaKey in size */ if (key_len >= sizeof(RsaKey)) { sig_len = wc_RsaEncryptSize((RsaKey*)key); } else { WOLFSSL_MSG("wc_SignatureGetSize: Invalid RsaKey key size"); } #else sig_len = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_NONE: default: sig_len = BAD_FUNC_ARG; break; } return sig_len; } int wc_SignatureVerifyHash( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* hash_data, word32 hash_len, const byte* sig, word32 sig_len, const void* key, word32 key_len) { int ret; /* Check arguments */ if (hash_data == NULL || hash_len <= 0 || sig == NULL || sig_len <= 0 || key == NULL || key_len <= 0) { return BAD_FUNC_ARG; } /* Validate signature len (1 to max is okay) */ if ((int)sig_len > wc_SignatureGetSize(sig_type, key, key_len)) { WOLFSSL_MSG("wc_SignatureVerify: Invalid sig type/len"); return BAD_FUNC_ARG; } /* Validate hash size */ ret = wc_HashGetDigestSize(hash_type); if (ret < 0) { WOLFSSL_MSG("wc_SignatureVerify: Invalid hash type/len"); return ret; } ret = 0; /* Verify signature using hash */ switch (sig_type) { case WC_SIGNATURE_TYPE_ECC: { #if defined(HAVE_ECC) && defined(HAVE_ECC_VERIFY) int is_valid_sig = 0; /* Perform verification of signature using provided ECC key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((ecc_key*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_ecc_verify_hash(sig, sig_len, hash_data, hash_len, &is_valid_sig, (ecc_key*)key); } while (ret == WC_PENDING_E); if (ret != 0 || is_valid_sig != 1) { ret = SIG_VERIFY_E; } #else ret = SIG_TYPE_E; #endif break; } case WC_SIGNATURE_TYPE_RSA_W_ENC: case WC_SIGNATURE_TYPE_RSA: { #ifndef NO_RSA #if defined(WOLFSSL_CRYPTOCELL) /* the signature must propagate to the cryptocell to get verfied */ ret = wc_RsaSSL_Verify(hash_data, hash_len, (byte*)sig, sig_len, (RsaKey*)key); if (ret != 0) { WOLFSSL_MSG("RSA Signature Verify difference!"); ret = SIG_VERIFY_E; } #else /* WOLFSSL_CRYPTOCELL */ word32 plain_len = hash_len; byte *plain_data; /* Make sure the plain text output is at least key size */ if (plain_len < sig_len) { plain_len = sig_len; } plain_data = (byte*)XMALLOC(plain_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (plain_data) { /* Perform verification of signature using provided RSA key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((RsaKey*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_RsaSSL_Verify(sig, sig_len, plain_data, plain_len, (RsaKey*)key); } while (ret == WC_PENDING_E); if (ret >= 0) { if ((word32)ret == hash_len && XMEMCMP(plain_data, hash_data, hash_len) == 0) { ret = 0; /* Success */ } else { WOLFSSL_MSG("RSA Signature Verify difference!"); ret = SIG_VERIFY_E; } } XFREE(plain_data, NULL, DYNAMIC_TYPE_TMP_BUFFER); } else { ret = MEMORY_E; } #endif /* !WOLFSSL_CRYPTOCELL */ #else ret = SIG_TYPE_E; #endif break; } case WC_SIGNATURE_TYPE_NONE: default: ret = BAD_FUNC_ARG; break; } return ret; } int wc_SignatureVerify( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* data, word32 data_len, const byte* sig, word32 sig_len, const void* key, word32 key_len) { int ret; word32 hash_len, hash_enc_len; #ifdef WOLFSSL_SMALL_STACK byte *hash_data; #else byte hash_data[MAX_DER_DIGEST_SZ]; #endif /* Check arguments */ if (data == NULL || data_len <= 0 || sig == NULL || sig_len <= 0 || key == NULL || key_len <= 0) { return BAD_FUNC_ARG; } /* Validate signature len (1 to max is okay) */ if ((int)sig_len > wc_SignatureGetSize(sig_type, key, key_len)) { WOLFSSL_MSG("wc_SignatureVerify: Invalid sig type/len"); return BAD_FUNC_ARG; } /* Validate hash size */ ret = wc_HashGetDigestSize(hash_type); if (ret < 0) { WOLFSSL_MSG("wc_SignatureVerify: Invalid hash type/len"); return ret; } hash_enc_len = hash_len = ret; #ifndef NO_RSA if (sig_type == WC_SIGNATURE_TYPE_RSA_W_ENC) { /* For RSA with ASN.1 encoding include room */ hash_enc_len += MAX_DER_DIGEST_ASN_SZ; } #endif #ifdef WOLFSSL_SMALL_STACK /* Allocate temporary buffer for hash data */ hash_data = (byte*)XMALLOC(hash_enc_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (hash_data == NULL) { return MEMORY_E; } #endif /* Perform hash of data */ ret = wc_Hash(hash_type, data, data_len, hash_data, hash_len); if (ret == 0) { /* Handle RSA with DER encoding */ if (sig_type == WC_SIGNATURE_TYPE_RSA_W_ENC) { #if defined(NO_RSA) || defined(NO_ASN) ret = SIG_TYPE_E; #else ret = wc_SignatureDerEncode(hash_type, hash_data, hash_len, &hash_enc_len); #endif } if (ret == 0) { /* Verify signature using hash */ ret = wc_SignatureVerifyHash(hash_type, sig_type, hash_data, hash_enc_len, sig, sig_len, key, key_len); } } #ifdef WOLFSSL_SMALL_STACK XFREE(hash_data, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return ret; } int wc_SignatureGenerateHash( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* hash_data, word32 hash_len, byte* sig, word32 *sig_len, const void* key, word32 key_len, WC_RNG* rng) { int ret; /* Suppress possible unused arg if all signature types are disabled */ (void)rng; /* Check arguments */ if (hash_data == NULL || hash_len <= 0 || sig == NULL || sig_len == NULL || *sig_len <= 0 || key == NULL || key_len <= 0) { return BAD_FUNC_ARG; } /* Validate signature len (needs to be at least max) */ if ((int)*sig_len < wc_SignatureGetSize(sig_type, key, key_len)) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid sig type/len"); return BAD_FUNC_ARG; } /* Validate hash size */ ret = wc_HashGetDigestSize(hash_type); if (ret < 0) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid hash type/len"); return ret; } ret = 0; /* Create signature using hash as data */ switch (sig_type) { case WC_SIGNATURE_TYPE_ECC: #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN) /* Create signature using provided ECC key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((ecc_key*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_ecc_sign_hash(hash_data, hash_len, sig, sig_len, rng, (ecc_key*)key); } while (ret == WC_PENDING_E); #else ret = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_RSA_W_ENC: case WC_SIGNATURE_TYPE_RSA: #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) /* Create signature using provided RSA key */ do { #ifdef WOLFSSL_ASYNC_CRYPT ret = wc_AsyncWait(ret, &((RsaKey*)key)->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); #endif if (ret >= 0) ret = wc_RsaSSL_Sign(hash_data, hash_len, sig, *sig_len, (RsaKey*)key, rng); } while (ret == WC_PENDING_E); if (ret >= 0) { *sig_len = ret; ret = 0; /* Success */ } #else ret = SIG_TYPE_E; #endif break; case WC_SIGNATURE_TYPE_NONE: default: ret = BAD_FUNC_ARG; break; } return ret; } int wc_SignatureGenerate( enum wc_HashType hash_type, enum wc_SignatureType sig_type, const byte* data, word32 data_len, byte* sig, word32 *sig_len, const void* key, word32 key_len, WC_RNG* rng) { int ret; word32 hash_len, hash_enc_len; #ifdef WOLFSSL_SMALL_STACK byte *hash_data; #else byte hash_data[MAX_DER_DIGEST_SZ]; #endif /* Check arguments */ if (data == NULL || data_len <= 0 || sig == NULL || sig_len == NULL || *sig_len <= 0 || key == NULL || key_len <= 0) { return BAD_FUNC_ARG; } /* Validate signature len (needs to be at least max) */ if ((int)*sig_len < wc_SignatureGetSize(sig_type, key, key_len)) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid sig type/len"); return BAD_FUNC_ARG; } /* Validate hash size */ ret = wc_HashGetDigestSize(hash_type); if (ret < 0) { WOLFSSL_MSG("wc_SignatureGenerate: Invalid hash type/len"); return ret; } hash_enc_len = hash_len = ret; #if !defined(NO_RSA) && !defined(WOLFSSL_RSA_PUBLIC_ONLY) if (sig_type == WC_SIGNATURE_TYPE_RSA_W_ENC) { /* For RSA with ASN.1 encoding include room */ hash_enc_len += MAX_DER_DIGEST_ASN_SZ; } #endif #ifdef WOLFSSL_SMALL_STACK /* Allocate temporary buffer for hash data */ hash_data = (byte*)XMALLOC(hash_enc_len, NULL, DYNAMIC_TYPE_TMP_BUFFER); if (hash_data == NULL) { return MEMORY_E; } #endif /* Perform hash of data */ ret = wc_Hash(hash_type, data, data_len, hash_data, hash_len); if (ret == 0) { /* Handle RSA with DER encoding */ if (sig_type == WC_SIGNATURE_TYPE_RSA_W_ENC) { #if defined(NO_RSA) || defined(NO_ASN) || \ defined(WOLFSSL_RSA_PUBLIC_ONLY) ret = SIG_TYPE_E; #else ret = wc_SignatureDerEncode(hash_type, hash_data, hash_len, &hash_enc_len); #endif } if (ret == 0) { /* Generate signature using hash */ ret = wc_SignatureGenerateHash(hash_type, sig_type, hash_data, hash_enc_len, sig, sig_len, key, key_len, rng); } } #ifdef WOLFSSL_SMALL_STACK XFREE(hash_data, NULL, DYNAMIC_TYPE_TMP_BUFFER); #endif return ret; } #endif /* NO_SIG_WRAPPER */
./CrossVul/dataset_final_sorted/CWE-327/c/bad_1336_0
crossvul-cpp_data_bad_4053_0
/* // Copyright (c) 2018 Intel Corporation // // 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 "passwd_mgr.hpp" #include "file.hpp" #include "shadowlock.hpp" #include <openssl/hmac.h> #include <openssl/rand.h> #include <openssl/sha.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include <cerrno> #include <cstring> #include <fstream> #include <iomanip> #include <phosphor-logging/log.hpp> namespace ipmi { static const char* passwdFileName = "/etc/ipmi_pass"; static const char* encryptKeyFileName = "/etc/key_file"; static const size_t maxKeySize = 8; #define META_PASSWD_SIG "=OPENBMC=" /* * Meta data struct for encrypted password file */ struct MetaPassStruct { char signature[10]; unsigned char reseved[2]; size_t hashSize; size_t ivSize; size_t dataSize; size_t padSize; size_t macSize; }; using namespace phosphor::logging; PasswdMgr::PasswdMgr() { initPasswordMap(); } std::string PasswdMgr::getPasswdByUserName(const std::string& userName) { checkAndReload(); auto iter = passwdMapList.find(userName); if (iter == passwdMapList.end()) { return std::string(); } return iter->second; } int PasswdMgr::updateUserEntry(const std::string& userName, const std::string& newUserName) { std::time_t updatedTime = getUpdatedFileTime(); // Check file time stamp to know passwdMapList is up-to-date. // If not up-to-date, then updatePasswdSpecialFile will read and // check the user entry existance. if (fileLastUpdatedTime == updatedTime && updatedTime != -EIO) { if (passwdMapList.find(userName) == passwdMapList.end()) { log<level::DEBUG>("User not found"); return 0; } } // Write passwdMap to Encryted file if (updatePasswdSpecialFile(userName, newUserName) != 0) { log<level::DEBUG>("Passwd file update failed"); return -EIO; } log<level::DEBUG>("Passwd file updated successfully"); return 0; } void PasswdMgr::checkAndReload(void) { std::time_t updatedTime = getUpdatedFileTime(); if (fileLastUpdatedTime != updatedTime && updatedTime != -1) { log<level::DEBUG>("Reloading password map list"); passwdMapList.clear(); initPasswordMap(); } } int PasswdMgr::encryptDecryptData(bool doEncrypt, const EVP_CIPHER* cipher, uint8_t* key, size_t keyLen, uint8_t* iv, size_t ivLen, uint8_t* inBytes, size_t inBytesLen, uint8_t* mac, size_t* macLen, unsigned char* outBytes, size_t* outBytesLen) { if (cipher == NULL || key == NULL || iv == NULL || inBytes == NULL || outBytes == NULL || mac == NULL || inBytesLen == 0 || (size_t)EVP_CIPHER_key_length(cipher) > keyLen || (size_t)EVP_CIPHER_iv_length(cipher) > ivLen) { log<level::DEBUG>("Error Invalid Inputs"); return -EINVAL; } if (!doEncrypt) { // verify MAC before decrypting the data. std::array<uint8_t, EVP_MAX_MD_SIZE> calMac; size_t calMacLen = calMac.size(); // calculate MAC for the encrypted message. if (NULL == HMAC(EVP_sha256(), key, keyLen, inBytes, inBytesLen, calMac.data(), reinterpret_cast<unsigned int*>(&calMacLen))) { log<level::DEBUG>("Error: Failed to calculate MAC"); return -EIO; } if (!((calMacLen == *macLen) && (std::memcmp(calMac.data(), mac, calMacLen) == 0))) { log<level::DEBUG>("Authenticated message doesn't match"); return -EBADMSG; } } std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)> ctx( EVP_CIPHER_CTX_new(), ::EVP_CIPHER_CTX_free); EVP_CIPHER_CTX_set_padding(ctx.get(), 1); // Set key & IV int retval = EVP_CipherInit_ex(ctx.get(), cipher, NULL, key, iv, static_cast<int>(doEncrypt)); if (!retval) { log<level::DEBUG>("EVP_CipherInit_ex failed", entry("RET_VAL=%d", retval)); return -EIO; } int outLen = 0, outEVPLen = 0; if ((retval = EVP_CipherUpdate(ctx.get(), outBytes + outLen, &outEVPLen, inBytes, inBytesLen))) { outLen += outEVPLen; if ((retval = EVP_CipherFinal(ctx.get(), outBytes + outLen, &outEVPLen))) { outLen += outEVPLen; *outBytesLen = outLen; } else { log<level::DEBUG>("EVP_CipherFinal fails", entry("RET_VAL=%d", retval)); return -EIO; } } else { log<level::DEBUG>("EVP_CipherUpdate fails", entry("RET_VAL=%d", retval)); return -EIO; } if (doEncrypt) { // Create MAC for the encrypted message if (NULL == HMAC(EVP_sha256(), key, keyLen, outBytes, *outBytesLen, mac, reinterpret_cast<unsigned int*>(macLen))) { log<level::DEBUG>("Failed to create authentication"); return -EIO; } } return 0; } void PasswdMgr::initPasswordMap(void) { phosphor::user::shadow::Lock lock(); std::vector<uint8_t> dataBuf; if (readPasswdFileData(dataBuf) != 0) { log<level::DEBUG>("Error in reading the encrypted pass file"); return; } if (dataBuf.size() != 0) { // populate the user list with password char* outPtr = reinterpret_cast<char*>(dataBuf.data()); char* nToken = NULL; char* linePtr = strtok_r(outPtr, "\n", &nToken); size_t lineSize = 0; while (linePtr != NULL) { size_t userEPos = 0; std::string lineStr(linePtr); if ((userEPos = lineStr.find(":")) != std::string::npos) { lineSize = lineStr.size(); passwdMapList.emplace( lineStr.substr(0, userEPos), lineStr.substr(userEPos + 1, lineSize - (userEPos + 1))); } linePtr = strtok_r(NULL, "\n", &nToken); } } // Update the timestamp fileLastUpdatedTime = getUpdatedFileTime(); return; } int PasswdMgr::readPasswdFileData(std::vector<uint8_t>& outBytes) { std::array<uint8_t, maxKeySize> keyBuff; std::ifstream keyFile(encryptKeyFileName, std::ios::in | std::ios::binary); if (!keyFile.is_open()) { log<level::DEBUG>("Error in opening encryption key file"); return -EIO; } keyFile.read(reinterpret_cast<char*>(keyBuff.data()), keyBuff.size()); if (keyFile.fail()) { log<level::DEBUG>("Error in reading encryption key file"); return -EIO; } std::ifstream passwdFile(passwdFileName, std::ios::in | std::ios::binary); if (!passwdFile.is_open()) { log<level::DEBUG>("Error in opening ipmi password file"); return -EIO; } // calculate file size and read the data passwdFile.seekg(0, std::ios::end); ssize_t fileSize = passwdFile.tellg(); passwdFile.seekg(0, std::ios::beg); std::vector<uint8_t> input(fileSize); passwdFile.read(reinterpret_cast<char*>(input.data()), fileSize); if (passwdFile.fail()) { log<level::DEBUG>("Error in reading encryption key file"); return -EIO; } // verify the signature first MetaPassStruct* metaData = reinterpret_cast<MetaPassStruct*>(input.data()); if (std::strncmp(metaData->signature, META_PASSWD_SIG, sizeof(metaData->signature))) { log<level::DEBUG>("Error signature mismatch in password file"); return -EBADMSG; } size_t inBytesLen = metaData->dataSize + metaData->padSize; // If data is empty i.e no password map then return success if (inBytesLen == 0) { log<level::DEBUG>("Empty password file"); return 0; } // compute the key needed to decrypt std::array<uint8_t, EVP_MAX_KEY_LENGTH> key; auto keyLen = key.size(); if (NULL == HMAC(EVP_sha256(), keyBuff.data(), keyBuff.size(), input.data() + sizeof(*metaData), metaData->hashSize, key.data(), reinterpret_cast<unsigned int*>(&keyLen))) { log<level::DEBUG>("Failed to create MAC for authentication"); return -EIO; } // decrypt the data uint8_t* iv = input.data() + sizeof(*metaData) + metaData->hashSize; size_t ivLen = metaData->ivSize; uint8_t* inBytes = iv + ivLen; uint8_t* mac = inBytes + inBytesLen; size_t macLen = metaData->macSize; size_t outBytesLen = 0; // Resize to actual data size outBytes.resize(inBytesLen + EVP_MAX_BLOCK_LENGTH); if (encryptDecryptData(false, EVP_aes_128_cbc(), key.data(), keyLen, iv, ivLen, inBytes, inBytesLen, mac, &macLen, outBytes.data(), &outBytesLen) != 0) { log<level::DEBUG>("Error in decryption"); return -EIO; } // Resize the vector to outBytesLen outBytes.resize(outBytesLen); OPENSSL_cleanse(key.data(), keyLen); OPENSSL_cleanse(iv, ivLen); return 0; } int PasswdMgr::updatePasswdSpecialFile(const std::string& userName, const std::string& newUserName) { phosphor::user::shadow::Lock lock(); size_t bytesWritten = 0; size_t inBytesLen = 0; size_t isUsrFound = false; const EVP_CIPHER* cipher = EVP_aes_128_cbc(); std::vector<uint8_t> dataBuf; // Read the encrypted file and get the file data // Check user existance and return if not exist. if (readPasswdFileData(dataBuf) != 0) { log<level::DEBUG>("Error in reading the encrypted pass file"); return -EIO; } if (dataBuf.size() != 0) { inBytesLen = dataBuf.size() + newUserName.size() + EVP_CIPHER_block_size(cipher); } std::vector<uint8_t> inBytes(inBytesLen); if (inBytesLen != 0) { char* outPtr = reinterpret_cast<char*>(dataBuf.data()); char* nToken = NULL; char* linePtr = strtok_r(outPtr, "\n", &nToken); while (linePtr != NULL) { size_t userEPos = 0; std::string lineStr(linePtr); if ((userEPos = lineStr.find(":")) != std::string::npos) { if (userName.compare(lineStr.substr(0, userEPos)) == 0) { isUsrFound = true; if (!newUserName.empty()) { bytesWritten += std::snprintf( reinterpret_cast<char*>(&inBytes[0]) + bytesWritten, (inBytesLen - bytesWritten), "%s%s\n", newUserName.c_str(), lineStr.substr(userEPos, lineStr.size()).data()); } } else { bytesWritten += std::snprintf( reinterpret_cast<char*>(&inBytes[0]) + bytesWritten, (inBytesLen - bytesWritten), "%s\n", lineStr.data()); } } linePtr = strtok_r(NULL, "\n", &nToken); } inBytesLen = bytesWritten; } if (!isUsrFound) { log<level::DEBUG>("User doesn't exist"); return 0; } // Read the key buff from key file std::array<uint8_t, maxKeySize> keyBuff; std::ifstream keyFile(encryptKeyFileName, std::ios::in | std::ios::binary); if (!keyFile.good()) { log<level::DEBUG>("Error in opening encryption key file"); return -EIO; } keyFile.read(reinterpret_cast<char*>(keyBuff.data()), keyBuff.size()); if (keyFile.fail()) { log<level::DEBUG>("Error in reading encryption key file"); return -EIO; } keyFile.close(); // Read the original passwd file mode struct stat st = {}; if (stat(passwdFileName, &st) != 0) { log<level::DEBUG>("Error in getting password file fstat()"); return -EIO; } // Create temporary file for write std::string pwdFile(passwdFileName); std::vector<char> tempFileName(pwdFile.begin(), pwdFile.end()); std::vector<char> fileTemplate = {'_', '_', 'X', 'X', 'X', 'X', 'X', 'X', '\0'}; tempFileName.insert(tempFileName.end(), fileTemplate.begin(), fileTemplate.end()); int fd = mkstemp((char*)tempFileName.data()); if (fd == -1) { log<level::DEBUG>("Error creating temp file"); return -EIO; } std::string strTempFileName(tempFileName.data()); // Open the temp file for writing from provided fd // By "true", remove it at exit if still there. // This is needed to cleanup the temp file at exception phosphor::user::File temp(fd, strTempFileName, "w", true); if ((temp)() == NULL) { close(fd); log<level::DEBUG>("Error creating temp file"); return -EIO; } // Set the file mode as of actual ipmi-pass file. if (fchmod(fileno((temp)()), st.st_mode) < 0) { log<level::DEBUG>("Error setting fchmod for temp file"); return -EIO; } const EVP_MD* digest = EVP_sha256(); size_t hashLen = EVP_MD_block_size(digest); std::vector<uint8_t> hash(hashLen); size_t ivLen = EVP_CIPHER_iv_length(cipher); std::vector<uint8_t> iv(ivLen); std::array<uint8_t, EVP_MAX_KEY_LENGTH> key; size_t keyLen = key.size(); std::array<uint8_t, EVP_MAX_MD_SIZE> mac; size_t macLen = mac.size(); // Create random hash and generate hash key which will be used for // encryption. if (RAND_bytes(hash.data(), hashLen) != 1) { log<level::DEBUG>("Hash genertion failed, bailing out"); return -EIO; } if (NULL == HMAC(digest, keyBuff.data(), keyBuff.size(), hash.data(), hashLen, key.data(), reinterpret_cast<unsigned int*>(&keyLen))) { log<level::DEBUG>("Failed to create MAC for authentication"); return -EIO; } // Generate IV values if (RAND_bytes(iv.data(), ivLen) != 1) { log<level::DEBUG>("UV genertion failed, bailing out"); return -EIO; } // Encrypt the input data std::vector<uint8_t> outBytes(inBytesLen + EVP_MAX_BLOCK_LENGTH); size_t outBytesLen = 0; if (inBytesLen != 0) { if (encryptDecryptData(true, EVP_aes_128_cbc(), key.data(), keyLen, iv.data(), ivLen, inBytes.data(), inBytesLen, mac.data(), &macLen, outBytes.data(), &outBytesLen) != 0) { log<level::DEBUG>("Error while encrypting the data"); return -EIO; } outBytes[outBytesLen] = 0; } OPENSSL_cleanse(key.data(), keyLen); // Update the meta password structure. MetaPassStruct metaData = {META_PASSWD_SIG, {0, 0}, 0, 0, 0, 0, 0}; metaData.hashSize = hashLen; metaData.ivSize = ivLen; metaData.dataSize = bytesWritten; metaData.padSize = outBytesLen - bytesWritten; metaData.macSize = macLen; if (fwrite(&metaData, 1, sizeof(metaData), (temp)()) != sizeof(metaData)) { log<level::DEBUG>("Error in writing meta data"); return -EIO; } if (fwrite(&hash[0], 1, hashLen, (temp)()) != hashLen) { log<level::DEBUG>("Error in writing hash data"); return -EIO; } if (fwrite(&iv[0], 1, ivLen, (temp)()) != ivLen) { log<level::DEBUG>("Error in writing IV data"); return -EIO; } if (fwrite(&outBytes[0], 1, outBytesLen, (temp)()) != outBytesLen) { log<level::DEBUG>("Error in writing encrypted data"); return -EIO; } if (fwrite(&mac[0], 1, macLen, (temp)()) != macLen) { log<level::DEBUG>("Error in writing MAC data"); return -EIO; } if (fflush((temp)())) { log<level::DEBUG>( "File fflush error while writing entries to special file"); return -EIO; } OPENSSL_cleanse(iv.data(), ivLen); // Rename the tmp file to actual file if (std::rename(strTempFileName.data(), passwdFileName) != 0) { log<level::DEBUG>("Failed to rename tmp file to ipmi-pass"); return -EIO; } return 0; } std::time_t PasswdMgr::getUpdatedFileTime() { struct stat fileStat = {}; if (stat(passwdFileName, &fileStat) != 0) { log<level::DEBUG>("Error - Getting passwd file time stamp"); return -EIO; } return fileStat.st_mtime; } } // namespace ipmi
./CrossVul/dataset_final_sorted/CWE-276/cpp/bad_4053_0
crossvul-cpp_data_good_4053_0
/* // Copyright (c) 2018 Intel Corporation // // 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 "passwd_mgr.hpp" #include "file.hpp" #include "shadowlock.hpp" #include <openssl/hmac.h> #include <openssl/rand.h> #include <openssl/sha.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include <cerrno> #include <cstring> #include <fstream> #include <iomanip> #include <phosphor-logging/log.hpp> namespace ipmi { static const char* passwdFileName = "/etc/ipmi_pass"; static const char* encryptKeyFileName = "/etc/key_file"; static const size_t maxKeySize = 8; #define META_PASSWD_SIG "=OPENBMC=" /* * Meta data struct for encrypted password file */ struct MetaPassStruct { char signature[10]; unsigned char reseved[2]; size_t hashSize; size_t ivSize; size_t dataSize; size_t padSize; size_t macSize; }; using namespace phosphor::logging; PasswdMgr::PasswdMgr() { initPasswordMap(); } std::string PasswdMgr::getPasswdByUserName(const std::string& userName) { checkAndReload(); auto iter = passwdMapList.find(userName); if (iter == passwdMapList.end()) { return std::string(); } return iter->second; } int PasswdMgr::updateUserEntry(const std::string& userName, const std::string& newUserName) { std::time_t updatedTime = getUpdatedFileTime(); // Check file time stamp to know passwdMapList is up-to-date. // If not up-to-date, then updatePasswdSpecialFile will read and // check the user entry existance. if (fileLastUpdatedTime == updatedTime && updatedTime != -EIO) { if (passwdMapList.find(userName) == passwdMapList.end()) { log<level::DEBUG>("User not found"); return 0; } } // Write passwdMap to Encryted file if (updatePasswdSpecialFile(userName, newUserName) != 0) { log<level::DEBUG>("Passwd file update failed"); return -EIO; } log<level::DEBUG>("Passwd file updated successfully"); return 0; } void PasswdMgr::checkAndReload(void) { std::time_t updatedTime = getUpdatedFileTime(); if (fileLastUpdatedTime != updatedTime && updatedTime != -1) { log<level::DEBUG>("Reloading password map list"); passwdMapList.clear(); initPasswordMap(); } } int PasswdMgr::encryptDecryptData(bool doEncrypt, const EVP_CIPHER* cipher, uint8_t* key, size_t keyLen, uint8_t* iv, size_t ivLen, uint8_t* inBytes, size_t inBytesLen, uint8_t* mac, size_t* macLen, unsigned char* outBytes, size_t* outBytesLen) { if (cipher == NULL || key == NULL || iv == NULL || inBytes == NULL || outBytes == NULL || mac == NULL || inBytesLen == 0 || (size_t)EVP_CIPHER_key_length(cipher) > keyLen || (size_t)EVP_CIPHER_iv_length(cipher) > ivLen) { log<level::DEBUG>("Error Invalid Inputs"); return -EINVAL; } if (!doEncrypt) { // verify MAC before decrypting the data. std::array<uint8_t, EVP_MAX_MD_SIZE> calMac; size_t calMacLen = calMac.size(); // calculate MAC for the encrypted message. if (NULL == HMAC(EVP_sha256(), key, keyLen, inBytes, inBytesLen, calMac.data(), reinterpret_cast<unsigned int*>(&calMacLen))) { log<level::DEBUG>("Error: Failed to calculate MAC"); return -EIO; } if (!((calMacLen == *macLen) && (std::memcmp(calMac.data(), mac, calMacLen) == 0))) { log<level::DEBUG>("Authenticated message doesn't match"); return -EBADMSG; } } std::unique_ptr<EVP_CIPHER_CTX, decltype(&::EVP_CIPHER_CTX_free)> ctx( EVP_CIPHER_CTX_new(), ::EVP_CIPHER_CTX_free); EVP_CIPHER_CTX_set_padding(ctx.get(), 1); // Set key & IV int retval = EVP_CipherInit_ex(ctx.get(), cipher, NULL, key, iv, static_cast<int>(doEncrypt)); if (!retval) { log<level::DEBUG>("EVP_CipherInit_ex failed", entry("RET_VAL=%d", retval)); return -EIO; } int outLen = 0, outEVPLen = 0; if ((retval = EVP_CipherUpdate(ctx.get(), outBytes + outLen, &outEVPLen, inBytes, inBytesLen))) { outLen += outEVPLen; if ((retval = EVP_CipherFinal(ctx.get(), outBytes + outLen, &outEVPLen))) { outLen += outEVPLen; *outBytesLen = outLen; } else { log<level::DEBUG>("EVP_CipherFinal fails", entry("RET_VAL=%d", retval)); return -EIO; } } else { log<level::DEBUG>("EVP_CipherUpdate fails", entry("RET_VAL=%d", retval)); return -EIO; } if (doEncrypt) { // Create MAC for the encrypted message if (NULL == HMAC(EVP_sha256(), key, keyLen, outBytes, *outBytesLen, mac, reinterpret_cast<unsigned int*>(macLen))) { log<level::DEBUG>("Failed to create authentication"); return -EIO; } } return 0; } void PasswdMgr::initPasswordMap(void) { phosphor::user::shadow::Lock lock(); std::vector<uint8_t> dataBuf; if (readPasswdFileData(dataBuf) != 0) { log<level::DEBUG>("Error in reading the encrypted pass file"); return; } if (dataBuf.size() != 0) { // populate the user list with password char* outPtr = reinterpret_cast<char*>(dataBuf.data()); char* nToken = NULL; char* linePtr = strtok_r(outPtr, "\n", &nToken); size_t lineSize = 0; while (linePtr != NULL) { size_t userEPos = 0; std::string lineStr(linePtr); if ((userEPos = lineStr.find(":")) != std::string::npos) { lineSize = lineStr.size(); passwdMapList.emplace( lineStr.substr(0, userEPos), lineStr.substr(userEPos + 1, lineSize - (userEPos + 1))); } linePtr = strtok_r(NULL, "\n", &nToken); } } // Update the timestamp fileLastUpdatedTime = getUpdatedFileTime(); return; } int PasswdMgr::readPasswdFileData(std::vector<uint8_t>& outBytes) { std::array<uint8_t, maxKeySize> keyBuff; std::ifstream keyFile(encryptKeyFileName, std::ios::in | std::ios::binary); if (!keyFile.is_open()) { log<level::DEBUG>("Error in opening encryption key file"); return -EIO; } keyFile.read(reinterpret_cast<char*>(keyBuff.data()), keyBuff.size()); if (keyFile.fail()) { log<level::DEBUG>("Error in reading encryption key file"); return -EIO; } std::ifstream passwdFile(passwdFileName, std::ios::in | std::ios::binary); if (!passwdFile.is_open()) { log<level::DEBUG>("Error in opening ipmi password file"); return -EIO; } // calculate file size and read the data passwdFile.seekg(0, std::ios::end); ssize_t fileSize = passwdFile.tellg(); passwdFile.seekg(0, std::ios::beg); std::vector<uint8_t> input(fileSize); passwdFile.read(reinterpret_cast<char*>(input.data()), fileSize); if (passwdFile.fail()) { log<level::DEBUG>("Error in reading encryption key file"); return -EIO; } // verify the signature first MetaPassStruct* metaData = reinterpret_cast<MetaPassStruct*>(input.data()); if (std::strncmp(metaData->signature, META_PASSWD_SIG, sizeof(metaData->signature))) { log<level::DEBUG>("Error signature mismatch in password file"); return -EBADMSG; } size_t inBytesLen = metaData->dataSize + metaData->padSize; // If data is empty i.e no password map then return success if (inBytesLen == 0) { log<level::DEBUG>("Empty password file"); return 0; } // compute the key needed to decrypt std::array<uint8_t, EVP_MAX_KEY_LENGTH> key; auto keyLen = key.size(); if (NULL == HMAC(EVP_sha256(), keyBuff.data(), keyBuff.size(), input.data() + sizeof(*metaData), metaData->hashSize, key.data(), reinterpret_cast<unsigned int*>(&keyLen))) { log<level::DEBUG>("Failed to create MAC for authentication"); return -EIO; } // decrypt the data uint8_t* iv = input.data() + sizeof(*metaData) + metaData->hashSize; size_t ivLen = metaData->ivSize; uint8_t* inBytes = iv + ivLen; uint8_t* mac = inBytes + inBytesLen; size_t macLen = metaData->macSize; size_t outBytesLen = 0; // Resize to actual data size outBytes.resize(inBytesLen + EVP_MAX_BLOCK_LENGTH); if (encryptDecryptData(false, EVP_aes_128_cbc(), key.data(), keyLen, iv, ivLen, inBytes, inBytesLen, mac, &macLen, outBytes.data(), &outBytesLen) != 0) { log<level::DEBUG>("Error in decryption"); return -EIO; } // Resize the vector to outBytesLen outBytes.resize(outBytesLen); OPENSSL_cleanse(key.data(), keyLen); OPENSSL_cleanse(iv, ivLen); return 0; } int PasswdMgr::updatePasswdSpecialFile(const std::string& userName, const std::string& newUserName) { phosphor::user::shadow::Lock lock(); size_t bytesWritten = 0; size_t inBytesLen = 0; size_t isUsrFound = false; const EVP_CIPHER* cipher = EVP_aes_128_cbc(); std::vector<uint8_t> dataBuf; // Read the encrypted file and get the file data // Check user existance and return if not exist. if (readPasswdFileData(dataBuf) != 0) { log<level::DEBUG>("Error in reading the encrypted pass file"); return -EIO; } if (dataBuf.size() != 0) { inBytesLen = dataBuf.size() + newUserName.size() + EVP_CIPHER_block_size(cipher); } std::vector<uint8_t> inBytes(inBytesLen); if (inBytesLen != 0) { char* outPtr = reinterpret_cast<char*>(dataBuf.data()); char* nToken = NULL; char* linePtr = strtok_r(outPtr, "\n", &nToken); while (linePtr != NULL) { size_t userEPos = 0; std::string lineStr(linePtr); if ((userEPos = lineStr.find(":")) != std::string::npos) { if (userName.compare(lineStr.substr(0, userEPos)) == 0) { isUsrFound = true; if (!newUserName.empty()) { bytesWritten += std::snprintf( reinterpret_cast<char*>(&inBytes[0]) + bytesWritten, (inBytesLen - bytesWritten), "%s%s\n", newUserName.c_str(), lineStr.substr(userEPos, lineStr.size()).data()); } } else { bytesWritten += std::snprintf( reinterpret_cast<char*>(&inBytes[0]) + bytesWritten, (inBytesLen - bytesWritten), "%s\n", lineStr.data()); } } linePtr = strtok_r(NULL, "\n", &nToken); } inBytesLen = bytesWritten; } if (!isUsrFound) { log<level::DEBUG>("User doesn't exist"); return 0; } // Read the key buff from key file std::array<uint8_t, maxKeySize> keyBuff; std::ifstream keyFile(encryptKeyFileName, std::ios::in | std::ios::binary); if (!keyFile.good()) { log<level::DEBUG>("Error in opening encryption key file"); return -EIO; } keyFile.read(reinterpret_cast<char*>(keyBuff.data()), keyBuff.size()); if (keyFile.fail()) { log<level::DEBUG>("Error in reading encryption key file"); return -EIO; } keyFile.close(); // Read the original passwd file mode struct stat st = {}; if (stat(passwdFileName, &st) != 0) { log<level::DEBUG>("Error in getting password file fstat()"); return -EIO; } // Create temporary file for write std::string pwdFile(passwdFileName); std::vector<char> tempFileName(pwdFile.begin(), pwdFile.end()); std::vector<char> fileTemplate = {'_', '_', 'X', 'X', 'X', 'X', 'X', 'X', '\0'}; tempFileName.insert(tempFileName.end(), fileTemplate.begin(), fileTemplate.end()); int fd = mkstemp((char*)tempFileName.data()); if (fd == -1) { log<level::DEBUG>("Error creating temp file"); return -EIO; } std::string strTempFileName(tempFileName.data()); // Open the temp file for writing from provided fd // By "true", remove it at exit if still there. // This is needed to cleanup the temp file at exception phosphor::user::File temp(fd, strTempFileName, "w", true); if ((temp)() == NULL) { close(fd); log<level::DEBUG>("Error creating temp file"); return -EIO; } // Set the file mode as read-write for owner only if (fchmod(fileno((temp)()), S_IRUSR | S_IWUSR) < 0) { log<level::DEBUG>("Error setting fchmod for temp file"); return -EIO; } const EVP_MD* digest = EVP_sha256(); size_t hashLen = EVP_MD_block_size(digest); std::vector<uint8_t> hash(hashLen); size_t ivLen = EVP_CIPHER_iv_length(cipher); std::vector<uint8_t> iv(ivLen); std::array<uint8_t, EVP_MAX_KEY_LENGTH> key; size_t keyLen = key.size(); std::array<uint8_t, EVP_MAX_MD_SIZE> mac; size_t macLen = mac.size(); // Create random hash and generate hash key which will be used for // encryption. if (RAND_bytes(hash.data(), hashLen) != 1) { log<level::DEBUG>("Hash genertion failed, bailing out"); return -EIO; } if (NULL == HMAC(digest, keyBuff.data(), keyBuff.size(), hash.data(), hashLen, key.data(), reinterpret_cast<unsigned int*>(&keyLen))) { log<level::DEBUG>("Failed to create MAC for authentication"); return -EIO; } // Generate IV values if (RAND_bytes(iv.data(), ivLen) != 1) { log<level::DEBUG>("UV genertion failed, bailing out"); return -EIO; } // Encrypt the input data std::vector<uint8_t> outBytes(inBytesLen + EVP_MAX_BLOCK_LENGTH); size_t outBytesLen = 0; if (inBytesLen != 0) { if (encryptDecryptData(true, EVP_aes_128_cbc(), key.data(), keyLen, iv.data(), ivLen, inBytes.data(), inBytesLen, mac.data(), &macLen, outBytes.data(), &outBytesLen) != 0) { log<level::DEBUG>("Error while encrypting the data"); return -EIO; } outBytes[outBytesLen] = 0; } OPENSSL_cleanse(key.data(), keyLen); // Update the meta password structure. MetaPassStruct metaData = {META_PASSWD_SIG, {0, 0}, 0, 0, 0, 0, 0}; metaData.hashSize = hashLen; metaData.ivSize = ivLen; metaData.dataSize = bytesWritten; metaData.padSize = outBytesLen - bytesWritten; metaData.macSize = macLen; if (fwrite(&metaData, 1, sizeof(metaData), (temp)()) != sizeof(metaData)) { log<level::DEBUG>("Error in writing meta data"); return -EIO; } if (fwrite(&hash[0], 1, hashLen, (temp)()) != hashLen) { log<level::DEBUG>("Error in writing hash data"); return -EIO; } if (fwrite(&iv[0], 1, ivLen, (temp)()) != ivLen) { log<level::DEBUG>("Error in writing IV data"); return -EIO; } if (fwrite(&outBytes[0], 1, outBytesLen, (temp)()) != outBytesLen) { log<level::DEBUG>("Error in writing encrypted data"); return -EIO; } if (fwrite(&mac[0], 1, macLen, (temp)()) != macLen) { log<level::DEBUG>("Error in writing MAC data"); return -EIO; } if (fflush((temp)())) { log<level::DEBUG>( "File fflush error while writing entries to special file"); return -EIO; } OPENSSL_cleanse(iv.data(), ivLen); // Rename the tmp file to actual file if (std::rename(strTempFileName.data(), passwdFileName) != 0) { log<level::DEBUG>("Failed to rename tmp file to ipmi-pass"); return -EIO; } return 0; } std::time_t PasswdMgr::getUpdatedFileTime() { struct stat fileStat = {}; if (stat(passwdFileName, &fileStat) != 0) { log<level::DEBUG>("Error - Getting passwd file time stamp"); return -EIO; } return fileStat.st_mtime; } } // namespace ipmi
./CrossVul/dataset_final_sorted/CWE-276/cpp/good_4053_0
crossvul-cpp_data_bad_4225_4
// SPDX-License-Identifier: GPL-2.0 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/errno.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/smp.h> #include <linux/prctl.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/sched/idle.h> #include <linux/sched/debug.h> #include <linux/sched/task.h> #include <linux/sched/task_stack.h> #include <linux/init.h> #include <linux/export.h> #include <linux/pm.h> #include <linux/tick.h> #include <linux/random.h> #include <linux/user-return-notifier.h> #include <linux/dmi.h> #include <linux/utsname.h> #include <linux/stackprotector.h> #include <linux/cpuidle.h> #include <linux/acpi.h> #include <linux/elf-randomize.h> #include <trace/events/power.h> #include <linux/hw_breakpoint.h> #include <asm/cpu.h> #include <asm/apic.h> #include <linux/uaccess.h> #include <asm/mwait.h> #include <asm/fpu/internal.h> #include <asm/debugreg.h> #include <asm/nmi.h> #include <asm/tlbflush.h> #include <asm/mce.h> #include <asm/vm86.h> #include <asm/switch_to.h> #include <asm/desc.h> #include <asm/prctl.h> #include <asm/spec-ctrl.h> #include <asm/io_bitmap.h> #include <asm/proto.h> #include "process.h" /* * per-CPU TSS segments. Threads are completely 'soft' on Linux, * no more per-task TSS's. The TSS size is kept cacheline-aligned * so they are allowed to end up in the .data..cacheline_aligned * section. Since TSS's are completely CPU-local, we want them * on exact cacheline boundaries, to eliminate cacheline ping-pong. */ __visible DEFINE_PER_CPU_PAGE_ALIGNED(struct tss_struct, cpu_tss_rw) = { .x86_tss = { /* * .sp0 is only used when entering ring 0 from a lower * privilege level. Since the init task never runs anything * but ring 0 code, there is no need for a valid value here. * Poison it. */ .sp0 = (1UL << (BITS_PER_LONG-1)) + 1, /* * .sp1 is cpu_current_top_of_stack. The init task never * runs user code, but cpu_current_top_of_stack should still * be well defined before the first context switch. */ .sp1 = TOP_OF_INIT_STACK, #ifdef CONFIG_X86_32 .ss0 = __KERNEL_DS, .ss1 = __KERNEL_CS, #endif .io_bitmap_base = IO_BITMAP_OFFSET_INVALID, }, }; EXPORT_PER_CPU_SYMBOL(cpu_tss_rw); DEFINE_PER_CPU(bool, __tss_limit_invalid); EXPORT_PER_CPU_SYMBOL_GPL(__tss_limit_invalid); /* * this gets called so that we can store lazy state into memory and copy the * current task into the new thread. */ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src) { memcpy(dst, src, arch_task_struct_size); #ifdef CONFIG_VM86 dst->thread.vm86 = NULL; #endif return fpu__copy(dst, src); } /* * Free thread data structures etc.. */ void exit_thread(struct task_struct *tsk) { struct thread_struct *t = &tsk->thread; struct fpu *fpu = &t->fpu; if (test_thread_flag(TIF_IO_BITMAP)) io_bitmap_exit(tsk); free_vm86(t); fpu__drop(fpu); } static int set_new_tls(struct task_struct *p, unsigned long tls) { struct user_desc __user *utls = (struct user_desc __user *)tls; if (in_ia32_syscall()) return do_set_thread_area(p, -1, utls, 0); else return do_set_thread_area_64(p, ARCH_SET_FS, tls); } int copy_thread_tls(unsigned long clone_flags, unsigned long sp, unsigned long arg, struct task_struct *p, unsigned long tls) { struct inactive_task_frame *frame; struct fork_frame *fork_frame; struct pt_regs *childregs; int ret = 0; childregs = task_pt_regs(p); fork_frame = container_of(childregs, struct fork_frame, regs); frame = &fork_frame->frame; frame->bp = 0; frame->ret_addr = (unsigned long) ret_from_fork; p->thread.sp = (unsigned long) fork_frame; p->thread.io_bitmap = NULL; memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps)); #ifdef CONFIG_X86_64 savesegment(gs, p->thread.gsindex); p->thread.gsbase = p->thread.gsindex ? 0 : current->thread.gsbase; savesegment(fs, p->thread.fsindex); p->thread.fsbase = p->thread.fsindex ? 0 : current->thread.fsbase; savesegment(es, p->thread.es); savesegment(ds, p->thread.ds); #else p->thread.sp0 = (unsigned long) (childregs + 1); /* * Clear all status flags including IF and set fixed bit. 64bit * does not have this initialization as the frame does not contain * flags. The flags consistency (especially vs. AC) is there * ensured via objtool, which lacks 32bit support. */ frame->flags = X86_EFLAGS_FIXED; #endif /* Kernel thread ? */ if (unlikely(p->flags & PF_KTHREAD)) { memset(childregs, 0, sizeof(struct pt_regs)); kthread_frame_init(frame, sp, arg); return 0; } frame->bx = 0; *childregs = *current_pt_regs(); childregs->ax = 0; if (sp) childregs->sp = sp; #ifdef CONFIG_X86_32 task_user_gs(p) = get_user_gs(current_pt_regs()); #endif /* Set a new TLS for the child thread? */ if (clone_flags & CLONE_SETTLS) ret = set_new_tls(p, tls); if (!ret && unlikely(test_tsk_thread_flag(current, TIF_IO_BITMAP))) io_bitmap_share(p); return ret; } void flush_thread(void) { struct task_struct *tsk = current; flush_ptrace_hw_breakpoint(tsk); memset(tsk->thread.tls_array, 0, sizeof(tsk->thread.tls_array)); fpu__clear_all(&tsk->thread.fpu); } void disable_TSC(void) { preempt_disable(); if (!test_and_set_thread_flag(TIF_NOTSC)) /* * Must flip the CPU state synchronously with * TIF_NOTSC in the current running context. */ cr4_set_bits(X86_CR4_TSD); preempt_enable(); } static void enable_TSC(void) { preempt_disable(); if (test_and_clear_thread_flag(TIF_NOTSC)) /* * Must flip the CPU state synchronously with * TIF_NOTSC in the current running context. */ cr4_clear_bits(X86_CR4_TSD); preempt_enable(); } int get_tsc_mode(unsigned long adr) { unsigned int val; if (test_thread_flag(TIF_NOTSC)) val = PR_TSC_SIGSEGV; else val = PR_TSC_ENABLE; return put_user(val, (unsigned int __user *)adr); } int set_tsc_mode(unsigned int val) { if (val == PR_TSC_SIGSEGV) disable_TSC(); else if (val == PR_TSC_ENABLE) enable_TSC(); else return -EINVAL; return 0; } DEFINE_PER_CPU(u64, msr_misc_features_shadow); static void set_cpuid_faulting(bool on) { u64 msrval; msrval = this_cpu_read(msr_misc_features_shadow); msrval &= ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT; msrval |= (on << MSR_MISC_FEATURES_ENABLES_CPUID_FAULT_BIT); this_cpu_write(msr_misc_features_shadow, msrval); wrmsrl(MSR_MISC_FEATURES_ENABLES, msrval); } static void disable_cpuid(void) { preempt_disable(); if (!test_and_set_thread_flag(TIF_NOCPUID)) { /* * Must flip the CPU state synchronously with * TIF_NOCPUID in the current running context. */ set_cpuid_faulting(true); } preempt_enable(); } static void enable_cpuid(void) { preempt_disable(); if (test_and_clear_thread_flag(TIF_NOCPUID)) { /* * Must flip the CPU state synchronously with * TIF_NOCPUID in the current running context. */ set_cpuid_faulting(false); } preempt_enable(); } static int get_cpuid_mode(void) { return !test_thread_flag(TIF_NOCPUID); } static int set_cpuid_mode(struct task_struct *task, unsigned long cpuid_enabled) { if (!boot_cpu_has(X86_FEATURE_CPUID_FAULT)) return -ENODEV; if (cpuid_enabled) enable_cpuid(); else disable_cpuid(); return 0; } /* * Called immediately after a successful exec. */ void arch_setup_new_exec(void) { /* If cpuid was previously disabled for this task, re-enable it. */ if (test_thread_flag(TIF_NOCPUID)) enable_cpuid(); /* * Don't inherit TIF_SSBD across exec boundary when * PR_SPEC_DISABLE_NOEXEC is used. */ if (test_thread_flag(TIF_SSBD) && task_spec_ssb_noexec(current)) { clear_thread_flag(TIF_SSBD); task_clear_spec_ssb_disable(current); task_clear_spec_ssb_noexec(current); speculation_ctrl_update(task_thread_info(current)->flags); } } #ifdef CONFIG_X86_IOPL_IOPERM static inline void tss_invalidate_io_bitmap(struct tss_struct *tss) { /* * Invalidate the I/O bitmap by moving io_bitmap_base outside the * TSS limit so any subsequent I/O access from user space will * trigger a #GP. * * This is correct even when VMEXIT rewrites the TSS limit * to 0x67 as the only requirement is that the base points * outside the limit. */ tss->x86_tss.io_bitmap_base = IO_BITMAP_OFFSET_INVALID; } static inline void switch_to_bitmap(unsigned long tifp) { /* * Invalidate I/O bitmap if the previous task used it. This prevents * any possible leakage of an active I/O bitmap. * * If the next task has an I/O bitmap it will handle it on exit to * user mode. */ if (tifp & _TIF_IO_BITMAP) tss_invalidate_io_bitmap(this_cpu_ptr(&cpu_tss_rw)); } static void tss_copy_io_bitmap(struct tss_struct *tss, struct io_bitmap *iobm) { /* * Copy at least the byte range of the incoming tasks bitmap which * covers the permitted I/O ports. * * If the previous task which used an I/O bitmap had more bits * permitted, then the copy needs to cover those as well so they * get turned off. */ memcpy(tss->io_bitmap.bitmap, iobm->bitmap, max(tss->io_bitmap.prev_max, iobm->max)); /* * Store the new max and the sequence number of this bitmap * and a pointer to the bitmap itself. */ tss->io_bitmap.prev_max = iobm->max; tss->io_bitmap.prev_sequence = iobm->sequence; } /** * tss_update_io_bitmap - Update I/O bitmap before exiting to usermode */ void native_tss_update_io_bitmap(void) { struct tss_struct *tss = this_cpu_ptr(&cpu_tss_rw); struct thread_struct *t = &current->thread; u16 *base = &tss->x86_tss.io_bitmap_base; if (!test_thread_flag(TIF_IO_BITMAP)) { tss_invalidate_io_bitmap(tss); return; } if (IS_ENABLED(CONFIG_X86_IOPL_IOPERM) && t->iopl_emul == 3) { *base = IO_BITMAP_OFFSET_VALID_ALL; } else { struct io_bitmap *iobm = t->io_bitmap; /* * Only copy bitmap data when the sequence number differs. The * update time is accounted to the incoming task. */ if (tss->io_bitmap.prev_sequence != iobm->sequence) tss_copy_io_bitmap(tss, iobm); /* Enable the bitmap */ *base = IO_BITMAP_OFFSET_VALID_MAP; } /* * Make sure that the TSS limit is covering the IO bitmap. It might have * been cut down by a VMEXIT to 0x67 which would cause a subsequent I/O * access from user space to trigger a #GP because tbe bitmap is outside * the TSS limit. */ refresh_tss_limit(); } #else /* CONFIG_X86_IOPL_IOPERM */ static inline void switch_to_bitmap(unsigned long tifp) { } #endif #ifdef CONFIG_SMP struct ssb_state { struct ssb_state *shared_state; raw_spinlock_t lock; unsigned int disable_state; unsigned long local_state; }; #define LSTATE_SSB 0 static DEFINE_PER_CPU(struct ssb_state, ssb_state); void speculative_store_bypass_ht_init(void) { struct ssb_state *st = this_cpu_ptr(&ssb_state); unsigned int this_cpu = smp_processor_id(); unsigned int cpu; st->local_state = 0; /* * Shared state setup happens once on the first bringup * of the CPU. It's not destroyed on CPU hotunplug. */ if (st->shared_state) return; raw_spin_lock_init(&st->lock); /* * Go over HT siblings and check whether one of them has set up the * shared state pointer already. */ for_each_cpu(cpu, topology_sibling_cpumask(this_cpu)) { if (cpu == this_cpu) continue; if (!per_cpu(ssb_state, cpu).shared_state) continue; /* Link it to the state of the sibling: */ st->shared_state = per_cpu(ssb_state, cpu).shared_state; return; } /* * First HT sibling to come up on the core. Link shared state of * the first HT sibling to itself. The siblings on the same core * which come up later will see the shared state pointer and link * themself to the state of this CPU. */ st->shared_state = st; } /* * Logic is: First HT sibling enables SSBD for both siblings in the core * and last sibling to disable it, disables it for the whole core. This how * MSR_SPEC_CTRL works in "hardware": * * CORE_SPEC_CTRL = THREAD0_SPEC_CTRL | THREAD1_SPEC_CTRL */ static __always_inline void amd_set_core_ssb_state(unsigned long tifn) { struct ssb_state *st = this_cpu_ptr(&ssb_state); u64 msr = x86_amd_ls_cfg_base; if (!static_cpu_has(X86_FEATURE_ZEN)) { msr |= ssbd_tif_to_amd_ls_cfg(tifn); wrmsrl(MSR_AMD64_LS_CFG, msr); return; } if (tifn & _TIF_SSBD) { /* * Since this can race with prctl(), block reentry on the * same CPU. */ if (__test_and_set_bit(LSTATE_SSB, &st->local_state)) return; msr |= x86_amd_ls_cfg_ssbd_mask; raw_spin_lock(&st->shared_state->lock); /* First sibling enables SSBD: */ if (!st->shared_state->disable_state) wrmsrl(MSR_AMD64_LS_CFG, msr); st->shared_state->disable_state++; raw_spin_unlock(&st->shared_state->lock); } else { if (!__test_and_clear_bit(LSTATE_SSB, &st->local_state)) return; raw_spin_lock(&st->shared_state->lock); st->shared_state->disable_state--; if (!st->shared_state->disable_state) wrmsrl(MSR_AMD64_LS_CFG, msr); raw_spin_unlock(&st->shared_state->lock); } } #else static __always_inline void amd_set_core_ssb_state(unsigned long tifn) { u64 msr = x86_amd_ls_cfg_base | ssbd_tif_to_amd_ls_cfg(tifn); wrmsrl(MSR_AMD64_LS_CFG, msr); } #endif static __always_inline void amd_set_ssb_virt_state(unsigned long tifn) { /* * SSBD has the same definition in SPEC_CTRL and VIRT_SPEC_CTRL, * so ssbd_tif_to_spec_ctrl() just works. */ wrmsrl(MSR_AMD64_VIRT_SPEC_CTRL, ssbd_tif_to_spec_ctrl(tifn)); } /* * Update the MSRs managing speculation control, during context switch. * * tifp: Previous task's thread flags * tifn: Next task's thread flags */ static __always_inline void __speculation_ctrl_update(unsigned long tifp, unsigned long tifn) { unsigned long tif_diff = tifp ^ tifn; u64 msr = x86_spec_ctrl_base; bool updmsr = false; lockdep_assert_irqs_disabled(); /* Handle change of TIF_SSBD depending on the mitigation method. */ if (static_cpu_has(X86_FEATURE_VIRT_SSBD)) { if (tif_diff & _TIF_SSBD) amd_set_ssb_virt_state(tifn); } else if (static_cpu_has(X86_FEATURE_LS_CFG_SSBD)) { if (tif_diff & _TIF_SSBD) amd_set_core_ssb_state(tifn); } else if (static_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD) || static_cpu_has(X86_FEATURE_AMD_SSBD)) { updmsr |= !!(tif_diff & _TIF_SSBD); msr |= ssbd_tif_to_spec_ctrl(tifn); } /* Only evaluate TIF_SPEC_IB if conditional STIBP is enabled. */ if (IS_ENABLED(CONFIG_SMP) && static_branch_unlikely(&switch_to_cond_stibp)) { updmsr |= !!(tif_diff & _TIF_SPEC_IB); msr |= stibp_tif_to_spec_ctrl(tifn); } if (updmsr) wrmsrl(MSR_IA32_SPEC_CTRL, msr); } static unsigned long speculation_ctrl_update_tif(struct task_struct *tsk) { if (test_and_clear_tsk_thread_flag(tsk, TIF_SPEC_FORCE_UPDATE)) { if (task_spec_ssb_disable(tsk)) set_tsk_thread_flag(tsk, TIF_SSBD); else clear_tsk_thread_flag(tsk, TIF_SSBD); if (task_spec_ib_disable(tsk)) set_tsk_thread_flag(tsk, TIF_SPEC_IB); else clear_tsk_thread_flag(tsk, TIF_SPEC_IB); } /* Return the updated threadinfo flags*/ return task_thread_info(tsk)->flags; } void speculation_ctrl_update(unsigned long tif) { unsigned long flags; /* Forced update. Make sure all relevant TIF flags are different */ local_irq_save(flags); __speculation_ctrl_update(~tif, tif); local_irq_restore(flags); } /* Called from seccomp/prctl update */ void speculation_ctrl_update_current(void) { preempt_disable(); speculation_ctrl_update(speculation_ctrl_update_tif(current)); preempt_enable(); } static inline void cr4_toggle_bits_irqsoff(unsigned long mask) { unsigned long newval, cr4 = this_cpu_read(cpu_tlbstate.cr4); newval = cr4 ^ mask; if (newval != cr4) { this_cpu_write(cpu_tlbstate.cr4, newval); __write_cr4(newval); } } void __switch_to_xtra(struct task_struct *prev_p, struct task_struct *next_p) { unsigned long tifp, tifn; tifn = READ_ONCE(task_thread_info(next_p)->flags); tifp = READ_ONCE(task_thread_info(prev_p)->flags); switch_to_bitmap(tifp); propagate_user_return_notify(prev_p, next_p); if ((tifp & _TIF_BLOCKSTEP || tifn & _TIF_BLOCKSTEP) && arch_has_block_step()) { unsigned long debugctl, msk; rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl); debugctl &= ~DEBUGCTLMSR_BTF; msk = tifn & _TIF_BLOCKSTEP; debugctl |= (msk >> TIF_BLOCKSTEP) << DEBUGCTLMSR_BTF_SHIFT; wrmsrl(MSR_IA32_DEBUGCTLMSR, debugctl); } if ((tifp ^ tifn) & _TIF_NOTSC) cr4_toggle_bits_irqsoff(X86_CR4_TSD); if ((tifp ^ tifn) & _TIF_NOCPUID) set_cpuid_faulting(!!(tifn & _TIF_NOCPUID)); if (likely(!((tifp | tifn) & _TIF_SPEC_FORCE_UPDATE))) { __speculation_ctrl_update(tifp, tifn); } else { speculation_ctrl_update_tif(prev_p); tifn = speculation_ctrl_update_tif(next_p); /* Enforce MSR update to ensure consistent state */ __speculation_ctrl_update(~tifn, tifn); } if ((tifp ^ tifn) & _TIF_SLD) switch_to_sld(tifn); } /* * Idle related variables and functions */ unsigned long boot_option_idle_override = IDLE_NO_OVERRIDE; EXPORT_SYMBOL(boot_option_idle_override); static void (*x86_idle)(void); #ifndef CONFIG_SMP static inline void play_dead(void) { BUG(); } #endif void arch_cpu_idle_enter(void) { tsc_verify_tsc_adjust(false); local_touch_nmi(); } void arch_cpu_idle_dead(void) { play_dead(); } /* * Called from the generic idle code. */ void arch_cpu_idle(void) { x86_idle(); } /* * We use this if we don't have any better idle routine.. */ void __cpuidle default_idle(void) { trace_cpu_idle_rcuidle(1, smp_processor_id()); safe_halt(); trace_cpu_idle_rcuidle(PWR_EVENT_EXIT, smp_processor_id()); } #if defined(CONFIG_APM_MODULE) || defined(CONFIG_HALTPOLL_CPUIDLE_MODULE) EXPORT_SYMBOL(default_idle); #endif #ifdef CONFIG_XEN bool xen_set_default_idle(void) { bool ret = !!x86_idle; x86_idle = default_idle; return ret; } #endif void stop_this_cpu(void *dummy) { local_irq_disable(); /* * Remove this CPU: */ set_cpu_online(smp_processor_id(), false); disable_local_APIC(); mcheck_cpu_clear(this_cpu_ptr(&cpu_info)); /* * Use wbinvd on processors that support SME. This provides support * for performing a successful kexec when going from SME inactive * to SME active (or vice-versa). The cache must be cleared so that * if there are entries with the same physical address, both with and * without the encryption bit, they don't race each other when flushed * and potentially end up with the wrong entry being committed to * memory. */ if (boot_cpu_has(X86_FEATURE_SME)) native_wbinvd(); for (;;) { /* * Use native_halt() so that memory contents don't change * (stack usage and variables) after possibly issuing the * native_wbinvd() above. */ native_halt(); } } /* * AMD Erratum 400 aware idle routine. We handle it the same way as C3 power * states (local apic timer and TSC stop). */ static void amd_e400_idle(void) { /* * We cannot use static_cpu_has_bug() here because X86_BUG_AMD_APIC_C1E * gets set after static_cpu_has() places have been converted via * alternatives. */ if (!boot_cpu_has_bug(X86_BUG_AMD_APIC_C1E)) { default_idle(); return; } tick_broadcast_enter(); default_idle(); /* * The switch back from broadcast mode needs to be called with * interrupts disabled. */ local_irq_disable(); tick_broadcast_exit(); local_irq_enable(); } /* * Intel Core2 and older machines prefer MWAIT over HALT for C1. * We can't rely on cpuidle installing MWAIT, because it will not load * on systems that support only C1 -- so the boot default must be MWAIT. * * Some AMD machines are the opposite, they depend on using HALT. * * So for default C1, which is used during boot until cpuidle loads, * use MWAIT-C1 on Intel HW that has it, else use HALT. */ static int prefer_mwait_c1_over_halt(const struct cpuinfo_x86 *c) { if (c->x86_vendor != X86_VENDOR_INTEL) return 0; if (!cpu_has(c, X86_FEATURE_MWAIT) || boot_cpu_has_bug(X86_BUG_MONITOR)) return 0; return 1; } /* * MONITOR/MWAIT with no hints, used for default C1 state. This invokes MWAIT * with interrupts enabled and no flags, which is backwards compatible with the * original MWAIT implementation. */ static __cpuidle void mwait_idle(void) { if (!current_set_polling_and_test()) { trace_cpu_idle_rcuidle(1, smp_processor_id()); if (this_cpu_has(X86_BUG_CLFLUSH_MONITOR)) { mb(); /* quirk */ clflush((void *)&current_thread_info()->flags); mb(); /* quirk */ } __monitor((void *)&current_thread_info()->flags, 0, 0); if (!need_resched()) __sti_mwait(0, 0); else local_irq_enable(); trace_cpu_idle_rcuidle(PWR_EVENT_EXIT, smp_processor_id()); } else { local_irq_enable(); } __current_clr_polling(); } void select_idle_routine(const struct cpuinfo_x86 *c) { #ifdef CONFIG_SMP if (boot_option_idle_override == IDLE_POLL && smp_num_siblings > 1) pr_warn_once("WARNING: polling idle and HT enabled, performance may degrade\n"); #endif if (x86_idle || boot_option_idle_override == IDLE_POLL) return; if (boot_cpu_has_bug(X86_BUG_AMD_E400)) { pr_info("using AMD E400 aware idle routine\n"); x86_idle = amd_e400_idle; } else if (prefer_mwait_c1_over_halt(c)) { pr_info("using mwait in idle threads\n"); x86_idle = mwait_idle; } else x86_idle = default_idle; } void amd_e400_c1e_apic_setup(void) { if (boot_cpu_has_bug(X86_BUG_AMD_APIC_C1E)) { pr_info("Switch to broadcast mode on CPU%d\n", smp_processor_id()); local_irq_disable(); tick_broadcast_force(); local_irq_enable(); } } void __init arch_post_acpi_subsys_init(void) { u32 lo, hi; if (!boot_cpu_has_bug(X86_BUG_AMD_E400)) return; /* * AMD E400 detection needs to happen after ACPI has been enabled. If * the machine is affected K8_INTP_C1E_ACTIVE_MASK bits are set in * MSR_K8_INT_PENDING_MSG. */ rdmsr(MSR_K8_INT_PENDING_MSG, lo, hi); if (!(lo & K8_INTP_C1E_ACTIVE_MASK)) return; boot_cpu_set_bug(X86_BUG_AMD_APIC_C1E); if (!boot_cpu_has(X86_FEATURE_NONSTOP_TSC)) mark_tsc_unstable("TSC halt in AMD C1E"); pr_info("System has AMD C1E enabled\n"); } static int __init idle_setup(char *str) { if (!str) return -EINVAL; if (!strcmp(str, "poll")) { pr_info("using polling idle threads\n"); boot_option_idle_override = IDLE_POLL; cpu_idle_poll_ctrl(true); } else if (!strcmp(str, "halt")) { /* * When the boot option of idle=halt is added, halt is * forced to be used for CPU idle. In such case CPU C2/C3 * won't be used again. * To continue to load the CPU idle driver, don't touch * the boot_option_idle_override. */ x86_idle = default_idle; boot_option_idle_override = IDLE_HALT; } else if (!strcmp(str, "nomwait")) { /* * If the boot option of "idle=nomwait" is added, * it means that mwait will be disabled for CPU C2/C3 * states. In such case it won't touch the variable * of boot_option_idle_override. */ boot_option_idle_override = IDLE_NOMWAIT; } else return -1; return 0; } early_param("idle", idle_setup); unsigned long arch_align_stack(unsigned long sp) { if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space) sp -= get_random_int() % 8192; return sp & ~0xf; } unsigned long arch_randomize_brk(struct mm_struct *mm) { return randomize_page(mm->brk, 0x02000000); } /* * Called from fs/proc with a reference on @p to find the function * which called into schedule(). This needs to be done carefully * because the task might wake up and we might look at a stack * changing under us. */ unsigned long get_wchan(struct task_struct *p) { unsigned long start, bottom, top, sp, fp, ip, ret = 0; int count = 0; if (p == current || p->state == TASK_RUNNING) return 0; if (!try_get_task_stack(p)) return 0; start = (unsigned long)task_stack_page(p); if (!start) goto out; /* * Layout of the stack page: * * ----------- topmax = start + THREAD_SIZE - sizeof(unsigned long) * PADDING * ----------- top = topmax - TOP_OF_KERNEL_STACK_PADDING * stack * ----------- bottom = start * * The tasks stack pointer points at the location where the * framepointer is stored. The data on the stack is: * ... IP FP ... IP FP * * We need to read FP and IP, so we need to adjust the upper * bound by another unsigned long. */ top = start + THREAD_SIZE - TOP_OF_KERNEL_STACK_PADDING; top -= 2 * sizeof(unsigned long); bottom = start; sp = READ_ONCE(p->thread.sp); if (sp < bottom || sp > top) goto out; fp = READ_ONCE_NOCHECK(((struct inactive_task_frame *)sp)->bp); do { if (fp < bottom || fp > top) goto out; ip = READ_ONCE_NOCHECK(*(unsigned long *)(fp + sizeof(unsigned long))); if (!in_sched_functions(ip)) { ret = ip; goto out; } fp = READ_ONCE_NOCHECK(*(unsigned long *)fp); } while (count++ < 16 && p->state != TASK_RUNNING); out: put_task_stack(p); return ret; } long do_arch_prctl_common(struct task_struct *task, int option, unsigned long cpuid_enabled) { switch (option) { case ARCH_GET_CPUID: return get_cpuid_mode(); case ARCH_SET_CPUID: return set_cpuid_mode(task, cpuid_enabled); } return -EINVAL; }
./CrossVul/dataset_final_sorted/CWE-276/c/bad_4225_4
crossvul-cpp_data_good_4225_3
// SPDX-License-Identifier: GPL-2.0-or-later /* Paravirtualization interfaces Copyright (C) 2006 Rusty Russell IBM Corporation 2007 - x86_64 support added by Glauber de Oliveira Costa, Red Hat Inc */ #include <linux/errno.h> #include <linux/init.h> #include <linux/export.h> #include <linux/efi.h> #include <linux/bcd.h> #include <linux/highmem.h> #include <linux/kprobes.h> #include <linux/pgtable.h> #include <asm/bug.h> #include <asm/paravirt.h> #include <asm/debugreg.h> #include <asm/desc.h> #include <asm/setup.h> #include <asm/time.h> #include <asm/pgalloc.h> #include <asm/irq.h> #include <asm/delay.h> #include <asm/fixmap.h> #include <asm/apic.h> #include <asm/tlbflush.h> #include <asm/timer.h> #include <asm/special_insns.h> #include <asm/tlb.h> #include <asm/io_bitmap.h> /* * nop stub, which must not clobber anything *including the stack* to * avoid confusing the entry prologues. */ extern void _paravirt_nop(void); asm (".pushsection .entry.text, \"ax\"\n" ".global _paravirt_nop\n" "_paravirt_nop:\n\t" "ret\n\t" ".size _paravirt_nop, . - _paravirt_nop\n\t" ".type _paravirt_nop, @function\n\t" ".popsection"); void __init default_banner(void) { printk(KERN_INFO "Booting paravirtualized kernel on %s\n", pv_info.name); } /* Undefined instruction for dealing with missing ops pointers. */ static const unsigned char ud2a[] = { 0x0f, 0x0b }; struct branch { unsigned char opcode; u32 delta; } __attribute__((packed)); static unsigned paravirt_patch_call(void *insn_buff, const void *target, unsigned long addr, unsigned len) { const int call_len = 5; struct branch *b = insn_buff; unsigned long delta = (unsigned long)target - (addr+call_len); if (len < call_len) { pr_warn("paravirt: Failed to patch indirect CALL at %ps\n", (void *)addr); /* Kernel might not be viable if patching fails, bail out: */ BUG_ON(1); } b->opcode = 0xe8; /* call */ b->delta = delta; BUILD_BUG_ON(sizeof(*b) != call_len); return call_len; } #ifdef CONFIG_PARAVIRT_XXL /* identity function, which can be inlined */ u64 notrace _paravirt_ident_64(u64 x) { return x; } static unsigned paravirt_patch_jmp(void *insn_buff, const void *target, unsigned long addr, unsigned len) { struct branch *b = insn_buff; unsigned long delta = (unsigned long)target - (addr+5); if (len < 5) { #ifdef CONFIG_RETPOLINE WARN_ONCE(1, "Failing to patch indirect JMP in %ps\n", (void *)addr); #endif return len; /* call too long for patch site */ } b->opcode = 0xe9; /* jmp */ b->delta = delta; return 5; } #endif DEFINE_STATIC_KEY_TRUE(virt_spin_lock_key); void __init native_pv_lock_init(void) { if (!boot_cpu_has(X86_FEATURE_HYPERVISOR)) static_branch_disable(&virt_spin_lock_key); } unsigned paravirt_patch_default(u8 type, void *insn_buff, unsigned long addr, unsigned len) { /* * Neat trick to map patch type back to the call within the * corresponding structure. */ void *opfunc = *((void **)&pv_ops + type); unsigned ret; if (opfunc == NULL) /* If there's no function, patch it with a ud2a (BUG) */ ret = paravirt_patch_insns(insn_buff, len, ud2a, ud2a+sizeof(ud2a)); else if (opfunc == _paravirt_nop) ret = 0; #ifdef CONFIG_PARAVIRT_XXL /* identity functions just return their single argument */ else if (opfunc == _paravirt_ident_64) ret = paravirt_patch_ident_64(insn_buff, len); else if (type == PARAVIRT_PATCH(cpu.iret) || type == PARAVIRT_PATCH(cpu.usergs_sysret64)) /* If operation requires a jmp, then jmp */ ret = paravirt_patch_jmp(insn_buff, opfunc, addr, len); #endif else /* Otherwise call the function. */ ret = paravirt_patch_call(insn_buff, opfunc, addr, len); return ret; } unsigned paravirt_patch_insns(void *insn_buff, unsigned len, const char *start, const char *end) { unsigned insn_len = end - start; /* Alternative instruction is too large for the patch site and we cannot continue: */ BUG_ON(insn_len > len || start == NULL); memcpy(insn_buff, start, insn_len); return insn_len; } struct static_key paravirt_steal_enabled; struct static_key paravirt_steal_rq_enabled; static u64 native_steal_clock(int cpu) { return 0; } /* These are in entry.S */ extern void native_iret(void); extern void native_usergs_sysret64(void); static struct resource reserve_ioports = { .start = 0, .end = IO_SPACE_LIMIT, .name = "paravirt-ioport", .flags = IORESOURCE_IO | IORESOURCE_BUSY, }; /* * Reserve the whole legacy IO space to prevent any legacy drivers * from wasting time probing for their hardware. This is a fairly * brute-force approach to disabling all non-virtual drivers. * * Note that this must be called very early to have any effect. */ int paravirt_disable_iospace(void) { return request_resource(&ioport_resource, &reserve_ioports); } static DEFINE_PER_CPU(enum paravirt_lazy_mode, paravirt_lazy_mode) = PARAVIRT_LAZY_NONE; static inline void enter_lazy(enum paravirt_lazy_mode mode) { BUG_ON(this_cpu_read(paravirt_lazy_mode) != PARAVIRT_LAZY_NONE); this_cpu_write(paravirt_lazy_mode, mode); } static void leave_lazy(enum paravirt_lazy_mode mode) { BUG_ON(this_cpu_read(paravirt_lazy_mode) != mode); this_cpu_write(paravirt_lazy_mode, PARAVIRT_LAZY_NONE); } void paravirt_enter_lazy_mmu(void) { enter_lazy(PARAVIRT_LAZY_MMU); } void paravirt_leave_lazy_mmu(void) { leave_lazy(PARAVIRT_LAZY_MMU); } void paravirt_flush_lazy_mmu(void) { preempt_disable(); if (paravirt_get_lazy_mode() == PARAVIRT_LAZY_MMU) { arch_leave_lazy_mmu_mode(); arch_enter_lazy_mmu_mode(); } preempt_enable(); } #ifdef CONFIG_PARAVIRT_XXL void paravirt_start_context_switch(struct task_struct *prev) { BUG_ON(preemptible()); if (this_cpu_read(paravirt_lazy_mode) == PARAVIRT_LAZY_MMU) { arch_leave_lazy_mmu_mode(); set_ti_thread_flag(task_thread_info(prev), TIF_LAZY_MMU_UPDATES); } enter_lazy(PARAVIRT_LAZY_CPU); } void paravirt_end_context_switch(struct task_struct *next) { BUG_ON(preemptible()); leave_lazy(PARAVIRT_LAZY_CPU); if (test_and_clear_ti_thread_flag(task_thread_info(next), TIF_LAZY_MMU_UPDATES)) arch_enter_lazy_mmu_mode(); } #endif enum paravirt_lazy_mode paravirt_get_lazy_mode(void) { if (in_interrupt()) return PARAVIRT_LAZY_NONE; return this_cpu_read(paravirt_lazy_mode); } struct pv_info pv_info = { .name = "bare hardware", #ifdef CONFIG_PARAVIRT_XXL .kernel_rpl = 0, .shared_kernel_pmd = 1, /* Only used when CONFIG_X86_PAE is set */ #ifdef CONFIG_X86_64 .extra_user_64bit_cs = __USER_CS, #endif #endif }; /* 64-bit pagetable entries */ #define PTE_IDENT __PV_IS_CALLEE_SAVE(_paravirt_ident_64) struct paravirt_patch_template pv_ops = { /* Init ops. */ .init.patch = native_patch, /* Time ops. */ .time.sched_clock = native_sched_clock, .time.steal_clock = native_steal_clock, /* Cpu ops. */ .cpu.io_delay = native_io_delay, #ifdef CONFIG_PARAVIRT_XXL .cpu.cpuid = native_cpuid, .cpu.get_debugreg = native_get_debugreg, .cpu.set_debugreg = native_set_debugreg, .cpu.read_cr0 = native_read_cr0, .cpu.write_cr0 = native_write_cr0, .cpu.write_cr4 = native_write_cr4, .cpu.wbinvd = native_wbinvd, .cpu.read_msr = native_read_msr, .cpu.write_msr = native_write_msr, .cpu.read_msr_safe = native_read_msr_safe, .cpu.write_msr_safe = native_write_msr_safe, .cpu.read_pmc = native_read_pmc, .cpu.load_tr_desc = native_load_tr_desc, .cpu.set_ldt = native_set_ldt, .cpu.load_gdt = native_load_gdt, .cpu.load_idt = native_load_idt, .cpu.store_tr = native_store_tr, .cpu.load_tls = native_load_tls, #ifdef CONFIG_X86_64 .cpu.load_gs_index = native_load_gs_index, #endif .cpu.write_ldt_entry = native_write_ldt_entry, .cpu.write_gdt_entry = native_write_gdt_entry, .cpu.write_idt_entry = native_write_idt_entry, .cpu.alloc_ldt = paravirt_nop, .cpu.free_ldt = paravirt_nop, .cpu.load_sp0 = native_load_sp0, #ifdef CONFIG_X86_64 .cpu.usergs_sysret64 = native_usergs_sysret64, #endif .cpu.iret = native_iret, .cpu.swapgs = native_swapgs, #ifdef CONFIG_X86_IOPL_IOPERM .cpu.invalidate_io_bitmap = native_tss_invalidate_io_bitmap, .cpu.update_io_bitmap = native_tss_update_io_bitmap, #endif .cpu.start_context_switch = paravirt_nop, .cpu.end_context_switch = paravirt_nop, /* Irq ops. */ .irq.save_fl = __PV_IS_CALLEE_SAVE(native_save_fl), .irq.restore_fl = __PV_IS_CALLEE_SAVE(native_restore_fl), .irq.irq_disable = __PV_IS_CALLEE_SAVE(native_irq_disable), .irq.irq_enable = __PV_IS_CALLEE_SAVE(native_irq_enable), .irq.safe_halt = native_safe_halt, .irq.halt = native_halt, #endif /* CONFIG_PARAVIRT_XXL */ /* Mmu ops. */ .mmu.flush_tlb_user = native_flush_tlb_local, .mmu.flush_tlb_kernel = native_flush_tlb_global, .mmu.flush_tlb_one_user = native_flush_tlb_one_user, .mmu.flush_tlb_others = native_flush_tlb_others, .mmu.tlb_remove_table = (void (*)(struct mmu_gather *, void *))tlb_remove_page, .mmu.exit_mmap = paravirt_nop, #ifdef CONFIG_PARAVIRT_XXL .mmu.read_cr2 = __PV_IS_CALLEE_SAVE(native_read_cr2), .mmu.write_cr2 = native_write_cr2, .mmu.read_cr3 = __native_read_cr3, .mmu.write_cr3 = native_write_cr3, .mmu.pgd_alloc = __paravirt_pgd_alloc, .mmu.pgd_free = paravirt_nop, .mmu.alloc_pte = paravirt_nop, .mmu.alloc_pmd = paravirt_nop, .mmu.alloc_pud = paravirt_nop, .mmu.alloc_p4d = paravirt_nop, .mmu.release_pte = paravirt_nop, .mmu.release_pmd = paravirt_nop, .mmu.release_pud = paravirt_nop, .mmu.release_p4d = paravirt_nop, .mmu.set_pte = native_set_pte, .mmu.set_pte_at = native_set_pte_at, .mmu.set_pmd = native_set_pmd, .mmu.ptep_modify_prot_start = __ptep_modify_prot_start, .mmu.ptep_modify_prot_commit = __ptep_modify_prot_commit, #if CONFIG_PGTABLE_LEVELS >= 3 #ifdef CONFIG_X86_PAE .mmu.set_pte_atomic = native_set_pte_atomic, .mmu.pte_clear = native_pte_clear, .mmu.pmd_clear = native_pmd_clear, #endif .mmu.set_pud = native_set_pud, .mmu.pmd_val = PTE_IDENT, .mmu.make_pmd = PTE_IDENT, #if CONFIG_PGTABLE_LEVELS >= 4 .mmu.pud_val = PTE_IDENT, .mmu.make_pud = PTE_IDENT, .mmu.set_p4d = native_set_p4d, #if CONFIG_PGTABLE_LEVELS >= 5 .mmu.p4d_val = PTE_IDENT, .mmu.make_p4d = PTE_IDENT, .mmu.set_pgd = native_set_pgd, #endif /* CONFIG_PGTABLE_LEVELS >= 5 */ #endif /* CONFIG_PGTABLE_LEVELS >= 4 */ #endif /* CONFIG_PGTABLE_LEVELS >= 3 */ .mmu.pte_val = PTE_IDENT, .mmu.pgd_val = PTE_IDENT, .mmu.make_pte = PTE_IDENT, .mmu.make_pgd = PTE_IDENT, .mmu.dup_mmap = paravirt_nop, .mmu.activate_mm = paravirt_nop, .mmu.lazy_mode = { .enter = paravirt_nop, .leave = paravirt_nop, .flush = paravirt_nop, }, .mmu.set_fixmap = native_set_fixmap, #endif /* CONFIG_PARAVIRT_XXL */ #if defined(CONFIG_PARAVIRT_SPINLOCKS) /* Lock ops. */ #ifdef CONFIG_SMP .lock.queued_spin_lock_slowpath = native_queued_spin_lock_slowpath, .lock.queued_spin_unlock = PV_CALLEE_SAVE(__native_queued_spin_unlock), .lock.wait = paravirt_nop, .lock.kick = paravirt_nop, .lock.vcpu_is_preempted = PV_CALLEE_SAVE(__native_vcpu_is_preempted), #endif /* SMP */ #endif }; #ifdef CONFIG_PARAVIRT_XXL /* At this point, native_get/set_debugreg has real function entries */ NOKPROBE_SYMBOL(native_get_debugreg); NOKPROBE_SYMBOL(native_set_debugreg); NOKPROBE_SYMBOL(native_load_idt); #endif EXPORT_SYMBOL(pv_ops); EXPORT_SYMBOL_GPL(pv_info);
./CrossVul/dataset_final_sorted/CWE-276/c/good_4225_3
crossvul-cpp_data_good_4309_0
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 2011 Instituto Nokia de Tecnologia * * Authors: * Aloisio Almeida Jr <aloisio.almeida@openbossa.org> * Lauro Ramos Venancio <lauro.venancio@openbossa.org> */ #define pr_fmt(fmt) KBUILD_MODNAME ": %s: " fmt, __func__ #include <net/tcp_states.h> #include <linux/nfc.h> #include <linux/export.h> #include "nfc.h" static struct nfc_sock_list raw_sk_list = { .lock = __RW_LOCK_UNLOCKED(raw_sk_list.lock) }; static void nfc_sock_link(struct nfc_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_add_node(sk, &l->head); write_unlock(&l->lock); } static void nfc_sock_unlink(struct nfc_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_del_node_init(sk); write_unlock(&l->lock); } static void rawsock_write_queue_purge(struct sock *sk) { pr_debug("sk=%p\n", sk); spin_lock_bh(&sk->sk_write_queue.lock); __skb_queue_purge(&sk->sk_write_queue); nfc_rawsock(sk)->tx_work_scheduled = false; spin_unlock_bh(&sk->sk_write_queue.lock); } static void rawsock_report_error(struct sock *sk, int err) { pr_debug("sk=%p err=%d\n", sk, err); sk->sk_shutdown = SHUTDOWN_MASK; sk->sk_err = -err; sk->sk_error_report(sk); rawsock_write_queue_purge(sk); } static int rawsock_release(struct socket *sock) { struct sock *sk = sock->sk; pr_debug("sock=%p sk=%p\n", sock, sk); if (!sk) return 0; if (sock->type == SOCK_RAW) nfc_sock_unlink(&raw_sk_list, sk); sock_orphan(sk); sock_put(sk); return 0; } static int rawsock_connect(struct socket *sock, struct sockaddr *_addr, int len, int flags) { struct sock *sk = sock->sk; struct sockaddr_nfc *addr = (struct sockaddr_nfc *)_addr; struct nfc_dev *dev; int rc = 0; pr_debug("sock=%p sk=%p flags=%d\n", sock, sk, flags); if (!addr || len < sizeof(struct sockaddr_nfc) || addr->sa_family != AF_NFC) return -EINVAL; pr_debug("addr dev_idx=%u target_idx=%u protocol=%u\n", addr->dev_idx, addr->target_idx, addr->nfc_protocol); lock_sock(sk); if (sock->state == SS_CONNECTED) { rc = -EISCONN; goto error; } dev = nfc_get_device(addr->dev_idx); if (!dev) { rc = -ENODEV; goto error; } if (addr->target_idx > dev->target_next_idx - 1 || addr->target_idx < dev->target_next_idx - dev->n_targets) { rc = -EINVAL; goto error; } rc = nfc_activate_target(dev, addr->target_idx, addr->nfc_protocol); if (rc) goto put_dev; nfc_rawsock(sk)->dev = dev; nfc_rawsock(sk)->target_idx = addr->target_idx; sock->state = SS_CONNECTED; sk->sk_state = TCP_ESTABLISHED; sk->sk_state_change(sk); release_sock(sk); return 0; put_dev: nfc_put_device(dev); error: release_sock(sk); return rc; } static int rawsock_add_header(struct sk_buff *skb) { *(u8 *)skb_push(skb, NFC_HEADER_SIZE) = 0; return 0; } static void rawsock_data_exchange_complete(void *context, struct sk_buff *skb, int err) { struct sock *sk = (struct sock *) context; BUG_ON(in_irq()); pr_debug("sk=%p err=%d\n", sk, err); if (err) goto error; err = rawsock_add_header(skb); if (err) goto error_skb; err = sock_queue_rcv_skb(sk, skb); if (err) goto error_skb; spin_lock_bh(&sk->sk_write_queue.lock); if (!skb_queue_empty(&sk->sk_write_queue)) schedule_work(&nfc_rawsock(sk)->tx_work); else nfc_rawsock(sk)->tx_work_scheduled = false; spin_unlock_bh(&sk->sk_write_queue.lock); sock_put(sk); return; error_skb: kfree_skb(skb); error: rawsock_report_error(sk, err); sock_put(sk); } static void rawsock_tx_work(struct work_struct *work) { struct sock *sk = to_rawsock_sk(work); struct nfc_dev *dev = nfc_rawsock(sk)->dev; u32 target_idx = nfc_rawsock(sk)->target_idx; struct sk_buff *skb; int rc; pr_debug("sk=%p target_idx=%u\n", sk, target_idx); if (sk->sk_shutdown & SEND_SHUTDOWN) { rawsock_write_queue_purge(sk); return; } skb = skb_dequeue(&sk->sk_write_queue); sock_hold(sk); rc = nfc_data_exchange(dev, target_idx, skb, rawsock_data_exchange_complete, sk); if (rc) { rawsock_report_error(sk, rc); sock_put(sk); } } static int rawsock_sendmsg(struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct nfc_dev *dev = nfc_rawsock(sk)->dev; struct sk_buff *skb; int rc; pr_debug("sock=%p sk=%p len=%zu\n", sock, sk, len); if (msg->msg_namelen) return -EOPNOTSUPP; if (sock->state != SS_CONNECTED) return -ENOTCONN; skb = nfc_alloc_send_skb(dev, sk, msg->msg_flags, len, &rc); if (skb == NULL) return rc; rc = memcpy_from_msg(skb_put(skb, len), msg, len); if (rc < 0) { kfree_skb(skb); return rc; } spin_lock_bh(&sk->sk_write_queue.lock); __skb_queue_tail(&sk->sk_write_queue, skb); if (!nfc_rawsock(sk)->tx_work_scheduled) { schedule_work(&nfc_rawsock(sk)->tx_work); nfc_rawsock(sk)->tx_work_scheduled = true; } spin_unlock_bh(&sk->sk_write_queue.lock); return len; } static int rawsock_recvmsg(struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; struct sk_buff *skb; int copied; int rc; pr_debug("sock=%p sk=%p len=%zu flags=%d\n", sock, sk, len, flags); skb = skb_recv_datagram(sk, flags, noblock, &rc); if (!skb) return rc; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } rc = skb_copy_datagram_msg(skb, 0, msg, copied); skb_free_datagram(sk, skb); return rc ? : copied; } static const struct proto_ops rawsock_ops = { .family = PF_NFC, .owner = THIS_MODULE, .release = rawsock_release, .bind = sock_no_bind, .connect = rawsock_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .poll = datagram_poll, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .sendmsg = rawsock_sendmsg, .recvmsg = rawsock_recvmsg, .mmap = sock_no_mmap, }; static const struct proto_ops rawsock_raw_ops = { .family = PF_NFC, .owner = THIS_MODULE, .release = rawsock_release, .bind = sock_no_bind, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .poll = datagram_poll, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .sendmsg = sock_no_sendmsg, .recvmsg = rawsock_recvmsg, .mmap = sock_no_mmap, }; static void rawsock_destruct(struct sock *sk) { pr_debug("sk=%p\n", sk); if (sk->sk_state == TCP_ESTABLISHED) { nfc_deactivate_target(nfc_rawsock(sk)->dev, nfc_rawsock(sk)->target_idx, NFC_TARGET_MODE_IDLE); nfc_put_device(nfc_rawsock(sk)->dev); } skb_queue_purge(&sk->sk_receive_queue); if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Freeing alive NFC raw socket %p\n", sk); return; } } static int rawsock_create(struct net *net, struct socket *sock, const struct nfc_protocol *nfc_proto, int kern) { struct sock *sk; pr_debug("sock=%p\n", sock); if ((sock->type != SOCK_SEQPACKET) && (sock->type != SOCK_RAW)) return -ESOCKTNOSUPPORT; if (sock->type == SOCK_RAW) { if (!capable(CAP_NET_RAW)) return -EPERM; sock->ops = &rawsock_raw_ops; } else { sock->ops = &rawsock_ops; } sk = sk_alloc(net, PF_NFC, GFP_ATOMIC, nfc_proto->proto, kern); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sk->sk_protocol = nfc_proto->id; sk->sk_destruct = rawsock_destruct; sock->state = SS_UNCONNECTED; if (sock->type == SOCK_RAW) nfc_sock_link(&raw_sk_list, sk); else { INIT_WORK(&nfc_rawsock(sk)->tx_work, rawsock_tx_work); nfc_rawsock(sk)->tx_work_scheduled = false; } return 0; } void nfc_send_to_raw_sock(struct nfc_dev *dev, struct sk_buff *skb, u8 payload_type, u8 direction) { struct sk_buff *skb_copy = NULL, *nskb; struct sock *sk; u8 *data; read_lock(&raw_sk_list.lock); sk_for_each(sk, &raw_sk_list.head) { if (!skb_copy) { skb_copy = __pskb_copy_fclone(skb, NFC_RAW_HEADER_SIZE, GFP_ATOMIC, true); if (!skb_copy) continue; data = skb_push(skb_copy, NFC_RAW_HEADER_SIZE); data[0] = dev ? dev->idx : 0xFF; data[1] = direction & 0x01; data[1] |= (payload_type << 1); } nskb = skb_clone(skb_copy, GFP_ATOMIC); if (!nskb) continue; if (sock_queue_rcv_skb(sk, nskb)) kfree_skb(nskb); } read_unlock(&raw_sk_list.lock); kfree_skb(skb_copy); } EXPORT_SYMBOL(nfc_send_to_raw_sock); static struct proto rawsock_proto = { .name = "NFC_RAW", .owner = THIS_MODULE, .obj_size = sizeof(struct nfc_rawsock), }; static const struct nfc_protocol rawsock_nfc_proto = { .id = NFC_SOCKPROTO_RAW, .proto = &rawsock_proto, .owner = THIS_MODULE, .create = rawsock_create }; int __init rawsock_init(void) { int rc; rc = nfc_proto_register(&rawsock_nfc_proto); return rc; } void rawsock_exit(void) { nfc_proto_unregister(&rawsock_nfc_proto); }
./CrossVul/dataset_final_sorted/CWE-276/c/good_4309_0
crossvul-cpp_data_good_4225_4
// SPDX-License-Identifier: GPL-2.0 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/errno.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/smp.h> #include <linux/prctl.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/sched/idle.h> #include <linux/sched/debug.h> #include <linux/sched/task.h> #include <linux/sched/task_stack.h> #include <linux/init.h> #include <linux/export.h> #include <linux/pm.h> #include <linux/tick.h> #include <linux/random.h> #include <linux/user-return-notifier.h> #include <linux/dmi.h> #include <linux/utsname.h> #include <linux/stackprotector.h> #include <linux/cpuidle.h> #include <linux/acpi.h> #include <linux/elf-randomize.h> #include <trace/events/power.h> #include <linux/hw_breakpoint.h> #include <asm/cpu.h> #include <asm/apic.h> #include <linux/uaccess.h> #include <asm/mwait.h> #include <asm/fpu/internal.h> #include <asm/debugreg.h> #include <asm/nmi.h> #include <asm/tlbflush.h> #include <asm/mce.h> #include <asm/vm86.h> #include <asm/switch_to.h> #include <asm/desc.h> #include <asm/prctl.h> #include <asm/spec-ctrl.h> #include <asm/io_bitmap.h> #include <asm/proto.h> #include "process.h" /* * per-CPU TSS segments. Threads are completely 'soft' on Linux, * no more per-task TSS's. The TSS size is kept cacheline-aligned * so they are allowed to end up in the .data..cacheline_aligned * section. Since TSS's are completely CPU-local, we want them * on exact cacheline boundaries, to eliminate cacheline ping-pong. */ __visible DEFINE_PER_CPU_PAGE_ALIGNED(struct tss_struct, cpu_tss_rw) = { .x86_tss = { /* * .sp0 is only used when entering ring 0 from a lower * privilege level. Since the init task never runs anything * but ring 0 code, there is no need for a valid value here. * Poison it. */ .sp0 = (1UL << (BITS_PER_LONG-1)) + 1, /* * .sp1 is cpu_current_top_of_stack. The init task never * runs user code, but cpu_current_top_of_stack should still * be well defined before the first context switch. */ .sp1 = TOP_OF_INIT_STACK, #ifdef CONFIG_X86_32 .ss0 = __KERNEL_DS, .ss1 = __KERNEL_CS, #endif .io_bitmap_base = IO_BITMAP_OFFSET_INVALID, }, }; EXPORT_PER_CPU_SYMBOL(cpu_tss_rw); DEFINE_PER_CPU(bool, __tss_limit_invalid); EXPORT_PER_CPU_SYMBOL_GPL(__tss_limit_invalid); /* * this gets called so that we can store lazy state into memory and copy the * current task into the new thread. */ int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src) { memcpy(dst, src, arch_task_struct_size); #ifdef CONFIG_VM86 dst->thread.vm86 = NULL; #endif return fpu__copy(dst, src); } /* * Free thread data structures etc.. */ void exit_thread(struct task_struct *tsk) { struct thread_struct *t = &tsk->thread; struct fpu *fpu = &t->fpu; if (test_thread_flag(TIF_IO_BITMAP)) io_bitmap_exit(tsk); free_vm86(t); fpu__drop(fpu); } static int set_new_tls(struct task_struct *p, unsigned long tls) { struct user_desc __user *utls = (struct user_desc __user *)tls; if (in_ia32_syscall()) return do_set_thread_area(p, -1, utls, 0); else return do_set_thread_area_64(p, ARCH_SET_FS, tls); } int copy_thread_tls(unsigned long clone_flags, unsigned long sp, unsigned long arg, struct task_struct *p, unsigned long tls) { struct inactive_task_frame *frame; struct fork_frame *fork_frame; struct pt_regs *childregs; int ret = 0; childregs = task_pt_regs(p); fork_frame = container_of(childregs, struct fork_frame, regs); frame = &fork_frame->frame; frame->bp = 0; frame->ret_addr = (unsigned long) ret_from_fork; p->thread.sp = (unsigned long) fork_frame; p->thread.io_bitmap = NULL; memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps)); #ifdef CONFIG_X86_64 savesegment(gs, p->thread.gsindex); p->thread.gsbase = p->thread.gsindex ? 0 : current->thread.gsbase; savesegment(fs, p->thread.fsindex); p->thread.fsbase = p->thread.fsindex ? 0 : current->thread.fsbase; savesegment(es, p->thread.es); savesegment(ds, p->thread.ds); #else p->thread.sp0 = (unsigned long) (childregs + 1); /* * Clear all status flags including IF and set fixed bit. 64bit * does not have this initialization as the frame does not contain * flags. The flags consistency (especially vs. AC) is there * ensured via objtool, which lacks 32bit support. */ frame->flags = X86_EFLAGS_FIXED; #endif /* Kernel thread ? */ if (unlikely(p->flags & PF_KTHREAD)) { memset(childregs, 0, sizeof(struct pt_regs)); kthread_frame_init(frame, sp, arg); return 0; } frame->bx = 0; *childregs = *current_pt_regs(); childregs->ax = 0; if (sp) childregs->sp = sp; #ifdef CONFIG_X86_32 task_user_gs(p) = get_user_gs(current_pt_regs()); #endif /* Set a new TLS for the child thread? */ if (clone_flags & CLONE_SETTLS) ret = set_new_tls(p, tls); if (!ret && unlikely(test_tsk_thread_flag(current, TIF_IO_BITMAP))) io_bitmap_share(p); return ret; } void flush_thread(void) { struct task_struct *tsk = current; flush_ptrace_hw_breakpoint(tsk); memset(tsk->thread.tls_array, 0, sizeof(tsk->thread.tls_array)); fpu__clear_all(&tsk->thread.fpu); } void disable_TSC(void) { preempt_disable(); if (!test_and_set_thread_flag(TIF_NOTSC)) /* * Must flip the CPU state synchronously with * TIF_NOTSC in the current running context. */ cr4_set_bits(X86_CR4_TSD); preempt_enable(); } static void enable_TSC(void) { preempt_disable(); if (test_and_clear_thread_flag(TIF_NOTSC)) /* * Must flip the CPU state synchronously with * TIF_NOTSC in the current running context. */ cr4_clear_bits(X86_CR4_TSD); preempt_enable(); } int get_tsc_mode(unsigned long adr) { unsigned int val; if (test_thread_flag(TIF_NOTSC)) val = PR_TSC_SIGSEGV; else val = PR_TSC_ENABLE; return put_user(val, (unsigned int __user *)adr); } int set_tsc_mode(unsigned int val) { if (val == PR_TSC_SIGSEGV) disable_TSC(); else if (val == PR_TSC_ENABLE) enable_TSC(); else return -EINVAL; return 0; } DEFINE_PER_CPU(u64, msr_misc_features_shadow); static void set_cpuid_faulting(bool on) { u64 msrval; msrval = this_cpu_read(msr_misc_features_shadow); msrval &= ~MSR_MISC_FEATURES_ENABLES_CPUID_FAULT; msrval |= (on << MSR_MISC_FEATURES_ENABLES_CPUID_FAULT_BIT); this_cpu_write(msr_misc_features_shadow, msrval); wrmsrl(MSR_MISC_FEATURES_ENABLES, msrval); } static void disable_cpuid(void) { preempt_disable(); if (!test_and_set_thread_flag(TIF_NOCPUID)) { /* * Must flip the CPU state synchronously with * TIF_NOCPUID in the current running context. */ set_cpuid_faulting(true); } preempt_enable(); } static void enable_cpuid(void) { preempt_disable(); if (test_and_clear_thread_flag(TIF_NOCPUID)) { /* * Must flip the CPU state synchronously with * TIF_NOCPUID in the current running context. */ set_cpuid_faulting(false); } preempt_enable(); } static int get_cpuid_mode(void) { return !test_thread_flag(TIF_NOCPUID); } static int set_cpuid_mode(struct task_struct *task, unsigned long cpuid_enabled) { if (!boot_cpu_has(X86_FEATURE_CPUID_FAULT)) return -ENODEV; if (cpuid_enabled) enable_cpuid(); else disable_cpuid(); return 0; } /* * Called immediately after a successful exec. */ void arch_setup_new_exec(void) { /* If cpuid was previously disabled for this task, re-enable it. */ if (test_thread_flag(TIF_NOCPUID)) enable_cpuid(); /* * Don't inherit TIF_SSBD across exec boundary when * PR_SPEC_DISABLE_NOEXEC is used. */ if (test_thread_flag(TIF_SSBD) && task_spec_ssb_noexec(current)) { clear_thread_flag(TIF_SSBD); task_clear_spec_ssb_disable(current); task_clear_spec_ssb_noexec(current); speculation_ctrl_update(task_thread_info(current)->flags); } } #ifdef CONFIG_X86_IOPL_IOPERM static inline void switch_to_bitmap(unsigned long tifp) { /* * Invalidate I/O bitmap if the previous task used it. This prevents * any possible leakage of an active I/O bitmap. * * If the next task has an I/O bitmap it will handle it on exit to * user mode. */ if (tifp & _TIF_IO_BITMAP) tss_invalidate_io_bitmap(); } static void tss_copy_io_bitmap(struct tss_struct *tss, struct io_bitmap *iobm) { /* * Copy at least the byte range of the incoming tasks bitmap which * covers the permitted I/O ports. * * If the previous task which used an I/O bitmap had more bits * permitted, then the copy needs to cover those as well so they * get turned off. */ memcpy(tss->io_bitmap.bitmap, iobm->bitmap, max(tss->io_bitmap.prev_max, iobm->max)); /* * Store the new max and the sequence number of this bitmap * and a pointer to the bitmap itself. */ tss->io_bitmap.prev_max = iobm->max; tss->io_bitmap.prev_sequence = iobm->sequence; } /** * tss_update_io_bitmap - Update I/O bitmap before exiting to usermode */ void native_tss_update_io_bitmap(void) { struct tss_struct *tss = this_cpu_ptr(&cpu_tss_rw); struct thread_struct *t = &current->thread; u16 *base = &tss->x86_tss.io_bitmap_base; if (!test_thread_flag(TIF_IO_BITMAP)) { native_tss_invalidate_io_bitmap(); return; } if (IS_ENABLED(CONFIG_X86_IOPL_IOPERM) && t->iopl_emul == 3) { *base = IO_BITMAP_OFFSET_VALID_ALL; } else { struct io_bitmap *iobm = t->io_bitmap; /* * Only copy bitmap data when the sequence number differs. The * update time is accounted to the incoming task. */ if (tss->io_bitmap.prev_sequence != iobm->sequence) tss_copy_io_bitmap(tss, iobm); /* Enable the bitmap */ *base = IO_BITMAP_OFFSET_VALID_MAP; } /* * Make sure that the TSS limit is covering the IO bitmap. It might have * been cut down by a VMEXIT to 0x67 which would cause a subsequent I/O * access from user space to trigger a #GP because tbe bitmap is outside * the TSS limit. */ refresh_tss_limit(); } #else /* CONFIG_X86_IOPL_IOPERM */ static inline void switch_to_bitmap(unsigned long tifp) { } #endif #ifdef CONFIG_SMP struct ssb_state { struct ssb_state *shared_state; raw_spinlock_t lock; unsigned int disable_state; unsigned long local_state; }; #define LSTATE_SSB 0 static DEFINE_PER_CPU(struct ssb_state, ssb_state); void speculative_store_bypass_ht_init(void) { struct ssb_state *st = this_cpu_ptr(&ssb_state); unsigned int this_cpu = smp_processor_id(); unsigned int cpu; st->local_state = 0; /* * Shared state setup happens once on the first bringup * of the CPU. It's not destroyed on CPU hotunplug. */ if (st->shared_state) return; raw_spin_lock_init(&st->lock); /* * Go over HT siblings and check whether one of them has set up the * shared state pointer already. */ for_each_cpu(cpu, topology_sibling_cpumask(this_cpu)) { if (cpu == this_cpu) continue; if (!per_cpu(ssb_state, cpu).shared_state) continue; /* Link it to the state of the sibling: */ st->shared_state = per_cpu(ssb_state, cpu).shared_state; return; } /* * First HT sibling to come up on the core. Link shared state of * the first HT sibling to itself. The siblings on the same core * which come up later will see the shared state pointer and link * themself to the state of this CPU. */ st->shared_state = st; } /* * Logic is: First HT sibling enables SSBD for both siblings in the core * and last sibling to disable it, disables it for the whole core. This how * MSR_SPEC_CTRL works in "hardware": * * CORE_SPEC_CTRL = THREAD0_SPEC_CTRL | THREAD1_SPEC_CTRL */ static __always_inline void amd_set_core_ssb_state(unsigned long tifn) { struct ssb_state *st = this_cpu_ptr(&ssb_state); u64 msr = x86_amd_ls_cfg_base; if (!static_cpu_has(X86_FEATURE_ZEN)) { msr |= ssbd_tif_to_amd_ls_cfg(tifn); wrmsrl(MSR_AMD64_LS_CFG, msr); return; } if (tifn & _TIF_SSBD) { /* * Since this can race with prctl(), block reentry on the * same CPU. */ if (__test_and_set_bit(LSTATE_SSB, &st->local_state)) return; msr |= x86_amd_ls_cfg_ssbd_mask; raw_spin_lock(&st->shared_state->lock); /* First sibling enables SSBD: */ if (!st->shared_state->disable_state) wrmsrl(MSR_AMD64_LS_CFG, msr); st->shared_state->disable_state++; raw_spin_unlock(&st->shared_state->lock); } else { if (!__test_and_clear_bit(LSTATE_SSB, &st->local_state)) return; raw_spin_lock(&st->shared_state->lock); st->shared_state->disable_state--; if (!st->shared_state->disable_state) wrmsrl(MSR_AMD64_LS_CFG, msr); raw_spin_unlock(&st->shared_state->lock); } } #else static __always_inline void amd_set_core_ssb_state(unsigned long tifn) { u64 msr = x86_amd_ls_cfg_base | ssbd_tif_to_amd_ls_cfg(tifn); wrmsrl(MSR_AMD64_LS_CFG, msr); } #endif static __always_inline void amd_set_ssb_virt_state(unsigned long tifn) { /* * SSBD has the same definition in SPEC_CTRL and VIRT_SPEC_CTRL, * so ssbd_tif_to_spec_ctrl() just works. */ wrmsrl(MSR_AMD64_VIRT_SPEC_CTRL, ssbd_tif_to_spec_ctrl(tifn)); } /* * Update the MSRs managing speculation control, during context switch. * * tifp: Previous task's thread flags * tifn: Next task's thread flags */ static __always_inline void __speculation_ctrl_update(unsigned long tifp, unsigned long tifn) { unsigned long tif_diff = tifp ^ tifn; u64 msr = x86_spec_ctrl_base; bool updmsr = false; lockdep_assert_irqs_disabled(); /* Handle change of TIF_SSBD depending on the mitigation method. */ if (static_cpu_has(X86_FEATURE_VIRT_SSBD)) { if (tif_diff & _TIF_SSBD) amd_set_ssb_virt_state(tifn); } else if (static_cpu_has(X86_FEATURE_LS_CFG_SSBD)) { if (tif_diff & _TIF_SSBD) amd_set_core_ssb_state(tifn); } else if (static_cpu_has(X86_FEATURE_SPEC_CTRL_SSBD) || static_cpu_has(X86_FEATURE_AMD_SSBD)) { updmsr |= !!(tif_diff & _TIF_SSBD); msr |= ssbd_tif_to_spec_ctrl(tifn); } /* Only evaluate TIF_SPEC_IB if conditional STIBP is enabled. */ if (IS_ENABLED(CONFIG_SMP) && static_branch_unlikely(&switch_to_cond_stibp)) { updmsr |= !!(tif_diff & _TIF_SPEC_IB); msr |= stibp_tif_to_spec_ctrl(tifn); } if (updmsr) wrmsrl(MSR_IA32_SPEC_CTRL, msr); } static unsigned long speculation_ctrl_update_tif(struct task_struct *tsk) { if (test_and_clear_tsk_thread_flag(tsk, TIF_SPEC_FORCE_UPDATE)) { if (task_spec_ssb_disable(tsk)) set_tsk_thread_flag(tsk, TIF_SSBD); else clear_tsk_thread_flag(tsk, TIF_SSBD); if (task_spec_ib_disable(tsk)) set_tsk_thread_flag(tsk, TIF_SPEC_IB); else clear_tsk_thread_flag(tsk, TIF_SPEC_IB); } /* Return the updated threadinfo flags*/ return task_thread_info(tsk)->flags; } void speculation_ctrl_update(unsigned long tif) { unsigned long flags; /* Forced update. Make sure all relevant TIF flags are different */ local_irq_save(flags); __speculation_ctrl_update(~tif, tif); local_irq_restore(flags); } /* Called from seccomp/prctl update */ void speculation_ctrl_update_current(void) { preempt_disable(); speculation_ctrl_update(speculation_ctrl_update_tif(current)); preempt_enable(); } static inline void cr4_toggle_bits_irqsoff(unsigned long mask) { unsigned long newval, cr4 = this_cpu_read(cpu_tlbstate.cr4); newval = cr4 ^ mask; if (newval != cr4) { this_cpu_write(cpu_tlbstate.cr4, newval); __write_cr4(newval); } } void __switch_to_xtra(struct task_struct *prev_p, struct task_struct *next_p) { unsigned long tifp, tifn; tifn = READ_ONCE(task_thread_info(next_p)->flags); tifp = READ_ONCE(task_thread_info(prev_p)->flags); switch_to_bitmap(tifp); propagate_user_return_notify(prev_p, next_p); if ((tifp & _TIF_BLOCKSTEP || tifn & _TIF_BLOCKSTEP) && arch_has_block_step()) { unsigned long debugctl, msk; rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl); debugctl &= ~DEBUGCTLMSR_BTF; msk = tifn & _TIF_BLOCKSTEP; debugctl |= (msk >> TIF_BLOCKSTEP) << DEBUGCTLMSR_BTF_SHIFT; wrmsrl(MSR_IA32_DEBUGCTLMSR, debugctl); } if ((tifp ^ tifn) & _TIF_NOTSC) cr4_toggle_bits_irqsoff(X86_CR4_TSD); if ((tifp ^ tifn) & _TIF_NOCPUID) set_cpuid_faulting(!!(tifn & _TIF_NOCPUID)); if (likely(!((tifp | tifn) & _TIF_SPEC_FORCE_UPDATE))) { __speculation_ctrl_update(tifp, tifn); } else { speculation_ctrl_update_tif(prev_p); tifn = speculation_ctrl_update_tif(next_p); /* Enforce MSR update to ensure consistent state */ __speculation_ctrl_update(~tifn, tifn); } if ((tifp ^ tifn) & _TIF_SLD) switch_to_sld(tifn); } /* * Idle related variables and functions */ unsigned long boot_option_idle_override = IDLE_NO_OVERRIDE; EXPORT_SYMBOL(boot_option_idle_override); static void (*x86_idle)(void); #ifndef CONFIG_SMP static inline void play_dead(void) { BUG(); } #endif void arch_cpu_idle_enter(void) { tsc_verify_tsc_adjust(false); local_touch_nmi(); } void arch_cpu_idle_dead(void) { play_dead(); } /* * Called from the generic idle code. */ void arch_cpu_idle(void) { x86_idle(); } /* * We use this if we don't have any better idle routine.. */ void __cpuidle default_idle(void) { trace_cpu_idle_rcuidle(1, smp_processor_id()); safe_halt(); trace_cpu_idle_rcuidle(PWR_EVENT_EXIT, smp_processor_id()); } #if defined(CONFIG_APM_MODULE) || defined(CONFIG_HALTPOLL_CPUIDLE_MODULE) EXPORT_SYMBOL(default_idle); #endif #ifdef CONFIG_XEN bool xen_set_default_idle(void) { bool ret = !!x86_idle; x86_idle = default_idle; return ret; } #endif void stop_this_cpu(void *dummy) { local_irq_disable(); /* * Remove this CPU: */ set_cpu_online(smp_processor_id(), false); disable_local_APIC(); mcheck_cpu_clear(this_cpu_ptr(&cpu_info)); /* * Use wbinvd on processors that support SME. This provides support * for performing a successful kexec when going from SME inactive * to SME active (or vice-versa). The cache must be cleared so that * if there are entries with the same physical address, both with and * without the encryption bit, they don't race each other when flushed * and potentially end up with the wrong entry being committed to * memory. */ if (boot_cpu_has(X86_FEATURE_SME)) native_wbinvd(); for (;;) { /* * Use native_halt() so that memory contents don't change * (stack usage and variables) after possibly issuing the * native_wbinvd() above. */ native_halt(); } } /* * AMD Erratum 400 aware idle routine. We handle it the same way as C3 power * states (local apic timer and TSC stop). */ static void amd_e400_idle(void) { /* * We cannot use static_cpu_has_bug() here because X86_BUG_AMD_APIC_C1E * gets set after static_cpu_has() places have been converted via * alternatives. */ if (!boot_cpu_has_bug(X86_BUG_AMD_APIC_C1E)) { default_idle(); return; } tick_broadcast_enter(); default_idle(); /* * The switch back from broadcast mode needs to be called with * interrupts disabled. */ local_irq_disable(); tick_broadcast_exit(); local_irq_enable(); } /* * Intel Core2 and older machines prefer MWAIT over HALT for C1. * We can't rely on cpuidle installing MWAIT, because it will not load * on systems that support only C1 -- so the boot default must be MWAIT. * * Some AMD machines are the opposite, they depend on using HALT. * * So for default C1, which is used during boot until cpuidle loads, * use MWAIT-C1 on Intel HW that has it, else use HALT. */ static int prefer_mwait_c1_over_halt(const struct cpuinfo_x86 *c) { if (c->x86_vendor != X86_VENDOR_INTEL) return 0; if (!cpu_has(c, X86_FEATURE_MWAIT) || boot_cpu_has_bug(X86_BUG_MONITOR)) return 0; return 1; } /* * MONITOR/MWAIT with no hints, used for default C1 state. This invokes MWAIT * with interrupts enabled and no flags, which is backwards compatible with the * original MWAIT implementation. */ static __cpuidle void mwait_idle(void) { if (!current_set_polling_and_test()) { trace_cpu_idle_rcuidle(1, smp_processor_id()); if (this_cpu_has(X86_BUG_CLFLUSH_MONITOR)) { mb(); /* quirk */ clflush((void *)&current_thread_info()->flags); mb(); /* quirk */ } __monitor((void *)&current_thread_info()->flags, 0, 0); if (!need_resched()) __sti_mwait(0, 0); else local_irq_enable(); trace_cpu_idle_rcuidle(PWR_EVENT_EXIT, smp_processor_id()); } else { local_irq_enable(); } __current_clr_polling(); } void select_idle_routine(const struct cpuinfo_x86 *c) { #ifdef CONFIG_SMP if (boot_option_idle_override == IDLE_POLL && smp_num_siblings > 1) pr_warn_once("WARNING: polling idle and HT enabled, performance may degrade\n"); #endif if (x86_idle || boot_option_idle_override == IDLE_POLL) return; if (boot_cpu_has_bug(X86_BUG_AMD_E400)) { pr_info("using AMD E400 aware idle routine\n"); x86_idle = amd_e400_idle; } else if (prefer_mwait_c1_over_halt(c)) { pr_info("using mwait in idle threads\n"); x86_idle = mwait_idle; } else x86_idle = default_idle; } void amd_e400_c1e_apic_setup(void) { if (boot_cpu_has_bug(X86_BUG_AMD_APIC_C1E)) { pr_info("Switch to broadcast mode on CPU%d\n", smp_processor_id()); local_irq_disable(); tick_broadcast_force(); local_irq_enable(); } } void __init arch_post_acpi_subsys_init(void) { u32 lo, hi; if (!boot_cpu_has_bug(X86_BUG_AMD_E400)) return; /* * AMD E400 detection needs to happen after ACPI has been enabled. If * the machine is affected K8_INTP_C1E_ACTIVE_MASK bits are set in * MSR_K8_INT_PENDING_MSG. */ rdmsr(MSR_K8_INT_PENDING_MSG, lo, hi); if (!(lo & K8_INTP_C1E_ACTIVE_MASK)) return; boot_cpu_set_bug(X86_BUG_AMD_APIC_C1E); if (!boot_cpu_has(X86_FEATURE_NONSTOP_TSC)) mark_tsc_unstable("TSC halt in AMD C1E"); pr_info("System has AMD C1E enabled\n"); } static int __init idle_setup(char *str) { if (!str) return -EINVAL; if (!strcmp(str, "poll")) { pr_info("using polling idle threads\n"); boot_option_idle_override = IDLE_POLL; cpu_idle_poll_ctrl(true); } else if (!strcmp(str, "halt")) { /* * When the boot option of idle=halt is added, halt is * forced to be used for CPU idle. In such case CPU C2/C3 * won't be used again. * To continue to load the CPU idle driver, don't touch * the boot_option_idle_override. */ x86_idle = default_idle; boot_option_idle_override = IDLE_HALT; } else if (!strcmp(str, "nomwait")) { /* * If the boot option of "idle=nomwait" is added, * it means that mwait will be disabled for CPU C2/C3 * states. In such case it won't touch the variable * of boot_option_idle_override. */ boot_option_idle_override = IDLE_NOMWAIT; } else return -1; return 0; } early_param("idle", idle_setup); unsigned long arch_align_stack(unsigned long sp) { if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space) sp -= get_random_int() % 8192; return sp & ~0xf; } unsigned long arch_randomize_brk(struct mm_struct *mm) { return randomize_page(mm->brk, 0x02000000); } /* * Called from fs/proc with a reference on @p to find the function * which called into schedule(). This needs to be done carefully * because the task might wake up and we might look at a stack * changing under us. */ unsigned long get_wchan(struct task_struct *p) { unsigned long start, bottom, top, sp, fp, ip, ret = 0; int count = 0; if (p == current || p->state == TASK_RUNNING) return 0; if (!try_get_task_stack(p)) return 0; start = (unsigned long)task_stack_page(p); if (!start) goto out; /* * Layout of the stack page: * * ----------- topmax = start + THREAD_SIZE - sizeof(unsigned long) * PADDING * ----------- top = topmax - TOP_OF_KERNEL_STACK_PADDING * stack * ----------- bottom = start * * The tasks stack pointer points at the location where the * framepointer is stored. The data on the stack is: * ... IP FP ... IP FP * * We need to read FP and IP, so we need to adjust the upper * bound by another unsigned long. */ top = start + THREAD_SIZE - TOP_OF_KERNEL_STACK_PADDING; top -= 2 * sizeof(unsigned long); bottom = start; sp = READ_ONCE(p->thread.sp); if (sp < bottom || sp > top) goto out; fp = READ_ONCE_NOCHECK(((struct inactive_task_frame *)sp)->bp); do { if (fp < bottom || fp > top) goto out; ip = READ_ONCE_NOCHECK(*(unsigned long *)(fp + sizeof(unsigned long))); if (!in_sched_functions(ip)) { ret = ip; goto out; } fp = READ_ONCE_NOCHECK(*(unsigned long *)fp); } while (count++ < 16 && p->state != TASK_RUNNING); out: put_task_stack(p); return ret; } long do_arch_prctl_common(struct task_struct *task, int option, unsigned long cpuid_enabled) { switch (option) { case ARCH_GET_CPUID: return get_cpuid_mode(); case ARCH_SET_CPUID: return set_cpuid_mode(task, cpuid_enabled); } return -EINVAL; }
./CrossVul/dataset_final_sorted/CWE-276/c/good_4225_4
crossvul-cpp_data_bad_4309_0
// SPDX-License-Identifier: GPL-2.0-or-later /* * Copyright (C) 2011 Instituto Nokia de Tecnologia * * Authors: * Aloisio Almeida Jr <aloisio.almeida@openbossa.org> * Lauro Ramos Venancio <lauro.venancio@openbossa.org> */ #define pr_fmt(fmt) KBUILD_MODNAME ": %s: " fmt, __func__ #include <net/tcp_states.h> #include <linux/nfc.h> #include <linux/export.h> #include "nfc.h" static struct nfc_sock_list raw_sk_list = { .lock = __RW_LOCK_UNLOCKED(raw_sk_list.lock) }; static void nfc_sock_link(struct nfc_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_add_node(sk, &l->head); write_unlock(&l->lock); } static void nfc_sock_unlink(struct nfc_sock_list *l, struct sock *sk) { write_lock(&l->lock); sk_del_node_init(sk); write_unlock(&l->lock); } static void rawsock_write_queue_purge(struct sock *sk) { pr_debug("sk=%p\n", sk); spin_lock_bh(&sk->sk_write_queue.lock); __skb_queue_purge(&sk->sk_write_queue); nfc_rawsock(sk)->tx_work_scheduled = false; spin_unlock_bh(&sk->sk_write_queue.lock); } static void rawsock_report_error(struct sock *sk, int err) { pr_debug("sk=%p err=%d\n", sk, err); sk->sk_shutdown = SHUTDOWN_MASK; sk->sk_err = -err; sk->sk_error_report(sk); rawsock_write_queue_purge(sk); } static int rawsock_release(struct socket *sock) { struct sock *sk = sock->sk; pr_debug("sock=%p sk=%p\n", sock, sk); if (!sk) return 0; if (sock->type == SOCK_RAW) nfc_sock_unlink(&raw_sk_list, sk); sock_orphan(sk); sock_put(sk); return 0; } static int rawsock_connect(struct socket *sock, struct sockaddr *_addr, int len, int flags) { struct sock *sk = sock->sk; struct sockaddr_nfc *addr = (struct sockaddr_nfc *)_addr; struct nfc_dev *dev; int rc = 0; pr_debug("sock=%p sk=%p flags=%d\n", sock, sk, flags); if (!addr || len < sizeof(struct sockaddr_nfc) || addr->sa_family != AF_NFC) return -EINVAL; pr_debug("addr dev_idx=%u target_idx=%u protocol=%u\n", addr->dev_idx, addr->target_idx, addr->nfc_protocol); lock_sock(sk); if (sock->state == SS_CONNECTED) { rc = -EISCONN; goto error; } dev = nfc_get_device(addr->dev_idx); if (!dev) { rc = -ENODEV; goto error; } if (addr->target_idx > dev->target_next_idx - 1 || addr->target_idx < dev->target_next_idx - dev->n_targets) { rc = -EINVAL; goto error; } rc = nfc_activate_target(dev, addr->target_idx, addr->nfc_protocol); if (rc) goto put_dev; nfc_rawsock(sk)->dev = dev; nfc_rawsock(sk)->target_idx = addr->target_idx; sock->state = SS_CONNECTED; sk->sk_state = TCP_ESTABLISHED; sk->sk_state_change(sk); release_sock(sk); return 0; put_dev: nfc_put_device(dev); error: release_sock(sk); return rc; } static int rawsock_add_header(struct sk_buff *skb) { *(u8 *)skb_push(skb, NFC_HEADER_SIZE) = 0; return 0; } static void rawsock_data_exchange_complete(void *context, struct sk_buff *skb, int err) { struct sock *sk = (struct sock *) context; BUG_ON(in_irq()); pr_debug("sk=%p err=%d\n", sk, err); if (err) goto error; err = rawsock_add_header(skb); if (err) goto error_skb; err = sock_queue_rcv_skb(sk, skb); if (err) goto error_skb; spin_lock_bh(&sk->sk_write_queue.lock); if (!skb_queue_empty(&sk->sk_write_queue)) schedule_work(&nfc_rawsock(sk)->tx_work); else nfc_rawsock(sk)->tx_work_scheduled = false; spin_unlock_bh(&sk->sk_write_queue.lock); sock_put(sk); return; error_skb: kfree_skb(skb); error: rawsock_report_error(sk, err); sock_put(sk); } static void rawsock_tx_work(struct work_struct *work) { struct sock *sk = to_rawsock_sk(work); struct nfc_dev *dev = nfc_rawsock(sk)->dev; u32 target_idx = nfc_rawsock(sk)->target_idx; struct sk_buff *skb; int rc; pr_debug("sk=%p target_idx=%u\n", sk, target_idx); if (sk->sk_shutdown & SEND_SHUTDOWN) { rawsock_write_queue_purge(sk); return; } skb = skb_dequeue(&sk->sk_write_queue); sock_hold(sk); rc = nfc_data_exchange(dev, target_idx, skb, rawsock_data_exchange_complete, sk); if (rc) { rawsock_report_error(sk, rc); sock_put(sk); } } static int rawsock_sendmsg(struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct nfc_dev *dev = nfc_rawsock(sk)->dev; struct sk_buff *skb; int rc; pr_debug("sock=%p sk=%p len=%zu\n", sock, sk, len); if (msg->msg_namelen) return -EOPNOTSUPP; if (sock->state != SS_CONNECTED) return -ENOTCONN; skb = nfc_alloc_send_skb(dev, sk, msg->msg_flags, len, &rc); if (skb == NULL) return rc; rc = memcpy_from_msg(skb_put(skb, len), msg, len); if (rc < 0) { kfree_skb(skb); return rc; } spin_lock_bh(&sk->sk_write_queue.lock); __skb_queue_tail(&sk->sk_write_queue, skb); if (!nfc_rawsock(sk)->tx_work_scheduled) { schedule_work(&nfc_rawsock(sk)->tx_work); nfc_rawsock(sk)->tx_work_scheduled = true; } spin_unlock_bh(&sk->sk_write_queue.lock); return len; } static int rawsock_recvmsg(struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; struct sk_buff *skb; int copied; int rc; pr_debug("sock=%p sk=%p len=%zu flags=%d\n", sock, sk, len, flags); skb = skb_recv_datagram(sk, flags, noblock, &rc); if (!skb) return rc; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } rc = skb_copy_datagram_msg(skb, 0, msg, copied); skb_free_datagram(sk, skb); return rc ? : copied; } static const struct proto_ops rawsock_ops = { .family = PF_NFC, .owner = THIS_MODULE, .release = rawsock_release, .bind = sock_no_bind, .connect = rawsock_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .poll = datagram_poll, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .sendmsg = rawsock_sendmsg, .recvmsg = rawsock_recvmsg, .mmap = sock_no_mmap, }; static const struct proto_ops rawsock_raw_ops = { .family = PF_NFC, .owner = THIS_MODULE, .release = rawsock_release, .bind = sock_no_bind, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = sock_no_getname, .poll = datagram_poll, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .sendmsg = sock_no_sendmsg, .recvmsg = rawsock_recvmsg, .mmap = sock_no_mmap, }; static void rawsock_destruct(struct sock *sk) { pr_debug("sk=%p\n", sk); if (sk->sk_state == TCP_ESTABLISHED) { nfc_deactivate_target(nfc_rawsock(sk)->dev, nfc_rawsock(sk)->target_idx, NFC_TARGET_MODE_IDLE); nfc_put_device(nfc_rawsock(sk)->dev); } skb_queue_purge(&sk->sk_receive_queue); if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Freeing alive NFC raw socket %p\n", sk); return; } } static int rawsock_create(struct net *net, struct socket *sock, const struct nfc_protocol *nfc_proto, int kern) { struct sock *sk; pr_debug("sock=%p\n", sock); if ((sock->type != SOCK_SEQPACKET) && (sock->type != SOCK_RAW)) return -ESOCKTNOSUPPORT; if (sock->type == SOCK_RAW) sock->ops = &rawsock_raw_ops; else sock->ops = &rawsock_ops; sk = sk_alloc(net, PF_NFC, GFP_ATOMIC, nfc_proto->proto, kern); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sk->sk_protocol = nfc_proto->id; sk->sk_destruct = rawsock_destruct; sock->state = SS_UNCONNECTED; if (sock->type == SOCK_RAW) nfc_sock_link(&raw_sk_list, sk); else { INIT_WORK(&nfc_rawsock(sk)->tx_work, rawsock_tx_work); nfc_rawsock(sk)->tx_work_scheduled = false; } return 0; } void nfc_send_to_raw_sock(struct nfc_dev *dev, struct sk_buff *skb, u8 payload_type, u8 direction) { struct sk_buff *skb_copy = NULL, *nskb; struct sock *sk; u8 *data; read_lock(&raw_sk_list.lock); sk_for_each(sk, &raw_sk_list.head) { if (!skb_copy) { skb_copy = __pskb_copy_fclone(skb, NFC_RAW_HEADER_SIZE, GFP_ATOMIC, true); if (!skb_copy) continue; data = skb_push(skb_copy, NFC_RAW_HEADER_SIZE); data[0] = dev ? dev->idx : 0xFF; data[1] = direction & 0x01; data[1] |= (payload_type << 1); } nskb = skb_clone(skb_copy, GFP_ATOMIC); if (!nskb) continue; if (sock_queue_rcv_skb(sk, nskb)) kfree_skb(nskb); } read_unlock(&raw_sk_list.lock); kfree_skb(skb_copy); } EXPORT_SYMBOL(nfc_send_to_raw_sock); static struct proto rawsock_proto = { .name = "NFC_RAW", .owner = THIS_MODULE, .obj_size = sizeof(struct nfc_rawsock), }; static const struct nfc_protocol rawsock_nfc_proto = { .id = NFC_SOCKPROTO_RAW, .proto = &rawsock_proto, .owner = THIS_MODULE, .create = rawsock_create }; int __init rawsock_init(void) { int rc; rc = nfc_proto_register(&rawsock_nfc_proto); return rc; } void rawsock_exit(void) { nfc_proto_unregister(&rawsock_nfc_proto); }
./CrossVul/dataset_final_sorted/CWE-276/c/bad_4309_0
crossvul-cpp_data_bad_4225_3
// SPDX-License-Identifier: GPL-2.0-or-later /* Paravirtualization interfaces Copyright (C) 2006 Rusty Russell IBM Corporation 2007 - x86_64 support added by Glauber de Oliveira Costa, Red Hat Inc */ #include <linux/errno.h> #include <linux/init.h> #include <linux/export.h> #include <linux/efi.h> #include <linux/bcd.h> #include <linux/highmem.h> #include <linux/kprobes.h> #include <linux/pgtable.h> #include <asm/bug.h> #include <asm/paravirt.h> #include <asm/debugreg.h> #include <asm/desc.h> #include <asm/setup.h> #include <asm/time.h> #include <asm/pgalloc.h> #include <asm/irq.h> #include <asm/delay.h> #include <asm/fixmap.h> #include <asm/apic.h> #include <asm/tlbflush.h> #include <asm/timer.h> #include <asm/special_insns.h> #include <asm/tlb.h> #include <asm/io_bitmap.h> /* * nop stub, which must not clobber anything *including the stack* to * avoid confusing the entry prologues. */ extern void _paravirt_nop(void); asm (".pushsection .entry.text, \"ax\"\n" ".global _paravirt_nop\n" "_paravirt_nop:\n\t" "ret\n\t" ".size _paravirt_nop, . - _paravirt_nop\n\t" ".type _paravirt_nop, @function\n\t" ".popsection"); void __init default_banner(void) { printk(KERN_INFO "Booting paravirtualized kernel on %s\n", pv_info.name); } /* Undefined instruction for dealing with missing ops pointers. */ static const unsigned char ud2a[] = { 0x0f, 0x0b }; struct branch { unsigned char opcode; u32 delta; } __attribute__((packed)); static unsigned paravirt_patch_call(void *insn_buff, const void *target, unsigned long addr, unsigned len) { const int call_len = 5; struct branch *b = insn_buff; unsigned long delta = (unsigned long)target - (addr+call_len); if (len < call_len) { pr_warn("paravirt: Failed to patch indirect CALL at %ps\n", (void *)addr); /* Kernel might not be viable if patching fails, bail out: */ BUG_ON(1); } b->opcode = 0xe8; /* call */ b->delta = delta; BUILD_BUG_ON(sizeof(*b) != call_len); return call_len; } #ifdef CONFIG_PARAVIRT_XXL /* identity function, which can be inlined */ u64 notrace _paravirt_ident_64(u64 x) { return x; } static unsigned paravirt_patch_jmp(void *insn_buff, const void *target, unsigned long addr, unsigned len) { struct branch *b = insn_buff; unsigned long delta = (unsigned long)target - (addr+5); if (len < 5) { #ifdef CONFIG_RETPOLINE WARN_ONCE(1, "Failing to patch indirect JMP in %ps\n", (void *)addr); #endif return len; /* call too long for patch site */ } b->opcode = 0xe9; /* jmp */ b->delta = delta; return 5; } #endif DEFINE_STATIC_KEY_TRUE(virt_spin_lock_key); void __init native_pv_lock_init(void) { if (!boot_cpu_has(X86_FEATURE_HYPERVISOR)) static_branch_disable(&virt_spin_lock_key); } unsigned paravirt_patch_default(u8 type, void *insn_buff, unsigned long addr, unsigned len) { /* * Neat trick to map patch type back to the call within the * corresponding structure. */ void *opfunc = *((void **)&pv_ops + type); unsigned ret; if (opfunc == NULL) /* If there's no function, patch it with a ud2a (BUG) */ ret = paravirt_patch_insns(insn_buff, len, ud2a, ud2a+sizeof(ud2a)); else if (opfunc == _paravirt_nop) ret = 0; #ifdef CONFIG_PARAVIRT_XXL /* identity functions just return their single argument */ else if (opfunc == _paravirt_ident_64) ret = paravirt_patch_ident_64(insn_buff, len); else if (type == PARAVIRT_PATCH(cpu.iret) || type == PARAVIRT_PATCH(cpu.usergs_sysret64)) /* If operation requires a jmp, then jmp */ ret = paravirt_patch_jmp(insn_buff, opfunc, addr, len); #endif else /* Otherwise call the function. */ ret = paravirt_patch_call(insn_buff, opfunc, addr, len); return ret; } unsigned paravirt_patch_insns(void *insn_buff, unsigned len, const char *start, const char *end) { unsigned insn_len = end - start; /* Alternative instruction is too large for the patch site and we cannot continue: */ BUG_ON(insn_len > len || start == NULL); memcpy(insn_buff, start, insn_len); return insn_len; } struct static_key paravirt_steal_enabled; struct static_key paravirt_steal_rq_enabled; static u64 native_steal_clock(int cpu) { return 0; } /* These are in entry.S */ extern void native_iret(void); extern void native_usergs_sysret64(void); static struct resource reserve_ioports = { .start = 0, .end = IO_SPACE_LIMIT, .name = "paravirt-ioport", .flags = IORESOURCE_IO | IORESOURCE_BUSY, }; /* * Reserve the whole legacy IO space to prevent any legacy drivers * from wasting time probing for their hardware. This is a fairly * brute-force approach to disabling all non-virtual drivers. * * Note that this must be called very early to have any effect. */ int paravirt_disable_iospace(void) { return request_resource(&ioport_resource, &reserve_ioports); } static DEFINE_PER_CPU(enum paravirt_lazy_mode, paravirt_lazy_mode) = PARAVIRT_LAZY_NONE; static inline void enter_lazy(enum paravirt_lazy_mode mode) { BUG_ON(this_cpu_read(paravirt_lazy_mode) != PARAVIRT_LAZY_NONE); this_cpu_write(paravirt_lazy_mode, mode); } static void leave_lazy(enum paravirt_lazy_mode mode) { BUG_ON(this_cpu_read(paravirt_lazy_mode) != mode); this_cpu_write(paravirt_lazy_mode, PARAVIRT_LAZY_NONE); } void paravirt_enter_lazy_mmu(void) { enter_lazy(PARAVIRT_LAZY_MMU); } void paravirt_leave_lazy_mmu(void) { leave_lazy(PARAVIRT_LAZY_MMU); } void paravirt_flush_lazy_mmu(void) { preempt_disable(); if (paravirt_get_lazy_mode() == PARAVIRT_LAZY_MMU) { arch_leave_lazy_mmu_mode(); arch_enter_lazy_mmu_mode(); } preempt_enable(); } #ifdef CONFIG_PARAVIRT_XXL void paravirt_start_context_switch(struct task_struct *prev) { BUG_ON(preemptible()); if (this_cpu_read(paravirt_lazy_mode) == PARAVIRT_LAZY_MMU) { arch_leave_lazy_mmu_mode(); set_ti_thread_flag(task_thread_info(prev), TIF_LAZY_MMU_UPDATES); } enter_lazy(PARAVIRT_LAZY_CPU); } void paravirt_end_context_switch(struct task_struct *next) { BUG_ON(preemptible()); leave_lazy(PARAVIRT_LAZY_CPU); if (test_and_clear_ti_thread_flag(task_thread_info(next), TIF_LAZY_MMU_UPDATES)) arch_enter_lazy_mmu_mode(); } #endif enum paravirt_lazy_mode paravirt_get_lazy_mode(void) { if (in_interrupt()) return PARAVIRT_LAZY_NONE; return this_cpu_read(paravirt_lazy_mode); } struct pv_info pv_info = { .name = "bare hardware", #ifdef CONFIG_PARAVIRT_XXL .kernel_rpl = 0, .shared_kernel_pmd = 1, /* Only used when CONFIG_X86_PAE is set */ #ifdef CONFIG_X86_64 .extra_user_64bit_cs = __USER_CS, #endif #endif }; /* 64-bit pagetable entries */ #define PTE_IDENT __PV_IS_CALLEE_SAVE(_paravirt_ident_64) struct paravirt_patch_template pv_ops = { /* Init ops. */ .init.patch = native_patch, /* Time ops. */ .time.sched_clock = native_sched_clock, .time.steal_clock = native_steal_clock, /* Cpu ops. */ .cpu.io_delay = native_io_delay, #ifdef CONFIG_PARAVIRT_XXL .cpu.cpuid = native_cpuid, .cpu.get_debugreg = native_get_debugreg, .cpu.set_debugreg = native_set_debugreg, .cpu.read_cr0 = native_read_cr0, .cpu.write_cr0 = native_write_cr0, .cpu.write_cr4 = native_write_cr4, .cpu.wbinvd = native_wbinvd, .cpu.read_msr = native_read_msr, .cpu.write_msr = native_write_msr, .cpu.read_msr_safe = native_read_msr_safe, .cpu.write_msr_safe = native_write_msr_safe, .cpu.read_pmc = native_read_pmc, .cpu.load_tr_desc = native_load_tr_desc, .cpu.set_ldt = native_set_ldt, .cpu.load_gdt = native_load_gdt, .cpu.load_idt = native_load_idt, .cpu.store_tr = native_store_tr, .cpu.load_tls = native_load_tls, #ifdef CONFIG_X86_64 .cpu.load_gs_index = native_load_gs_index, #endif .cpu.write_ldt_entry = native_write_ldt_entry, .cpu.write_gdt_entry = native_write_gdt_entry, .cpu.write_idt_entry = native_write_idt_entry, .cpu.alloc_ldt = paravirt_nop, .cpu.free_ldt = paravirt_nop, .cpu.load_sp0 = native_load_sp0, #ifdef CONFIG_X86_64 .cpu.usergs_sysret64 = native_usergs_sysret64, #endif .cpu.iret = native_iret, .cpu.swapgs = native_swapgs, #ifdef CONFIG_X86_IOPL_IOPERM .cpu.update_io_bitmap = native_tss_update_io_bitmap, #endif .cpu.start_context_switch = paravirt_nop, .cpu.end_context_switch = paravirt_nop, /* Irq ops. */ .irq.save_fl = __PV_IS_CALLEE_SAVE(native_save_fl), .irq.restore_fl = __PV_IS_CALLEE_SAVE(native_restore_fl), .irq.irq_disable = __PV_IS_CALLEE_SAVE(native_irq_disable), .irq.irq_enable = __PV_IS_CALLEE_SAVE(native_irq_enable), .irq.safe_halt = native_safe_halt, .irq.halt = native_halt, #endif /* CONFIG_PARAVIRT_XXL */ /* Mmu ops. */ .mmu.flush_tlb_user = native_flush_tlb_local, .mmu.flush_tlb_kernel = native_flush_tlb_global, .mmu.flush_tlb_one_user = native_flush_tlb_one_user, .mmu.flush_tlb_others = native_flush_tlb_others, .mmu.tlb_remove_table = (void (*)(struct mmu_gather *, void *))tlb_remove_page, .mmu.exit_mmap = paravirt_nop, #ifdef CONFIG_PARAVIRT_XXL .mmu.read_cr2 = __PV_IS_CALLEE_SAVE(native_read_cr2), .mmu.write_cr2 = native_write_cr2, .mmu.read_cr3 = __native_read_cr3, .mmu.write_cr3 = native_write_cr3, .mmu.pgd_alloc = __paravirt_pgd_alloc, .mmu.pgd_free = paravirt_nop, .mmu.alloc_pte = paravirt_nop, .mmu.alloc_pmd = paravirt_nop, .mmu.alloc_pud = paravirt_nop, .mmu.alloc_p4d = paravirt_nop, .mmu.release_pte = paravirt_nop, .mmu.release_pmd = paravirt_nop, .mmu.release_pud = paravirt_nop, .mmu.release_p4d = paravirt_nop, .mmu.set_pte = native_set_pte, .mmu.set_pte_at = native_set_pte_at, .mmu.set_pmd = native_set_pmd, .mmu.ptep_modify_prot_start = __ptep_modify_prot_start, .mmu.ptep_modify_prot_commit = __ptep_modify_prot_commit, #if CONFIG_PGTABLE_LEVELS >= 3 #ifdef CONFIG_X86_PAE .mmu.set_pte_atomic = native_set_pte_atomic, .mmu.pte_clear = native_pte_clear, .mmu.pmd_clear = native_pmd_clear, #endif .mmu.set_pud = native_set_pud, .mmu.pmd_val = PTE_IDENT, .mmu.make_pmd = PTE_IDENT, #if CONFIG_PGTABLE_LEVELS >= 4 .mmu.pud_val = PTE_IDENT, .mmu.make_pud = PTE_IDENT, .mmu.set_p4d = native_set_p4d, #if CONFIG_PGTABLE_LEVELS >= 5 .mmu.p4d_val = PTE_IDENT, .mmu.make_p4d = PTE_IDENT, .mmu.set_pgd = native_set_pgd, #endif /* CONFIG_PGTABLE_LEVELS >= 5 */ #endif /* CONFIG_PGTABLE_LEVELS >= 4 */ #endif /* CONFIG_PGTABLE_LEVELS >= 3 */ .mmu.pte_val = PTE_IDENT, .mmu.pgd_val = PTE_IDENT, .mmu.make_pte = PTE_IDENT, .mmu.make_pgd = PTE_IDENT, .mmu.dup_mmap = paravirt_nop, .mmu.activate_mm = paravirt_nop, .mmu.lazy_mode = { .enter = paravirt_nop, .leave = paravirt_nop, .flush = paravirt_nop, }, .mmu.set_fixmap = native_set_fixmap, #endif /* CONFIG_PARAVIRT_XXL */ #if defined(CONFIG_PARAVIRT_SPINLOCKS) /* Lock ops. */ #ifdef CONFIG_SMP .lock.queued_spin_lock_slowpath = native_queued_spin_lock_slowpath, .lock.queued_spin_unlock = PV_CALLEE_SAVE(__native_queued_spin_unlock), .lock.wait = paravirt_nop, .lock.kick = paravirt_nop, .lock.vcpu_is_preempted = PV_CALLEE_SAVE(__native_vcpu_is_preempted), #endif /* SMP */ #endif }; #ifdef CONFIG_PARAVIRT_XXL /* At this point, native_get/set_debugreg has real function entries */ NOKPROBE_SYMBOL(native_get_debugreg); NOKPROBE_SYMBOL(native_set_debugreg); NOKPROBE_SYMBOL(native_load_idt); #endif EXPORT_SYMBOL(pv_ops); EXPORT_SYMBOL_GPL(pv_info);
./CrossVul/dataset_final_sorted/CWE-276/c/bad_4225_3
crossvul-cpp_data_good_4225_5
// SPDX-License-Identifier: GPL-2.0 /* * Core of Xen paravirt_ops implementation. * * This file contains the xen_paravirt_ops structure itself, and the * implementations for: * - privileged instructions * - interrupt flags * - segment operations * - booting and setup * * Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007 */ #include <linux/cpu.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/smp.h> #include <linux/preempt.h> #include <linux/hardirq.h> #include <linux/percpu.h> #include <linux/delay.h> #include <linux/start_kernel.h> #include <linux/sched.h> #include <linux/kprobes.h> #include <linux/memblock.h> #include <linux/export.h> #include <linux/mm.h> #include <linux/page-flags.h> #include <linux/highmem.h> #include <linux/console.h> #include <linux/pci.h> #include <linux/gfp.h> #include <linux/edd.h> #include <linux/frame.h> #include <xen/xen.h> #include <xen/events.h> #include <xen/interface/xen.h> #include <xen/interface/version.h> #include <xen/interface/physdev.h> #include <xen/interface/vcpu.h> #include <xen/interface/memory.h> #include <xen/interface/nmi.h> #include <xen/interface/xen-mca.h> #include <xen/features.h> #include <xen/page.h> #include <xen/hvc-console.h> #include <xen/acpi.h> #include <asm/paravirt.h> #include <asm/apic.h> #include <asm/page.h> #include <asm/xen/pci.h> #include <asm/xen/hypercall.h> #include <asm/xen/hypervisor.h> #include <asm/xen/cpuid.h> #include <asm/fixmap.h> #include <asm/processor.h> #include <asm/proto.h> #include <asm/msr-index.h> #include <asm/traps.h> #include <asm/setup.h> #include <asm/desc.h> #include <asm/pgalloc.h> #include <asm/tlbflush.h> #include <asm/reboot.h> #include <asm/stackprotector.h> #include <asm/hypervisor.h> #include <asm/mach_traps.h> #include <asm/mwait.h> #include <asm/pci_x86.h> #include <asm/cpu.h> #ifdef CONFIG_X86_IOPL_IOPERM #include <asm/io_bitmap.h> #endif #ifdef CONFIG_ACPI #include <linux/acpi.h> #include <asm/acpi.h> #include <acpi/pdc_intel.h> #include <acpi/processor.h> #include <xen/interface/platform.h> #endif #include "xen-ops.h" #include "mmu.h" #include "smp.h" #include "multicalls.h" #include "pmu.h" #include "../kernel/cpu/cpu.h" /* get_cpu_cap() */ void *xen_initial_gdt; static int xen_cpu_up_prepare_pv(unsigned int cpu); static int xen_cpu_dead_pv(unsigned int cpu); struct tls_descs { struct desc_struct desc[3]; }; /* * Updating the 3 TLS descriptors in the GDT on every task switch is * surprisingly expensive so we avoid updating them if they haven't * changed. Since Xen writes different descriptors than the one * passed in the update_descriptor hypercall we keep shadow copies to * compare against. */ static DEFINE_PER_CPU(struct tls_descs, shadow_tls_desc); static void __init xen_banner(void) { unsigned version = HYPERVISOR_xen_version(XENVER_version, NULL); struct xen_extraversion extra; HYPERVISOR_xen_version(XENVER_extraversion, &extra); pr_info("Booting paravirtualized kernel on %s\n", pv_info.name); printk(KERN_INFO "Xen version: %d.%d%s%s\n", version >> 16, version & 0xffff, extra.extraversion, xen_feature(XENFEAT_mmu_pt_update_preserve_ad) ? " (preserve-AD)" : ""); #ifdef CONFIG_X86_32 pr_warn("WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!\n" "Support for running as 32-bit PV-guest under Xen will soon be removed\n" "from the Linux kernel!\n" "Please use either a 64-bit kernel or switch to HVM or PVH mode!\n" "WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!\n"); #endif } static void __init xen_pv_init_platform(void) { populate_extra_pte(fix_to_virt(FIX_PARAVIRT_BOOTMAP)); set_fixmap(FIX_PARAVIRT_BOOTMAP, xen_start_info->shared_info); HYPERVISOR_shared_info = (void *)fix_to_virt(FIX_PARAVIRT_BOOTMAP); /* xen clock uses per-cpu vcpu_info, need to init it for boot cpu */ xen_vcpu_info_reset(0); /* pvclock is in shared info area */ xen_init_time_ops(); } static void __init xen_pv_guest_late_init(void) { #ifndef CONFIG_SMP /* Setup shared vcpu info for non-smp configurations */ xen_setup_vcpu_info_placement(); #endif } /* Check if running on Xen version (major, minor) or later */ bool xen_running_on_version_or_later(unsigned int major, unsigned int minor) { unsigned int version; if (!xen_domain()) return false; version = HYPERVISOR_xen_version(XENVER_version, NULL); if ((((version >> 16) == major) && ((version & 0xffff) >= minor)) || ((version >> 16) > major)) return true; return false; } static __read_mostly unsigned int cpuid_leaf5_ecx_val; static __read_mostly unsigned int cpuid_leaf5_edx_val; static void xen_cpuid(unsigned int *ax, unsigned int *bx, unsigned int *cx, unsigned int *dx) { unsigned maskebx = ~0; /* * Mask out inconvenient features, to try and disable as many * unsupported kernel subsystems as possible. */ switch (*ax) { case CPUID_MWAIT_LEAF: /* Synthesize the values.. */ *ax = 0; *bx = 0; *cx = cpuid_leaf5_ecx_val; *dx = cpuid_leaf5_edx_val; return; case 0xb: /* Suppress extended topology stuff */ maskebx = 0; break; } asm(XEN_EMULATE_PREFIX "cpuid" : "=a" (*ax), "=b" (*bx), "=c" (*cx), "=d" (*dx) : "0" (*ax), "2" (*cx)); *bx &= maskebx; } STACK_FRAME_NON_STANDARD(xen_cpuid); /* XEN_EMULATE_PREFIX */ static bool __init xen_check_mwait(void) { #ifdef CONFIG_ACPI struct xen_platform_op op = { .cmd = XENPF_set_processor_pminfo, .u.set_pminfo.id = -1, .u.set_pminfo.type = XEN_PM_PDC, }; uint32_t buf[3]; unsigned int ax, bx, cx, dx; unsigned int mwait_mask; /* We need to determine whether it is OK to expose the MWAIT * capability to the kernel to harvest deeper than C3 states from ACPI * _CST using the processor_harvest_xen.c module. For this to work, we * need to gather the MWAIT_LEAF values (which the cstate.c code * checks against). The hypervisor won't expose the MWAIT flag because * it would break backwards compatibility; so we will find out directly * from the hardware and hypercall. */ if (!xen_initial_domain()) return false; /* * When running under platform earlier than Xen4.2, do not expose * mwait, to avoid the risk of loading native acpi pad driver */ if (!xen_running_on_version_or_later(4, 2)) return false; ax = 1; cx = 0; native_cpuid(&ax, &bx, &cx, &dx); mwait_mask = (1 << (X86_FEATURE_EST % 32)) | (1 << (X86_FEATURE_MWAIT % 32)); if ((cx & mwait_mask) != mwait_mask) return false; /* We need to emulate the MWAIT_LEAF and for that we need both * ecx and edx. The hypercall provides only partial information. */ ax = CPUID_MWAIT_LEAF; bx = 0; cx = 0; dx = 0; native_cpuid(&ax, &bx, &cx, &dx); /* Ask the Hypervisor whether to clear ACPI_PDC_C_C2C3_FFH. If so, * don't expose MWAIT_LEAF and let ACPI pick the IOPORT version of C3. */ buf[0] = ACPI_PDC_REVISION_ID; buf[1] = 1; buf[2] = (ACPI_PDC_C_CAPABILITY_SMP | ACPI_PDC_EST_CAPABILITY_SWSMP); set_xen_guest_handle(op.u.set_pminfo.pdc, buf); if ((HYPERVISOR_platform_op(&op) == 0) && (buf[2] & (ACPI_PDC_C_C1_FFH | ACPI_PDC_C_C2C3_FFH))) { cpuid_leaf5_ecx_val = cx; cpuid_leaf5_edx_val = dx; } return true; #else return false; #endif } static bool __init xen_check_xsave(void) { unsigned int cx, xsave_mask; cx = cpuid_ecx(1); xsave_mask = (1 << (X86_FEATURE_XSAVE % 32)) | (1 << (X86_FEATURE_OSXSAVE % 32)); /* Xen will set CR4.OSXSAVE if supported and not disabled by force */ return (cx & xsave_mask) == xsave_mask; } static void __init xen_init_capabilities(void) { setup_force_cpu_cap(X86_FEATURE_XENPV); setup_clear_cpu_cap(X86_FEATURE_DCA); setup_clear_cpu_cap(X86_FEATURE_APERFMPERF); setup_clear_cpu_cap(X86_FEATURE_MTRR); setup_clear_cpu_cap(X86_FEATURE_ACC); setup_clear_cpu_cap(X86_FEATURE_X2APIC); setup_clear_cpu_cap(X86_FEATURE_SME); /* * Xen PV would need some work to support PCID: CR3 handling as well * as xen_flush_tlb_others() would need updating. */ setup_clear_cpu_cap(X86_FEATURE_PCID); if (!xen_initial_domain()) setup_clear_cpu_cap(X86_FEATURE_ACPI); if (xen_check_mwait()) setup_force_cpu_cap(X86_FEATURE_MWAIT); else setup_clear_cpu_cap(X86_FEATURE_MWAIT); if (!xen_check_xsave()) { setup_clear_cpu_cap(X86_FEATURE_XSAVE); setup_clear_cpu_cap(X86_FEATURE_OSXSAVE); } } static void xen_set_debugreg(int reg, unsigned long val) { HYPERVISOR_set_debugreg(reg, val); } static unsigned long xen_get_debugreg(int reg) { return HYPERVISOR_get_debugreg(reg); } static void xen_end_context_switch(struct task_struct *next) { xen_mc_flush(); paravirt_end_context_switch(next); } static unsigned long xen_store_tr(void) { return 0; } /* * Set the page permissions for a particular virtual address. If the * address is a vmalloc mapping (or other non-linear mapping), then * find the linear mapping of the page and also set its protections to * match. */ static void set_aliased_prot(void *v, pgprot_t prot) { int level; pte_t *ptep; pte_t pte; unsigned long pfn; struct page *page; unsigned char dummy; ptep = lookup_address((unsigned long)v, &level); BUG_ON(ptep == NULL); pfn = pte_pfn(*ptep); page = pfn_to_page(pfn); pte = pfn_pte(pfn, prot); /* * Careful: update_va_mapping() will fail if the virtual address * we're poking isn't populated in the page tables. We don't * need to worry about the direct map (that's always in the page * tables), but we need to be careful about vmap space. In * particular, the top level page table can lazily propagate * entries between processes, so if we've switched mms since we * vmapped the target in the first place, we might not have the * top-level page table entry populated. * * We disable preemption because we want the same mm active when * we probe the target and when we issue the hypercall. We'll * have the same nominal mm, but if we're a kernel thread, lazy * mm dropping could change our pgd. * * Out of an abundance of caution, this uses __get_user() to fault * in the target address just in case there's some obscure case * in which the target address isn't readable. */ preempt_disable(); copy_from_kernel_nofault(&dummy, v, 1); if (HYPERVISOR_update_va_mapping((unsigned long)v, pte, 0)) BUG(); if (!PageHighMem(page)) { void *av = __va(PFN_PHYS(pfn)); if (av != v) if (HYPERVISOR_update_va_mapping((unsigned long)av, pte, 0)) BUG(); } else kmap_flush_unused(); preempt_enable(); } static void xen_alloc_ldt(struct desc_struct *ldt, unsigned entries) { const unsigned entries_per_page = PAGE_SIZE / LDT_ENTRY_SIZE; int i; /* * We need to mark the all aliases of the LDT pages RO. We * don't need to call vm_flush_aliases(), though, since that's * only responsible for flushing aliases out the TLBs, not the * page tables, and Xen will flush the TLB for us if needed. * * To avoid confusing future readers: none of this is necessary * to load the LDT. The hypervisor only checks this when the * LDT is faulted in due to subsequent descriptor access. */ for (i = 0; i < entries; i += entries_per_page) set_aliased_prot(ldt + i, PAGE_KERNEL_RO); } static void xen_free_ldt(struct desc_struct *ldt, unsigned entries) { const unsigned entries_per_page = PAGE_SIZE / LDT_ENTRY_SIZE; int i; for (i = 0; i < entries; i += entries_per_page) set_aliased_prot(ldt + i, PAGE_KERNEL); } static void xen_set_ldt(const void *addr, unsigned entries) { struct mmuext_op *op; struct multicall_space mcs = xen_mc_entry(sizeof(*op)); trace_xen_cpu_set_ldt(addr, entries); op = mcs.args; op->cmd = MMUEXT_SET_LDT; op->arg1.linear_addr = (unsigned long)addr; op->arg2.nr_ents = entries; MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF); xen_mc_issue(PARAVIRT_LAZY_CPU); } static void xen_load_gdt(const struct desc_ptr *dtr) { unsigned long va = dtr->address; unsigned int size = dtr->size + 1; unsigned long pfn, mfn; int level; pte_t *ptep; void *virt; /* @size should be at most GDT_SIZE which is smaller than PAGE_SIZE. */ BUG_ON(size > PAGE_SIZE); BUG_ON(va & ~PAGE_MASK); /* * The GDT is per-cpu and is in the percpu data area. * That can be virtually mapped, so we need to do a * page-walk to get the underlying MFN for the * hypercall. The page can also be in the kernel's * linear range, so we need to RO that mapping too. */ ptep = lookup_address(va, &level); BUG_ON(ptep == NULL); pfn = pte_pfn(*ptep); mfn = pfn_to_mfn(pfn); virt = __va(PFN_PHYS(pfn)); make_lowmem_page_readonly((void *)va); make_lowmem_page_readonly(virt); if (HYPERVISOR_set_gdt(&mfn, size / sizeof(struct desc_struct))) BUG(); } /* * load_gdt for early boot, when the gdt is only mapped once */ static void __init xen_load_gdt_boot(const struct desc_ptr *dtr) { unsigned long va = dtr->address; unsigned int size = dtr->size + 1; unsigned long pfn, mfn; pte_t pte; /* @size should be at most GDT_SIZE which is smaller than PAGE_SIZE. */ BUG_ON(size > PAGE_SIZE); BUG_ON(va & ~PAGE_MASK); pfn = virt_to_pfn(va); mfn = pfn_to_mfn(pfn); pte = pfn_pte(pfn, PAGE_KERNEL_RO); if (HYPERVISOR_update_va_mapping((unsigned long)va, pte, 0)) BUG(); if (HYPERVISOR_set_gdt(&mfn, size / sizeof(struct desc_struct))) BUG(); } static inline bool desc_equal(const struct desc_struct *d1, const struct desc_struct *d2) { return !memcmp(d1, d2, sizeof(*d1)); } static void load_TLS_descriptor(struct thread_struct *t, unsigned int cpu, unsigned int i) { struct desc_struct *shadow = &per_cpu(shadow_tls_desc, cpu).desc[i]; struct desc_struct *gdt; xmaddr_t maddr; struct multicall_space mc; if (desc_equal(shadow, &t->tls_array[i])) return; *shadow = t->tls_array[i]; gdt = get_cpu_gdt_rw(cpu); maddr = arbitrary_virt_to_machine(&gdt[GDT_ENTRY_TLS_MIN+i]); mc = __xen_mc_entry(0); MULTI_update_descriptor(mc.mc, maddr.maddr, t->tls_array[i]); } static void xen_load_tls(struct thread_struct *t, unsigned int cpu) { /* * XXX sleazy hack: If we're being called in a lazy-cpu zone * and lazy gs handling is enabled, it means we're in a * context switch, and %gs has just been saved. This means we * can zero it out to prevent faults on exit from the * hypervisor if the next process has no %gs. Either way, it * has been saved, and the new value will get loaded properly. * This will go away as soon as Xen has been modified to not * save/restore %gs for normal hypercalls. * * On x86_64, this hack is not used for %gs, because gs points * to KERNEL_GS_BASE (and uses it for PDA references), so we * must not zero %gs on x86_64 * * For x86_64, we need to zero %fs, otherwise we may get an * exception between the new %fs descriptor being loaded and * %fs being effectively cleared at __switch_to(). */ if (paravirt_get_lazy_mode() == PARAVIRT_LAZY_CPU) { #ifdef CONFIG_X86_32 lazy_load_gs(0); #else loadsegment(fs, 0); #endif } xen_mc_batch(); load_TLS_descriptor(t, cpu, 0); load_TLS_descriptor(t, cpu, 1); load_TLS_descriptor(t, cpu, 2); xen_mc_issue(PARAVIRT_LAZY_CPU); } #ifdef CONFIG_X86_64 static void xen_load_gs_index(unsigned int idx) { if (HYPERVISOR_set_segment_base(SEGBASE_GS_USER_SEL, idx)) BUG(); } #endif static void xen_write_ldt_entry(struct desc_struct *dt, int entrynum, const void *ptr) { xmaddr_t mach_lp = arbitrary_virt_to_machine(&dt[entrynum]); u64 entry = *(u64 *)ptr; trace_xen_cpu_write_ldt_entry(dt, entrynum, entry); preempt_disable(); xen_mc_flush(); if (HYPERVISOR_update_descriptor(mach_lp.maddr, entry)) BUG(); preempt_enable(); } #ifdef CONFIG_X86_64 void noist_exc_debug(struct pt_regs *regs); DEFINE_IDTENTRY_RAW(xenpv_exc_nmi) { /* On Xen PV, NMI doesn't use IST. The C part is the sane as native. */ exc_nmi(regs); } DEFINE_IDTENTRY_RAW(xenpv_exc_debug) { /* * There's no IST on Xen PV, but we still need to dispatch * to the correct handler. */ if (user_mode(regs)) noist_exc_debug(regs); else exc_debug(regs); } struct trap_array_entry { void (*orig)(void); void (*xen)(void); bool ist_okay; }; #define TRAP_ENTRY(func, ist_ok) { \ .orig = asm_##func, \ .xen = xen_asm_##func, \ .ist_okay = ist_ok } #define TRAP_ENTRY_REDIR(func, ist_ok) { \ .orig = asm_##func, \ .xen = xen_asm_xenpv_##func, \ .ist_okay = ist_ok } static struct trap_array_entry trap_array[] = { TRAP_ENTRY_REDIR(exc_debug, true ), TRAP_ENTRY(exc_double_fault, true ), #ifdef CONFIG_X86_MCE TRAP_ENTRY(exc_machine_check, true ), #endif TRAP_ENTRY_REDIR(exc_nmi, true ), TRAP_ENTRY(exc_int3, false ), TRAP_ENTRY(exc_overflow, false ), #ifdef CONFIG_IA32_EMULATION { entry_INT80_compat, xen_entry_INT80_compat, false }, #endif TRAP_ENTRY(exc_page_fault, false ), TRAP_ENTRY(exc_divide_error, false ), TRAP_ENTRY(exc_bounds, false ), TRAP_ENTRY(exc_invalid_op, false ), TRAP_ENTRY(exc_device_not_available, false ), TRAP_ENTRY(exc_coproc_segment_overrun, false ), TRAP_ENTRY(exc_invalid_tss, false ), TRAP_ENTRY(exc_segment_not_present, false ), TRAP_ENTRY(exc_stack_segment, false ), TRAP_ENTRY(exc_general_protection, false ), TRAP_ENTRY(exc_spurious_interrupt_bug, false ), TRAP_ENTRY(exc_coprocessor_error, false ), TRAP_ENTRY(exc_alignment_check, false ), TRAP_ENTRY(exc_simd_coprocessor_error, false ), }; static bool __ref get_trap_addr(void **addr, unsigned int ist) { unsigned int nr; bool ist_okay = false; /* * Replace trap handler addresses by Xen specific ones. * Check for known traps using IST and whitelist them. * The debugger ones are the only ones we care about. * Xen will handle faults like double_fault, so we should never see * them. Warn if there's an unexpected IST-using fault handler. */ for (nr = 0; nr < ARRAY_SIZE(trap_array); nr++) { struct trap_array_entry *entry = trap_array + nr; if (*addr == entry->orig) { *addr = entry->xen; ist_okay = entry->ist_okay; break; } } if (nr == ARRAY_SIZE(trap_array) && *addr >= (void *)early_idt_handler_array[0] && *addr < (void *)early_idt_handler_array[NUM_EXCEPTION_VECTORS]) { nr = (*addr - (void *)early_idt_handler_array[0]) / EARLY_IDT_HANDLER_SIZE; *addr = (void *)xen_early_idt_handler_array[nr]; } if (WARN_ON(ist != 0 && !ist_okay)) return false; return true; } #endif static int cvt_gate_to_trap(int vector, const gate_desc *val, struct trap_info *info) { unsigned long addr; if (val->bits.type != GATE_TRAP && val->bits.type != GATE_INTERRUPT) return 0; info->vector = vector; addr = gate_offset(val); #ifdef CONFIG_X86_64 if (!get_trap_addr((void **)&addr, val->bits.ist)) return 0; #endif /* CONFIG_X86_64 */ info->address = addr; info->cs = gate_segment(val); info->flags = val->bits.dpl; /* interrupt gates clear IF */ if (val->bits.type == GATE_INTERRUPT) info->flags |= 1 << 2; return 1; } /* Locations of each CPU's IDT */ static DEFINE_PER_CPU(struct desc_ptr, idt_desc); /* Set an IDT entry. If the entry is part of the current IDT, then also update Xen. */ static void xen_write_idt_entry(gate_desc *dt, int entrynum, const gate_desc *g) { unsigned long p = (unsigned long)&dt[entrynum]; unsigned long start, end; trace_xen_cpu_write_idt_entry(dt, entrynum, g); preempt_disable(); start = __this_cpu_read(idt_desc.address); end = start + __this_cpu_read(idt_desc.size) + 1; xen_mc_flush(); native_write_idt_entry(dt, entrynum, g); if (p >= start && (p + 8) <= end) { struct trap_info info[2]; info[1].address = 0; if (cvt_gate_to_trap(entrynum, g, &info[0])) if (HYPERVISOR_set_trap_table(info)) BUG(); } preempt_enable(); } static void xen_convert_trap_info(const struct desc_ptr *desc, struct trap_info *traps) { unsigned in, out, count; count = (desc->size+1) / sizeof(gate_desc); BUG_ON(count > 256); for (in = out = 0; in < count; in++) { gate_desc *entry = (gate_desc *)(desc->address) + in; if (cvt_gate_to_trap(in, entry, &traps[out])) out++; } traps[out].address = 0; } void xen_copy_trap_info(struct trap_info *traps) { const struct desc_ptr *desc = this_cpu_ptr(&idt_desc); xen_convert_trap_info(desc, traps); } /* Load a new IDT into Xen. In principle this can be per-CPU, so we hold a spinlock to protect the static traps[] array (static because it avoids allocation, and saves stack space). */ static void xen_load_idt(const struct desc_ptr *desc) { static DEFINE_SPINLOCK(lock); static struct trap_info traps[257]; trace_xen_cpu_load_idt(desc); spin_lock(&lock); memcpy(this_cpu_ptr(&idt_desc), desc, sizeof(idt_desc)); xen_convert_trap_info(desc, traps); xen_mc_flush(); if (HYPERVISOR_set_trap_table(traps)) BUG(); spin_unlock(&lock); } /* Write a GDT descriptor entry. Ignore LDT descriptors, since they're handled differently. */ static void xen_write_gdt_entry(struct desc_struct *dt, int entry, const void *desc, int type) { trace_xen_cpu_write_gdt_entry(dt, entry, desc, type); preempt_disable(); switch (type) { case DESC_LDT: case DESC_TSS: /* ignore */ break; default: { xmaddr_t maddr = arbitrary_virt_to_machine(&dt[entry]); xen_mc_flush(); if (HYPERVISOR_update_descriptor(maddr.maddr, *(u64 *)desc)) BUG(); } } preempt_enable(); } /* * Version of write_gdt_entry for use at early boot-time needed to * update an entry as simply as possible. */ static void __init xen_write_gdt_entry_boot(struct desc_struct *dt, int entry, const void *desc, int type) { trace_xen_cpu_write_gdt_entry(dt, entry, desc, type); switch (type) { case DESC_LDT: case DESC_TSS: /* ignore */ break; default: { xmaddr_t maddr = virt_to_machine(&dt[entry]); if (HYPERVISOR_update_descriptor(maddr.maddr, *(u64 *)desc)) dt[entry] = *(struct desc_struct *)desc; } } } static void xen_load_sp0(unsigned long sp0) { struct multicall_space mcs; mcs = xen_mc_entry(0); MULTI_stack_switch(mcs.mc, __KERNEL_DS, sp0); xen_mc_issue(PARAVIRT_LAZY_CPU); this_cpu_write(cpu_tss_rw.x86_tss.sp0, sp0); } #ifdef CONFIG_X86_IOPL_IOPERM static void xen_invalidate_io_bitmap(void) { struct physdev_set_iobitmap iobitmap = { .bitmap = 0, .nr_ports = 0, }; native_tss_invalidate_io_bitmap(); HYPERVISOR_physdev_op(PHYSDEVOP_set_iobitmap, &iobitmap); } static void xen_update_io_bitmap(void) { struct physdev_set_iobitmap iobitmap; struct tss_struct *tss = this_cpu_ptr(&cpu_tss_rw); native_tss_update_io_bitmap(); iobitmap.bitmap = (uint8_t *)(&tss->x86_tss) + tss->x86_tss.io_bitmap_base; if (tss->x86_tss.io_bitmap_base == IO_BITMAP_OFFSET_INVALID) iobitmap.nr_ports = 0; else iobitmap.nr_ports = IO_BITMAP_BITS; HYPERVISOR_physdev_op(PHYSDEVOP_set_iobitmap, &iobitmap); } #endif static void xen_io_delay(void) { } static DEFINE_PER_CPU(unsigned long, xen_cr0_value); static unsigned long xen_read_cr0(void) { unsigned long cr0 = this_cpu_read(xen_cr0_value); if (unlikely(cr0 == 0)) { cr0 = native_read_cr0(); this_cpu_write(xen_cr0_value, cr0); } return cr0; } static void xen_write_cr0(unsigned long cr0) { struct multicall_space mcs; this_cpu_write(xen_cr0_value, cr0); /* Only pay attention to cr0.TS; everything else is ignored. */ mcs = xen_mc_entry(0); MULTI_fpu_taskswitch(mcs.mc, (cr0 & X86_CR0_TS) != 0); xen_mc_issue(PARAVIRT_LAZY_CPU); } static void xen_write_cr4(unsigned long cr4) { cr4 &= ~(X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PCE); native_write_cr4(cr4); } static u64 xen_read_msr_safe(unsigned int msr, int *err) { u64 val; if (pmu_msr_read(msr, &val, err)) return val; val = native_read_msr_safe(msr, err); switch (msr) { case MSR_IA32_APICBASE: val &= ~X2APIC_ENABLE; break; } return val; } static int xen_write_msr_safe(unsigned int msr, unsigned low, unsigned high) { int ret; #ifdef CONFIG_X86_64 unsigned int which; u64 base; #endif ret = 0; switch (msr) { #ifdef CONFIG_X86_64 case MSR_FS_BASE: which = SEGBASE_FS; goto set; case MSR_KERNEL_GS_BASE: which = SEGBASE_GS_USER; goto set; case MSR_GS_BASE: which = SEGBASE_GS_KERNEL; goto set; set: base = ((u64)high << 32) | low; if (HYPERVISOR_set_segment_base(which, base) != 0) ret = -EIO; break; #endif case MSR_STAR: case MSR_CSTAR: case MSR_LSTAR: case MSR_SYSCALL_MASK: case MSR_IA32_SYSENTER_CS: case MSR_IA32_SYSENTER_ESP: case MSR_IA32_SYSENTER_EIP: /* Fast syscall setup is all done in hypercalls, so these are all ignored. Stub them out here to stop Xen console noise. */ break; default: if (!pmu_msr_write(msr, low, high, &ret)) ret = native_write_msr_safe(msr, low, high); } return ret; } static u64 xen_read_msr(unsigned int msr) { /* * This will silently swallow a #GP from RDMSR. It may be worth * changing that. */ int err; return xen_read_msr_safe(msr, &err); } static void xen_write_msr(unsigned int msr, unsigned low, unsigned high) { /* * This will silently swallow a #GP from WRMSR. It may be worth * changing that. */ xen_write_msr_safe(msr, low, high); } /* This is called once we have the cpu_possible_mask */ void __init xen_setup_vcpu_info_placement(void) { int cpu; for_each_possible_cpu(cpu) { /* Set up direct vCPU id mapping for PV guests. */ per_cpu(xen_vcpu_id, cpu) = cpu; /* * xen_vcpu_setup(cpu) can fail -- in which case it * falls back to the shared_info version for cpus * where xen_vcpu_nr(cpu) < MAX_VIRT_CPUS. * * xen_cpu_up_prepare_pv() handles the rest by failing * them in hotplug. */ (void) xen_vcpu_setup(cpu); } /* * xen_vcpu_setup managed to place the vcpu_info within the * percpu area for all cpus, so make use of it. */ if (xen_have_vcpu_info_placement) { pv_ops.irq.save_fl = __PV_IS_CALLEE_SAVE(xen_save_fl_direct); pv_ops.irq.restore_fl = __PV_IS_CALLEE_SAVE(xen_restore_fl_direct); pv_ops.irq.irq_disable = __PV_IS_CALLEE_SAVE(xen_irq_disable_direct); pv_ops.irq.irq_enable = __PV_IS_CALLEE_SAVE(xen_irq_enable_direct); pv_ops.mmu.read_cr2 = __PV_IS_CALLEE_SAVE(xen_read_cr2_direct); } } static const struct pv_info xen_info __initconst = { .shared_kernel_pmd = 0, #ifdef CONFIG_X86_64 .extra_user_64bit_cs = FLAT_USER_CS64, #endif .name = "Xen", }; static const struct pv_cpu_ops xen_cpu_ops __initconst = { .cpuid = xen_cpuid, .set_debugreg = xen_set_debugreg, .get_debugreg = xen_get_debugreg, .read_cr0 = xen_read_cr0, .write_cr0 = xen_write_cr0, .write_cr4 = xen_write_cr4, .wbinvd = native_wbinvd, .read_msr = xen_read_msr, .write_msr = xen_write_msr, .read_msr_safe = xen_read_msr_safe, .write_msr_safe = xen_write_msr_safe, .read_pmc = xen_read_pmc, .iret = xen_iret, #ifdef CONFIG_X86_64 .usergs_sysret64 = xen_sysret64, #endif .load_tr_desc = paravirt_nop, .set_ldt = xen_set_ldt, .load_gdt = xen_load_gdt, .load_idt = xen_load_idt, .load_tls = xen_load_tls, #ifdef CONFIG_X86_64 .load_gs_index = xen_load_gs_index, #endif .alloc_ldt = xen_alloc_ldt, .free_ldt = xen_free_ldt, .store_tr = xen_store_tr, .write_ldt_entry = xen_write_ldt_entry, .write_gdt_entry = xen_write_gdt_entry, .write_idt_entry = xen_write_idt_entry, .load_sp0 = xen_load_sp0, #ifdef CONFIG_X86_IOPL_IOPERM .invalidate_io_bitmap = xen_invalidate_io_bitmap, .update_io_bitmap = xen_update_io_bitmap, #endif .io_delay = xen_io_delay, /* Xen takes care of %gs when switching to usermode for us */ .swapgs = paravirt_nop, .start_context_switch = paravirt_start_context_switch, .end_context_switch = xen_end_context_switch, }; static void xen_restart(char *msg) { xen_reboot(SHUTDOWN_reboot); } static void xen_machine_halt(void) { xen_reboot(SHUTDOWN_poweroff); } static void xen_machine_power_off(void) { if (pm_power_off) pm_power_off(); xen_reboot(SHUTDOWN_poweroff); } static void xen_crash_shutdown(struct pt_regs *regs) { xen_reboot(SHUTDOWN_crash); } static const struct machine_ops xen_machine_ops __initconst = { .restart = xen_restart, .halt = xen_machine_halt, .power_off = xen_machine_power_off, .shutdown = xen_machine_halt, .crash_shutdown = xen_crash_shutdown, .emergency_restart = xen_emergency_restart, }; static unsigned char xen_get_nmi_reason(void) { unsigned char reason = 0; /* Construct a value which looks like it came from port 0x61. */ if (test_bit(_XEN_NMIREASON_io_error, &HYPERVISOR_shared_info->arch.nmi_reason)) reason |= NMI_REASON_IOCHK; if (test_bit(_XEN_NMIREASON_pci_serr, &HYPERVISOR_shared_info->arch.nmi_reason)) reason |= NMI_REASON_SERR; return reason; } static void __init xen_boot_params_init_edd(void) { #if IS_ENABLED(CONFIG_EDD) struct xen_platform_op op; struct edd_info *edd_info; u32 *mbr_signature; unsigned nr; int ret; edd_info = boot_params.eddbuf; mbr_signature = boot_params.edd_mbr_sig_buffer; op.cmd = XENPF_firmware_info; op.u.firmware_info.type = XEN_FW_DISK_INFO; for (nr = 0; nr < EDDMAXNR; nr++) { struct edd_info *info = edd_info + nr; op.u.firmware_info.index = nr; info->params.length = sizeof(info->params); set_xen_guest_handle(op.u.firmware_info.u.disk_info.edd_params, &info->params); ret = HYPERVISOR_platform_op(&op); if (ret) break; #define C(x) info->x = op.u.firmware_info.u.disk_info.x C(device); C(version); C(interface_support); C(legacy_max_cylinder); C(legacy_max_head); C(legacy_sectors_per_track); #undef C } boot_params.eddbuf_entries = nr; op.u.firmware_info.type = XEN_FW_DISK_MBR_SIGNATURE; for (nr = 0; nr < EDD_MBR_SIG_MAX; nr++) { op.u.firmware_info.index = nr; ret = HYPERVISOR_platform_op(&op); if (ret) break; mbr_signature[nr] = op.u.firmware_info.u.disk_mbr_signature.mbr_signature; } boot_params.edd_mbr_sig_buf_entries = nr; #endif } /* * Set up the GDT and segment registers for -fstack-protector. Until * we do this, we have to be careful not to call any stack-protected * function, which is most of the kernel. */ static void __init xen_setup_gdt(int cpu) { pv_ops.cpu.write_gdt_entry = xen_write_gdt_entry_boot; pv_ops.cpu.load_gdt = xen_load_gdt_boot; setup_stack_canary_segment(cpu); switch_to_new_gdt(cpu); pv_ops.cpu.write_gdt_entry = xen_write_gdt_entry; pv_ops.cpu.load_gdt = xen_load_gdt; } static void __init xen_dom0_set_legacy_features(void) { x86_platform.legacy.rtc = 1; } /* First C function to be called on Xen boot */ asmlinkage __visible void __init xen_start_kernel(void) { struct physdev_set_iopl set_iopl; unsigned long initrd_start = 0; int rc; if (!xen_start_info) return; xen_domain_type = XEN_PV_DOMAIN; xen_start_flags = xen_start_info->flags; xen_setup_features(); /* Install Xen paravirt ops */ pv_info = xen_info; pv_ops.init.patch = paravirt_patch_default; pv_ops.cpu = xen_cpu_ops; xen_init_irq_ops(); /* * Setup xen_vcpu early because it is needed for * local_irq_disable(), irqs_disabled(), e.g. in printk(). * * Don't do the full vcpu_info placement stuff until we have * the cpu_possible_mask and a non-dummy shared_info. */ xen_vcpu_info_reset(0); x86_platform.get_nmi_reason = xen_get_nmi_reason; x86_init.resources.memory_setup = xen_memory_setup; x86_init.irqs.intr_mode_select = x86_init_noop; x86_init.irqs.intr_mode_init = x86_init_noop; x86_init.oem.arch_setup = xen_arch_setup; x86_init.oem.banner = xen_banner; x86_init.hyper.init_platform = xen_pv_init_platform; x86_init.hyper.guest_late_init = xen_pv_guest_late_init; /* * Set up some pagetable state before starting to set any ptes. */ xen_setup_machphys_mapping(); xen_init_mmu_ops(); /* Prevent unwanted bits from being set in PTEs. */ __supported_pte_mask &= ~_PAGE_GLOBAL; __default_kernel_pte_mask &= ~_PAGE_GLOBAL; /* * Prevent page tables from being allocated in highmem, even * if CONFIG_HIGHPTE is enabled. */ __userpte_alloc_gfp &= ~__GFP_HIGHMEM; /* Get mfn list */ xen_build_dynamic_phys_to_machine(); /* * Set up kernel GDT and segment registers, mainly so that * -fstack-protector code can be executed. */ xen_setup_gdt(0); /* Work out if we support NX */ get_cpu_cap(&boot_cpu_data); x86_configure_nx(); /* Determine virtual and physical address sizes */ get_cpu_address_sizes(&boot_cpu_data); /* Let's presume PV guests always boot on vCPU with id 0. */ per_cpu(xen_vcpu_id, 0) = 0; idt_setup_early_handler(); xen_init_capabilities(); #ifdef CONFIG_X86_LOCAL_APIC /* * set up the basic apic ops. */ xen_init_apic(); #endif if (xen_feature(XENFEAT_mmu_pt_update_preserve_ad)) { pv_ops.mmu.ptep_modify_prot_start = xen_ptep_modify_prot_start; pv_ops.mmu.ptep_modify_prot_commit = xen_ptep_modify_prot_commit; } machine_ops = xen_machine_ops; /* * The only reliable way to retain the initial address of the * percpu gdt_page is to remember it here, so we can go and * mark it RW later, when the initial percpu area is freed. */ xen_initial_gdt = &per_cpu(gdt_page, 0); xen_smp_init(); #ifdef CONFIG_ACPI_NUMA /* * The pages we from Xen are not related to machine pages, so * any NUMA information the kernel tries to get from ACPI will * be meaningless. Prevent it from trying. */ acpi_numa = -1; #endif WARN_ON(xen_cpuhp_setup(xen_cpu_up_prepare_pv, xen_cpu_dead_pv)); local_irq_disable(); early_boot_irqs_disabled = true; xen_raw_console_write("mapping kernel into physical memory\n"); xen_setup_kernel_pagetable((pgd_t *)xen_start_info->pt_base, xen_start_info->nr_pages); xen_reserve_special_pages(); /* keep using Xen gdt for now; no urgent need to change it */ #ifdef CONFIG_X86_32 pv_info.kernel_rpl = 1; if (xen_feature(XENFEAT_supervisor_mode_kernel)) pv_info.kernel_rpl = 0; #else pv_info.kernel_rpl = 0; #endif /* set the limit of our address space */ xen_reserve_top(); /* * We used to do this in xen_arch_setup, but that is too late * on AMD were early_cpu_init (run before ->arch_setup()) calls * early_amd_init which pokes 0xcf8 port. */ set_iopl.iopl = 1; rc = HYPERVISOR_physdev_op(PHYSDEVOP_set_iopl, &set_iopl); if (rc != 0) xen_raw_printk("physdev_op failed %d\n", rc); #ifdef CONFIG_X86_32 /* set up basic CPUID stuff */ cpu_detect(&new_cpu_data); set_cpu_cap(&new_cpu_data, X86_FEATURE_FPU); new_cpu_data.x86_capability[CPUID_1_EDX] = cpuid_edx(1); #endif if (xen_start_info->mod_start) { if (xen_start_info->flags & SIF_MOD_START_PFN) initrd_start = PFN_PHYS(xen_start_info->mod_start); else initrd_start = __pa(xen_start_info->mod_start); } /* Poke various useful things into boot_params */ boot_params.hdr.type_of_loader = (9 << 4) | 0; boot_params.hdr.ramdisk_image = initrd_start; boot_params.hdr.ramdisk_size = xen_start_info->mod_len; boot_params.hdr.cmd_line_ptr = __pa(xen_start_info->cmd_line); boot_params.hdr.hardware_subarch = X86_SUBARCH_XEN; if (!xen_initial_domain()) { add_preferred_console("xenboot", 0, NULL); if (pci_xen) x86_init.pci.arch_init = pci_xen_init; } else { const struct dom0_vga_console_info *info = (void *)((char *)xen_start_info + xen_start_info->console.dom0.info_off); struct xen_platform_op op = { .cmd = XENPF_firmware_info, .interface_version = XENPF_INTERFACE_VERSION, .u.firmware_info.type = XEN_FW_KBD_SHIFT_FLAGS, }; x86_platform.set_legacy_features = xen_dom0_set_legacy_features; xen_init_vga(info, xen_start_info->console.dom0.info_size); xen_start_info->console.domU.mfn = 0; xen_start_info->console.domU.evtchn = 0; if (HYPERVISOR_platform_op(&op) == 0) boot_params.kbd_status = op.u.firmware_info.u.kbd_shift_flags; /* Make sure ACS will be enabled */ pci_request_acs(); xen_acpi_sleep_register(); /* Avoid searching for BIOS MP tables */ x86_init.mpparse.find_smp_config = x86_init_noop; x86_init.mpparse.get_smp_config = x86_init_uint_noop; xen_boot_params_init_edd(); } if (!boot_params.screen_info.orig_video_isVGA) add_preferred_console("tty", 0, NULL); add_preferred_console("hvc", 0, NULL); if (boot_params.screen_info.orig_video_isVGA) add_preferred_console("tty", 0, NULL); #ifdef CONFIG_PCI /* PCI BIOS service won't work from a PV guest. */ pci_probe &= ~PCI_PROBE_BIOS; #endif xen_raw_console_write("about to get started...\n"); /* We need this for printk timestamps */ xen_setup_runstate_info(0); xen_efi_init(&boot_params); /* Start the world */ #ifdef CONFIG_X86_32 i386_start_kernel(); #else cr4_init_shadow(); /* 32b kernel does this in i386_start_kernel() */ x86_64_start_reservations((char *)__pa_symbol(&boot_params)); #endif } static int xen_cpu_up_prepare_pv(unsigned int cpu) { int rc; if (per_cpu(xen_vcpu, cpu) == NULL) return -ENODEV; xen_setup_timer(cpu); rc = xen_smp_intr_init(cpu); if (rc) { WARN(1, "xen_smp_intr_init() for CPU %d failed: %d\n", cpu, rc); return rc; } rc = xen_smp_intr_init_pv(cpu); if (rc) { WARN(1, "xen_smp_intr_init_pv() for CPU %d failed: %d\n", cpu, rc); return rc; } return 0; } static int xen_cpu_dead_pv(unsigned int cpu) { xen_smp_intr_free(cpu); xen_smp_intr_free_pv(cpu); xen_teardown_timer(cpu); return 0; } static uint32_t __init xen_platform_pv(void) { if (xen_pv_domain()) return xen_cpuid_base(); return 0; } const __initconst struct hypervisor_x86 x86_hyper_xen_pv = { .name = "Xen PV", .detect = xen_platform_pv, .type = X86_HYPER_XEN_PV, .runtime.pin_vcpu = xen_pin_vcpu, .ignore_nopv = true, };
./CrossVul/dataset_final_sorted/CWE-276/c/good_4225_5
crossvul-cpp_data_bad_4225_5
// SPDX-License-Identifier: GPL-2.0 /* * Core of Xen paravirt_ops implementation. * * This file contains the xen_paravirt_ops structure itself, and the * implementations for: * - privileged instructions * - interrupt flags * - segment operations * - booting and setup * * Jeremy Fitzhardinge <jeremy@xensource.com>, XenSource Inc, 2007 */ #include <linux/cpu.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/smp.h> #include <linux/preempt.h> #include <linux/hardirq.h> #include <linux/percpu.h> #include <linux/delay.h> #include <linux/start_kernel.h> #include <linux/sched.h> #include <linux/kprobes.h> #include <linux/memblock.h> #include <linux/export.h> #include <linux/mm.h> #include <linux/page-flags.h> #include <linux/highmem.h> #include <linux/console.h> #include <linux/pci.h> #include <linux/gfp.h> #include <linux/edd.h> #include <linux/frame.h> #include <xen/xen.h> #include <xen/events.h> #include <xen/interface/xen.h> #include <xen/interface/version.h> #include <xen/interface/physdev.h> #include <xen/interface/vcpu.h> #include <xen/interface/memory.h> #include <xen/interface/nmi.h> #include <xen/interface/xen-mca.h> #include <xen/features.h> #include <xen/page.h> #include <xen/hvc-console.h> #include <xen/acpi.h> #include <asm/paravirt.h> #include <asm/apic.h> #include <asm/page.h> #include <asm/xen/pci.h> #include <asm/xen/hypercall.h> #include <asm/xen/hypervisor.h> #include <asm/xen/cpuid.h> #include <asm/fixmap.h> #include <asm/processor.h> #include <asm/proto.h> #include <asm/msr-index.h> #include <asm/traps.h> #include <asm/setup.h> #include <asm/desc.h> #include <asm/pgalloc.h> #include <asm/tlbflush.h> #include <asm/reboot.h> #include <asm/stackprotector.h> #include <asm/hypervisor.h> #include <asm/mach_traps.h> #include <asm/mwait.h> #include <asm/pci_x86.h> #include <asm/cpu.h> #ifdef CONFIG_X86_IOPL_IOPERM #include <asm/io_bitmap.h> #endif #ifdef CONFIG_ACPI #include <linux/acpi.h> #include <asm/acpi.h> #include <acpi/pdc_intel.h> #include <acpi/processor.h> #include <xen/interface/platform.h> #endif #include "xen-ops.h" #include "mmu.h" #include "smp.h" #include "multicalls.h" #include "pmu.h" #include "../kernel/cpu/cpu.h" /* get_cpu_cap() */ void *xen_initial_gdt; static int xen_cpu_up_prepare_pv(unsigned int cpu); static int xen_cpu_dead_pv(unsigned int cpu); struct tls_descs { struct desc_struct desc[3]; }; /* * Updating the 3 TLS descriptors in the GDT on every task switch is * surprisingly expensive so we avoid updating them if they haven't * changed. Since Xen writes different descriptors than the one * passed in the update_descriptor hypercall we keep shadow copies to * compare against. */ static DEFINE_PER_CPU(struct tls_descs, shadow_tls_desc); static void __init xen_banner(void) { unsigned version = HYPERVISOR_xen_version(XENVER_version, NULL); struct xen_extraversion extra; HYPERVISOR_xen_version(XENVER_extraversion, &extra); pr_info("Booting paravirtualized kernel on %s\n", pv_info.name); printk(KERN_INFO "Xen version: %d.%d%s%s\n", version >> 16, version & 0xffff, extra.extraversion, xen_feature(XENFEAT_mmu_pt_update_preserve_ad) ? " (preserve-AD)" : ""); #ifdef CONFIG_X86_32 pr_warn("WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!\n" "Support for running as 32-bit PV-guest under Xen will soon be removed\n" "from the Linux kernel!\n" "Please use either a 64-bit kernel or switch to HVM or PVH mode!\n" "WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!\n"); #endif } static void __init xen_pv_init_platform(void) { populate_extra_pte(fix_to_virt(FIX_PARAVIRT_BOOTMAP)); set_fixmap(FIX_PARAVIRT_BOOTMAP, xen_start_info->shared_info); HYPERVISOR_shared_info = (void *)fix_to_virt(FIX_PARAVIRT_BOOTMAP); /* xen clock uses per-cpu vcpu_info, need to init it for boot cpu */ xen_vcpu_info_reset(0); /* pvclock is in shared info area */ xen_init_time_ops(); } static void __init xen_pv_guest_late_init(void) { #ifndef CONFIG_SMP /* Setup shared vcpu info for non-smp configurations */ xen_setup_vcpu_info_placement(); #endif } /* Check if running on Xen version (major, minor) or later */ bool xen_running_on_version_or_later(unsigned int major, unsigned int minor) { unsigned int version; if (!xen_domain()) return false; version = HYPERVISOR_xen_version(XENVER_version, NULL); if ((((version >> 16) == major) && ((version & 0xffff) >= minor)) || ((version >> 16) > major)) return true; return false; } static __read_mostly unsigned int cpuid_leaf5_ecx_val; static __read_mostly unsigned int cpuid_leaf5_edx_val; static void xen_cpuid(unsigned int *ax, unsigned int *bx, unsigned int *cx, unsigned int *dx) { unsigned maskebx = ~0; /* * Mask out inconvenient features, to try and disable as many * unsupported kernel subsystems as possible. */ switch (*ax) { case CPUID_MWAIT_LEAF: /* Synthesize the values.. */ *ax = 0; *bx = 0; *cx = cpuid_leaf5_ecx_val; *dx = cpuid_leaf5_edx_val; return; case 0xb: /* Suppress extended topology stuff */ maskebx = 0; break; } asm(XEN_EMULATE_PREFIX "cpuid" : "=a" (*ax), "=b" (*bx), "=c" (*cx), "=d" (*dx) : "0" (*ax), "2" (*cx)); *bx &= maskebx; } STACK_FRAME_NON_STANDARD(xen_cpuid); /* XEN_EMULATE_PREFIX */ static bool __init xen_check_mwait(void) { #ifdef CONFIG_ACPI struct xen_platform_op op = { .cmd = XENPF_set_processor_pminfo, .u.set_pminfo.id = -1, .u.set_pminfo.type = XEN_PM_PDC, }; uint32_t buf[3]; unsigned int ax, bx, cx, dx; unsigned int mwait_mask; /* We need to determine whether it is OK to expose the MWAIT * capability to the kernel to harvest deeper than C3 states from ACPI * _CST using the processor_harvest_xen.c module. For this to work, we * need to gather the MWAIT_LEAF values (which the cstate.c code * checks against). The hypervisor won't expose the MWAIT flag because * it would break backwards compatibility; so we will find out directly * from the hardware and hypercall. */ if (!xen_initial_domain()) return false; /* * When running under platform earlier than Xen4.2, do not expose * mwait, to avoid the risk of loading native acpi pad driver */ if (!xen_running_on_version_or_later(4, 2)) return false; ax = 1; cx = 0; native_cpuid(&ax, &bx, &cx, &dx); mwait_mask = (1 << (X86_FEATURE_EST % 32)) | (1 << (X86_FEATURE_MWAIT % 32)); if ((cx & mwait_mask) != mwait_mask) return false; /* We need to emulate the MWAIT_LEAF and for that we need both * ecx and edx. The hypercall provides only partial information. */ ax = CPUID_MWAIT_LEAF; bx = 0; cx = 0; dx = 0; native_cpuid(&ax, &bx, &cx, &dx); /* Ask the Hypervisor whether to clear ACPI_PDC_C_C2C3_FFH. If so, * don't expose MWAIT_LEAF and let ACPI pick the IOPORT version of C3. */ buf[0] = ACPI_PDC_REVISION_ID; buf[1] = 1; buf[2] = (ACPI_PDC_C_CAPABILITY_SMP | ACPI_PDC_EST_CAPABILITY_SWSMP); set_xen_guest_handle(op.u.set_pminfo.pdc, buf); if ((HYPERVISOR_platform_op(&op) == 0) && (buf[2] & (ACPI_PDC_C_C1_FFH | ACPI_PDC_C_C2C3_FFH))) { cpuid_leaf5_ecx_val = cx; cpuid_leaf5_edx_val = dx; } return true; #else return false; #endif } static bool __init xen_check_xsave(void) { unsigned int cx, xsave_mask; cx = cpuid_ecx(1); xsave_mask = (1 << (X86_FEATURE_XSAVE % 32)) | (1 << (X86_FEATURE_OSXSAVE % 32)); /* Xen will set CR4.OSXSAVE if supported and not disabled by force */ return (cx & xsave_mask) == xsave_mask; } static void __init xen_init_capabilities(void) { setup_force_cpu_cap(X86_FEATURE_XENPV); setup_clear_cpu_cap(X86_FEATURE_DCA); setup_clear_cpu_cap(X86_FEATURE_APERFMPERF); setup_clear_cpu_cap(X86_FEATURE_MTRR); setup_clear_cpu_cap(X86_FEATURE_ACC); setup_clear_cpu_cap(X86_FEATURE_X2APIC); setup_clear_cpu_cap(X86_FEATURE_SME); /* * Xen PV would need some work to support PCID: CR3 handling as well * as xen_flush_tlb_others() would need updating. */ setup_clear_cpu_cap(X86_FEATURE_PCID); if (!xen_initial_domain()) setup_clear_cpu_cap(X86_FEATURE_ACPI); if (xen_check_mwait()) setup_force_cpu_cap(X86_FEATURE_MWAIT); else setup_clear_cpu_cap(X86_FEATURE_MWAIT); if (!xen_check_xsave()) { setup_clear_cpu_cap(X86_FEATURE_XSAVE); setup_clear_cpu_cap(X86_FEATURE_OSXSAVE); } } static void xen_set_debugreg(int reg, unsigned long val) { HYPERVISOR_set_debugreg(reg, val); } static unsigned long xen_get_debugreg(int reg) { return HYPERVISOR_get_debugreg(reg); } static void xen_end_context_switch(struct task_struct *next) { xen_mc_flush(); paravirt_end_context_switch(next); } static unsigned long xen_store_tr(void) { return 0; } /* * Set the page permissions for a particular virtual address. If the * address is a vmalloc mapping (or other non-linear mapping), then * find the linear mapping of the page and also set its protections to * match. */ static void set_aliased_prot(void *v, pgprot_t prot) { int level; pte_t *ptep; pte_t pte; unsigned long pfn; struct page *page; unsigned char dummy; ptep = lookup_address((unsigned long)v, &level); BUG_ON(ptep == NULL); pfn = pte_pfn(*ptep); page = pfn_to_page(pfn); pte = pfn_pte(pfn, prot); /* * Careful: update_va_mapping() will fail if the virtual address * we're poking isn't populated in the page tables. We don't * need to worry about the direct map (that's always in the page * tables), but we need to be careful about vmap space. In * particular, the top level page table can lazily propagate * entries between processes, so if we've switched mms since we * vmapped the target in the first place, we might not have the * top-level page table entry populated. * * We disable preemption because we want the same mm active when * we probe the target and when we issue the hypercall. We'll * have the same nominal mm, but if we're a kernel thread, lazy * mm dropping could change our pgd. * * Out of an abundance of caution, this uses __get_user() to fault * in the target address just in case there's some obscure case * in which the target address isn't readable. */ preempt_disable(); copy_from_kernel_nofault(&dummy, v, 1); if (HYPERVISOR_update_va_mapping((unsigned long)v, pte, 0)) BUG(); if (!PageHighMem(page)) { void *av = __va(PFN_PHYS(pfn)); if (av != v) if (HYPERVISOR_update_va_mapping((unsigned long)av, pte, 0)) BUG(); } else kmap_flush_unused(); preempt_enable(); } static void xen_alloc_ldt(struct desc_struct *ldt, unsigned entries) { const unsigned entries_per_page = PAGE_SIZE / LDT_ENTRY_SIZE; int i; /* * We need to mark the all aliases of the LDT pages RO. We * don't need to call vm_flush_aliases(), though, since that's * only responsible for flushing aliases out the TLBs, not the * page tables, and Xen will flush the TLB for us if needed. * * To avoid confusing future readers: none of this is necessary * to load the LDT. The hypervisor only checks this when the * LDT is faulted in due to subsequent descriptor access. */ for (i = 0; i < entries; i += entries_per_page) set_aliased_prot(ldt + i, PAGE_KERNEL_RO); } static void xen_free_ldt(struct desc_struct *ldt, unsigned entries) { const unsigned entries_per_page = PAGE_SIZE / LDT_ENTRY_SIZE; int i; for (i = 0; i < entries; i += entries_per_page) set_aliased_prot(ldt + i, PAGE_KERNEL); } static void xen_set_ldt(const void *addr, unsigned entries) { struct mmuext_op *op; struct multicall_space mcs = xen_mc_entry(sizeof(*op)); trace_xen_cpu_set_ldt(addr, entries); op = mcs.args; op->cmd = MMUEXT_SET_LDT; op->arg1.linear_addr = (unsigned long)addr; op->arg2.nr_ents = entries; MULTI_mmuext_op(mcs.mc, op, 1, NULL, DOMID_SELF); xen_mc_issue(PARAVIRT_LAZY_CPU); } static void xen_load_gdt(const struct desc_ptr *dtr) { unsigned long va = dtr->address; unsigned int size = dtr->size + 1; unsigned long pfn, mfn; int level; pte_t *ptep; void *virt; /* @size should be at most GDT_SIZE which is smaller than PAGE_SIZE. */ BUG_ON(size > PAGE_SIZE); BUG_ON(va & ~PAGE_MASK); /* * The GDT is per-cpu and is in the percpu data area. * That can be virtually mapped, so we need to do a * page-walk to get the underlying MFN for the * hypercall. The page can also be in the kernel's * linear range, so we need to RO that mapping too. */ ptep = lookup_address(va, &level); BUG_ON(ptep == NULL); pfn = pte_pfn(*ptep); mfn = pfn_to_mfn(pfn); virt = __va(PFN_PHYS(pfn)); make_lowmem_page_readonly((void *)va); make_lowmem_page_readonly(virt); if (HYPERVISOR_set_gdt(&mfn, size / sizeof(struct desc_struct))) BUG(); } /* * load_gdt for early boot, when the gdt is only mapped once */ static void __init xen_load_gdt_boot(const struct desc_ptr *dtr) { unsigned long va = dtr->address; unsigned int size = dtr->size + 1; unsigned long pfn, mfn; pte_t pte; /* @size should be at most GDT_SIZE which is smaller than PAGE_SIZE. */ BUG_ON(size > PAGE_SIZE); BUG_ON(va & ~PAGE_MASK); pfn = virt_to_pfn(va); mfn = pfn_to_mfn(pfn); pte = pfn_pte(pfn, PAGE_KERNEL_RO); if (HYPERVISOR_update_va_mapping((unsigned long)va, pte, 0)) BUG(); if (HYPERVISOR_set_gdt(&mfn, size / sizeof(struct desc_struct))) BUG(); } static inline bool desc_equal(const struct desc_struct *d1, const struct desc_struct *d2) { return !memcmp(d1, d2, sizeof(*d1)); } static void load_TLS_descriptor(struct thread_struct *t, unsigned int cpu, unsigned int i) { struct desc_struct *shadow = &per_cpu(shadow_tls_desc, cpu).desc[i]; struct desc_struct *gdt; xmaddr_t maddr; struct multicall_space mc; if (desc_equal(shadow, &t->tls_array[i])) return; *shadow = t->tls_array[i]; gdt = get_cpu_gdt_rw(cpu); maddr = arbitrary_virt_to_machine(&gdt[GDT_ENTRY_TLS_MIN+i]); mc = __xen_mc_entry(0); MULTI_update_descriptor(mc.mc, maddr.maddr, t->tls_array[i]); } static void xen_load_tls(struct thread_struct *t, unsigned int cpu) { /* * XXX sleazy hack: If we're being called in a lazy-cpu zone * and lazy gs handling is enabled, it means we're in a * context switch, and %gs has just been saved. This means we * can zero it out to prevent faults on exit from the * hypervisor if the next process has no %gs. Either way, it * has been saved, and the new value will get loaded properly. * This will go away as soon as Xen has been modified to not * save/restore %gs for normal hypercalls. * * On x86_64, this hack is not used for %gs, because gs points * to KERNEL_GS_BASE (and uses it for PDA references), so we * must not zero %gs on x86_64 * * For x86_64, we need to zero %fs, otherwise we may get an * exception between the new %fs descriptor being loaded and * %fs being effectively cleared at __switch_to(). */ if (paravirt_get_lazy_mode() == PARAVIRT_LAZY_CPU) { #ifdef CONFIG_X86_32 lazy_load_gs(0); #else loadsegment(fs, 0); #endif } xen_mc_batch(); load_TLS_descriptor(t, cpu, 0); load_TLS_descriptor(t, cpu, 1); load_TLS_descriptor(t, cpu, 2); xen_mc_issue(PARAVIRT_LAZY_CPU); } #ifdef CONFIG_X86_64 static void xen_load_gs_index(unsigned int idx) { if (HYPERVISOR_set_segment_base(SEGBASE_GS_USER_SEL, idx)) BUG(); } #endif static void xen_write_ldt_entry(struct desc_struct *dt, int entrynum, const void *ptr) { xmaddr_t mach_lp = arbitrary_virt_to_machine(&dt[entrynum]); u64 entry = *(u64 *)ptr; trace_xen_cpu_write_ldt_entry(dt, entrynum, entry); preempt_disable(); xen_mc_flush(); if (HYPERVISOR_update_descriptor(mach_lp.maddr, entry)) BUG(); preempt_enable(); } #ifdef CONFIG_X86_64 void noist_exc_debug(struct pt_regs *regs); DEFINE_IDTENTRY_RAW(xenpv_exc_nmi) { /* On Xen PV, NMI doesn't use IST. The C part is the sane as native. */ exc_nmi(regs); } DEFINE_IDTENTRY_RAW(xenpv_exc_debug) { /* * There's no IST on Xen PV, but we still need to dispatch * to the correct handler. */ if (user_mode(regs)) noist_exc_debug(regs); else exc_debug(regs); } struct trap_array_entry { void (*orig)(void); void (*xen)(void); bool ist_okay; }; #define TRAP_ENTRY(func, ist_ok) { \ .orig = asm_##func, \ .xen = xen_asm_##func, \ .ist_okay = ist_ok } #define TRAP_ENTRY_REDIR(func, ist_ok) { \ .orig = asm_##func, \ .xen = xen_asm_xenpv_##func, \ .ist_okay = ist_ok } static struct trap_array_entry trap_array[] = { TRAP_ENTRY_REDIR(exc_debug, true ), TRAP_ENTRY(exc_double_fault, true ), #ifdef CONFIG_X86_MCE TRAP_ENTRY(exc_machine_check, true ), #endif TRAP_ENTRY_REDIR(exc_nmi, true ), TRAP_ENTRY(exc_int3, false ), TRAP_ENTRY(exc_overflow, false ), #ifdef CONFIG_IA32_EMULATION { entry_INT80_compat, xen_entry_INT80_compat, false }, #endif TRAP_ENTRY(exc_page_fault, false ), TRAP_ENTRY(exc_divide_error, false ), TRAP_ENTRY(exc_bounds, false ), TRAP_ENTRY(exc_invalid_op, false ), TRAP_ENTRY(exc_device_not_available, false ), TRAP_ENTRY(exc_coproc_segment_overrun, false ), TRAP_ENTRY(exc_invalid_tss, false ), TRAP_ENTRY(exc_segment_not_present, false ), TRAP_ENTRY(exc_stack_segment, false ), TRAP_ENTRY(exc_general_protection, false ), TRAP_ENTRY(exc_spurious_interrupt_bug, false ), TRAP_ENTRY(exc_coprocessor_error, false ), TRAP_ENTRY(exc_alignment_check, false ), TRAP_ENTRY(exc_simd_coprocessor_error, false ), }; static bool __ref get_trap_addr(void **addr, unsigned int ist) { unsigned int nr; bool ist_okay = false; /* * Replace trap handler addresses by Xen specific ones. * Check for known traps using IST and whitelist them. * The debugger ones are the only ones we care about. * Xen will handle faults like double_fault, so we should never see * them. Warn if there's an unexpected IST-using fault handler. */ for (nr = 0; nr < ARRAY_SIZE(trap_array); nr++) { struct trap_array_entry *entry = trap_array + nr; if (*addr == entry->orig) { *addr = entry->xen; ist_okay = entry->ist_okay; break; } } if (nr == ARRAY_SIZE(trap_array) && *addr >= (void *)early_idt_handler_array[0] && *addr < (void *)early_idt_handler_array[NUM_EXCEPTION_VECTORS]) { nr = (*addr - (void *)early_idt_handler_array[0]) / EARLY_IDT_HANDLER_SIZE; *addr = (void *)xen_early_idt_handler_array[nr]; } if (WARN_ON(ist != 0 && !ist_okay)) return false; return true; } #endif static int cvt_gate_to_trap(int vector, const gate_desc *val, struct trap_info *info) { unsigned long addr; if (val->bits.type != GATE_TRAP && val->bits.type != GATE_INTERRUPT) return 0; info->vector = vector; addr = gate_offset(val); #ifdef CONFIG_X86_64 if (!get_trap_addr((void **)&addr, val->bits.ist)) return 0; #endif /* CONFIG_X86_64 */ info->address = addr; info->cs = gate_segment(val); info->flags = val->bits.dpl; /* interrupt gates clear IF */ if (val->bits.type == GATE_INTERRUPT) info->flags |= 1 << 2; return 1; } /* Locations of each CPU's IDT */ static DEFINE_PER_CPU(struct desc_ptr, idt_desc); /* Set an IDT entry. If the entry is part of the current IDT, then also update Xen. */ static void xen_write_idt_entry(gate_desc *dt, int entrynum, const gate_desc *g) { unsigned long p = (unsigned long)&dt[entrynum]; unsigned long start, end; trace_xen_cpu_write_idt_entry(dt, entrynum, g); preempt_disable(); start = __this_cpu_read(idt_desc.address); end = start + __this_cpu_read(idt_desc.size) + 1; xen_mc_flush(); native_write_idt_entry(dt, entrynum, g); if (p >= start && (p + 8) <= end) { struct trap_info info[2]; info[1].address = 0; if (cvt_gate_to_trap(entrynum, g, &info[0])) if (HYPERVISOR_set_trap_table(info)) BUG(); } preempt_enable(); } static void xen_convert_trap_info(const struct desc_ptr *desc, struct trap_info *traps) { unsigned in, out, count; count = (desc->size+1) / sizeof(gate_desc); BUG_ON(count > 256); for (in = out = 0; in < count; in++) { gate_desc *entry = (gate_desc *)(desc->address) + in; if (cvt_gate_to_trap(in, entry, &traps[out])) out++; } traps[out].address = 0; } void xen_copy_trap_info(struct trap_info *traps) { const struct desc_ptr *desc = this_cpu_ptr(&idt_desc); xen_convert_trap_info(desc, traps); } /* Load a new IDT into Xen. In principle this can be per-CPU, so we hold a spinlock to protect the static traps[] array (static because it avoids allocation, and saves stack space). */ static void xen_load_idt(const struct desc_ptr *desc) { static DEFINE_SPINLOCK(lock); static struct trap_info traps[257]; trace_xen_cpu_load_idt(desc); spin_lock(&lock); memcpy(this_cpu_ptr(&idt_desc), desc, sizeof(idt_desc)); xen_convert_trap_info(desc, traps); xen_mc_flush(); if (HYPERVISOR_set_trap_table(traps)) BUG(); spin_unlock(&lock); } /* Write a GDT descriptor entry. Ignore LDT descriptors, since they're handled differently. */ static void xen_write_gdt_entry(struct desc_struct *dt, int entry, const void *desc, int type) { trace_xen_cpu_write_gdt_entry(dt, entry, desc, type); preempt_disable(); switch (type) { case DESC_LDT: case DESC_TSS: /* ignore */ break; default: { xmaddr_t maddr = arbitrary_virt_to_machine(&dt[entry]); xen_mc_flush(); if (HYPERVISOR_update_descriptor(maddr.maddr, *(u64 *)desc)) BUG(); } } preempt_enable(); } /* * Version of write_gdt_entry for use at early boot-time needed to * update an entry as simply as possible. */ static void __init xen_write_gdt_entry_boot(struct desc_struct *dt, int entry, const void *desc, int type) { trace_xen_cpu_write_gdt_entry(dt, entry, desc, type); switch (type) { case DESC_LDT: case DESC_TSS: /* ignore */ break; default: { xmaddr_t maddr = virt_to_machine(&dt[entry]); if (HYPERVISOR_update_descriptor(maddr.maddr, *(u64 *)desc)) dt[entry] = *(struct desc_struct *)desc; } } } static void xen_load_sp0(unsigned long sp0) { struct multicall_space mcs; mcs = xen_mc_entry(0); MULTI_stack_switch(mcs.mc, __KERNEL_DS, sp0); xen_mc_issue(PARAVIRT_LAZY_CPU); this_cpu_write(cpu_tss_rw.x86_tss.sp0, sp0); } #ifdef CONFIG_X86_IOPL_IOPERM static void xen_update_io_bitmap(void) { struct physdev_set_iobitmap iobitmap; struct tss_struct *tss = this_cpu_ptr(&cpu_tss_rw); native_tss_update_io_bitmap(); iobitmap.bitmap = (uint8_t *)(&tss->x86_tss) + tss->x86_tss.io_bitmap_base; if (tss->x86_tss.io_bitmap_base == IO_BITMAP_OFFSET_INVALID) iobitmap.nr_ports = 0; else iobitmap.nr_ports = IO_BITMAP_BITS; HYPERVISOR_physdev_op(PHYSDEVOP_set_iobitmap, &iobitmap); } #endif static void xen_io_delay(void) { } static DEFINE_PER_CPU(unsigned long, xen_cr0_value); static unsigned long xen_read_cr0(void) { unsigned long cr0 = this_cpu_read(xen_cr0_value); if (unlikely(cr0 == 0)) { cr0 = native_read_cr0(); this_cpu_write(xen_cr0_value, cr0); } return cr0; } static void xen_write_cr0(unsigned long cr0) { struct multicall_space mcs; this_cpu_write(xen_cr0_value, cr0); /* Only pay attention to cr0.TS; everything else is ignored. */ mcs = xen_mc_entry(0); MULTI_fpu_taskswitch(mcs.mc, (cr0 & X86_CR0_TS) != 0); xen_mc_issue(PARAVIRT_LAZY_CPU); } static void xen_write_cr4(unsigned long cr4) { cr4 &= ~(X86_CR4_PGE | X86_CR4_PSE | X86_CR4_PCE); native_write_cr4(cr4); } static u64 xen_read_msr_safe(unsigned int msr, int *err) { u64 val; if (pmu_msr_read(msr, &val, err)) return val; val = native_read_msr_safe(msr, err); switch (msr) { case MSR_IA32_APICBASE: val &= ~X2APIC_ENABLE; break; } return val; } static int xen_write_msr_safe(unsigned int msr, unsigned low, unsigned high) { int ret; #ifdef CONFIG_X86_64 unsigned int which; u64 base; #endif ret = 0; switch (msr) { #ifdef CONFIG_X86_64 case MSR_FS_BASE: which = SEGBASE_FS; goto set; case MSR_KERNEL_GS_BASE: which = SEGBASE_GS_USER; goto set; case MSR_GS_BASE: which = SEGBASE_GS_KERNEL; goto set; set: base = ((u64)high << 32) | low; if (HYPERVISOR_set_segment_base(which, base) != 0) ret = -EIO; break; #endif case MSR_STAR: case MSR_CSTAR: case MSR_LSTAR: case MSR_SYSCALL_MASK: case MSR_IA32_SYSENTER_CS: case MSR_IA32_SYSENTER_ESP: case MSR_IA32_SYSENTER_EIP: /* Fast syscall setup is all done in hypercalls, so these are all ignored. Stub them out here to stop Xen console noise. */ break; default: if (!pmu_msr_write(msr, low, high, &ret)) ret = native_write_msr_safe(msr, low, high); } return ret; } static u64 xen_read_msr(unsigned int msr) { /* * This will silently swallow a #GP from RDMSR. It may be worth * changing that. */ int err; return xen_read_msr_safe(msr, &err); } static void xen_write_msr(unsigned int msr, unsigned low, unsigned high) { /* * This will silently swallow a #GP from WRMSR. It may be worth * changing that. */ xen_write_msr_safe(msr, low, high); } /* This is called once we have the cpu_possible_mask */ void __init xen_setup_vcpu_info_placement(void) { int cpu; for_each_possible_cpu(cpu) { /* Set up direct vCPU id mapping for PV guests. */ per_cpu(xen_vcpu_id, cpu) = cpu; /* * xen_vcpu_setup(cpu) can fail -- in which case it * falls back to the shared_info version for cpus * where xen_vcpu_nr(cpu) < MAX_VIRT_CPUS. * * xen_cpu_up_prepare_pv() handles the rest by failing * them in hotplug. */ (void) xen_vcpu_setup(cpu); } /* * xen_vcpu_setup managed to place the vcpu_info within the * percpu area for all cpus, so make use of it. */ if (xen_have_vcpu_info_placement) { pv_ops.irq.save_fl = __PV_IS_CALLEE_SAVE(xen_save_fl_direct); pv_ops.irq.restore_fl = __PV_IS_CALLEE_SAVE(xen_restore_fl_direct); pv_ops.irq.irq_disable = __PV_IS_CALLEE_SAVE(xen_irq_disable_direct); pv_ops.irq.irq_enable = __PV_IS_CALLEE_SAVE(xen_irq_enable_direct); pv_ops.mmu.read_cr2 = __PV_IS_CALLEE_SAVE(xen_read_cr2_direct); } } static const struct pv_info xen_info __initconst = { .shared_kernel_pmd = 0, #ifdef CONFIG_X86_64 .extra_user_64bit_cs = FLAT_USER_CS64, #endif .name = "Xen", }; static const struct pv_cpu_ops xen_cpu_ops __initconst = { .cpuid = xen_cpuid, .set_debugreg = xen_set_debugreg, .get_debugreg = xen_get_debugreg, .read_cr0 = xen_read_cr0, .write_cr0 = xen_write_cr0, .write_cr4 = xen_write_cr4, .wbinvd = native_wbinvd, .read_msr = xen_read_msr, .write_msr = xen_write_msr, .read_msr_safe = xen_read_msr_safe, .write_msr_safe = xen_write_msr_safe, .read_pmc = xen_read_pmc, .iret = xen_iret, #ifdef CONFIG_X86_64 .usergs_sysret64 = xen_sysret64, #endif .load_tr_desc = paravirt_nop, .set_ldt = xen_set_ldt, .load_gdt = xen_load_gdt, .load_idt = xen_load_idt, .load_tls = xen_load_tls, #ifdef CONFIG_X86_64 .load_gs_index = xen_load_gs_index, #endif .alloc_ldt = xen_alloc_ldt, .free_ldt = xen_free_ldt, .store_tr = xen_store_tr, .write_ldt_entry = xen_write_ldt_entry, .write_gdt_entry = xen_write_gdt_entry, .write_idt_entry = xen_write_idt_entry, .load_sp0 = xen_load_sp0, #ifdef CONFIG_X86_IOPL_IOPERM .update_io_bitmap = xen_update_io_bitmap, #endif .io_delay = xen_io_delay, /* Xen takes care of %gs when switching to usermode for us */ .swapgs = paravirt_nop, .start_context_switch = paravirt_start_context_switch, .end_context_switch = xen_end_context_switch, }; static void xen_restart(char *msg) { xen_reboot(SHUTDOWN_reboot); } static void xen_machine_halt(void) { xen_reboot(SHUTDOWN_poweroff); } static void xen_machine_power_off(void) { if (pm_power_off) pm_power_off(); xen_reboot(SHUTDOWN_poweroff); } static void xen_crash_shutdown(struct pt_regs *regs) { xen_reboot(SHUTDOWN_crash); } static const struct machine_ops xen_machine_ops __initconst = { .restart = xen_restart, .halt = xen_machine_halt, .power_off = xen_machine_power_off, .shutdown = xen_machine_halt, .crash_shutdown = xen_crash_shutdown, .emergency_restart = xen_emergency_restart, }; static unsigned char xen_get_nmi_reason(void) { unsigned char reason = 0; /* Construct a value which looks like it came from port 0x61. */ if (test_bit(_XEN_NMIREASON_io_error, &HYPERVISOR_shared_info->arch.nmi_reason)) reason |= NMI_REASON_IOCHK; if (test_bit(_XEN_NMIREASON_pci_serr, &HYPERVISOR_shared_info->arch.nmi_reason)) reason |= NMI_REASON_SERR; return reason; } static void __init xen_boot_params_init_edd(void) { #if IS_ENABLED(CONFIG_EDD) struct xen_platform_op op; struct edd_info *edd_info; u32 *mbr_signature; unsigned nr; int ret; edd_info = boot_params.eddbuf; mbr_signature = boot_params.edd_mbr_sig_buffer; op.cmd = XENPF_firmware_info; op.u.firmware_info.type = XEN_FW_DISK_INFO; for (nr = 0; nr < EDDMAXNR; nr++) { struct edd_info *info = edd_info + nr; op.u.firmware_info.index = nr; info->params.length = sizeof(info->params); set_xen_guest_handle(op.u.firmware_info.u.disk_info.edd_params, &info->params); ret = HYPERVISOR_platform_op(&op); if (ret) break; #define C(x) info->x = op.u.firmware_info.u.disk_info.x C(device); C(version); C(interface_support); C(legacy_max_cylinder); C(legacy_max_head); C(legacy_sectors_per_track); #undef C } boot_params.eddbuf_entries = nr; op.u.firmware_info.type = XEN_FW_DISK_MBR_SIGNATURE; for (nr = 0; nr < EDD_MBR_SIG_MAX; nr++) { op.u.firmware_info.index = nr; ret = HYPERVISOR_platform_op(&op); if (ret) break; mbr_signature[nr] = op.u.firmware_info.u.disk_mbr_signature.mbr_signature; } boot_params.edd_mbr_sig_buf_entries = nr; #endif } /* * Set up the GDT and segment registers for -fstack-protector. Until * we do this, we have to be careful not to call any stack-protected * function, which is most of the kernel. */ static void __init xen_setup_gdt(int cpu) { pv_ops.cpu.write_gdt_entry = xen_write_gdt_entry_boot; pv_ops.cpu.load_gdt = xen_load_gdt_boot; setup_stack_canary_segment(cpu); switch_to_new_gdt(cpu); pv_ops.cpu.write_gdt_entry = xen_write_gdt_entry; pv_ops.cpu.load_gdt = xen_load_gdt; } static void __init xen_dom0_set_legacy_features(void) { x86_platform.legacy.rtc = 1; } /* First C function to be called on Xen boot */ asmlinkage __visible void __init xen_start_kernel(void) { struct physdev_set_iopl set_iopl; unsigned long initrd_start = 0; int rc; if (!xen_start_info) return; xen_domain_type = XEN_PV_DOMAIN; xen_start_flags = xen_start_info->flags; xen_setup_features(); /* Install Xen paravirt ops */ pv_info = xen_info; pv_ops.init.patch = paravirt_patch_default; pv_ops.cpu = xen_cpu_ops; xen_init_irq_ops(); /* * Setup xen_vcpu early because it is needed for * local_irq_disable(), irqs_disabled(), e.g. in printk(). * * Don't do the full vcpu_info placement stuff until we have * the cpu_possible_mask and a non-dummy shared_info. */ xen_vcpu_info_reset(0); x86_platform.get_nmi_reason = xen_get_nmi_reason; x86_init.resources.memory_setup = xen_memory_setup; x86_init.irqs.intr_mode_select = x86_init_noop; x86_init.irqs.intr_mode_init = x86_init_noop; x86_init.oem.arch_setup = xen_arch_setup; x86_init.oem.banner = xen_banner; x86_init.hyper.init_platform = xen_pv_init_platform; x86_init.hyper.guest_late_init = xen_pv_guest_late_init; /* * Set up some pagetable state before starting to set any ptes. */ xen_setup_machphys_mapping(); xen_init_mmu_ops(); /* Prevent unwanted bits from being set in PTEs. */ __supported_pte_mask &= ~_PAGE_GLOBAL; __default_kernel_pte_mask &= ~_PAGE_GLOBAL; /* * Prevent page tables from being allocated in highmem, even * if CONFIG_HIGHPTE is enabled. */ __userpte_alloc_gfp &= ~__GFP_HIGHMEM; /* Get mfn list */ xen_build_dynamic_phys_to_machine(); /* * Set up kernel GDT and segment registers, mainly so that * -fstack-protector code can be executed. */ xen_setup_gdt(0); /* Work out if we support NX */ get_cpu_cap(&boot_cpu_data); x86_configure_nx(); /* Determine virtual and physical address sizes */ get_cpu_address_sizes(&boot_cpu_data); /* Let's presume PV guests always boot on vCPU with id 0. */ per_cpu(xen_vcpu_id, 0) = 0; idt_setup_early_handler(); xen_init_capabilities(); #ifdef CONFIG_X86_LOCAL_APIC /* * set up the basic apic ops. */ xen_init_apic(); #endif if (xen_feature(XENFEAT_mmu_pt_update_preserve_ad)) { pv_ops.mmu.ptep_modify_prot_start = xen_ptep_modify_prot_start; pv_ops.mmu.ptep_modify_prot_commit = xen_ptep_modify_prot_commit; } machine_ops = xen_machine_ops; /* * The only reliable way to retain the initial address of the * percpu gdt_page is to remember it here, so we can go and * mark it RW later, when the initial percpu area is freed. */ xen_initial_gdt = &per_cpu(gdt_page, 0); xen_smp_init(); #ifdef CONFIG_ACPI_NUMA /* * The pages we from Xen are not related to machine pages, so * any NUMA information the kernel tries to get from ACPI will * be meaningless. Prevent it from trying. */ acpi_numa = -1; #endif WARN_ON(xen_cpuhp_setup(xen_cpu_up_prepare_pv, xen_cpu_dead_pv)); local_irq_disable(); early_boot_irqs_disabled = true; xen_raw_console_write("mapping kernel into physical memory\n"); xen_setup_kernel_pagetable((pgd_t *)xen_start_info->pt_base, xen_start_info->nr_pages); xen_reserve_special_pages(); /* keep using Xen gdt for now; no urgent need to change it */ #ifdef CONFIG_X86_32 pv_info.kernel_rpl = 1; if (xen_feature(XENFEAT_supervisor_mode_kernel)) pv_info.kernel_rpl = 0; #else pv_info.kernel_rpl = 0; #endif /* set the limit of our address space */ xen_reserve_top(); /* * We used to do this in xen_arch_setup, but that is too late * on AMD were early_cpu_init (run before ->arch_setup()) calls * early_amd_init which pokes 0xcf8 port. */ set_iopl.iopl = 1; rc = HYPERVISOR_physdev_op(PHYSDEVOP_set_iopl, &set_iopl); if (rc != 0) xen_raw_printk("physdev_op failed %d\n", rc); #ifdef CONFIG_X86_32 /* set up basic CPUID stuff */ cpu_detect(&new_cpu_data); set_cpu_cap(&new_cpu_data, X86_FEATURE_FPU); new_cpu_data.x86_capability[CPUID_1_EDX] = cpuid_edx(1); #endif if (xen_start_info->mod_start) { if (xen_start_info->flags & SIF_MOD_START_PFN) initrd_start = PFN_PHYS(xen_start_info->mod_start); else initrd_start = __pa(xen_start_info->mod_start); } /* Poke various useful things into boot_params */ boot_params.hdr.type_of_loader = (9 << 4) | 0; boot_params.hdr.ramdisk_image = initrd_start; boot_params.hdr.ramdisk_size = xen_start_info->mod_len; boot_params.hdr.cmd_line_ptr = __pa(xen_start_info->cmd_line); boot_params.hdr.hardware_subarch = X86_SUBARCH_XEN; if (!xen_initial_domain()) { add_preferred_console("xenboot", 0, NULL); if (pci_xen) x86_init.pci.arch_init = pci_xen_init; } else { const struct dom0_vga_console_info *info = (void *)((char *)xen_start_info + xen_start_info->console.dom0.info_off); struct xen_platform_op op = { .cmd = XENPF_firmware_info, .interface_version = XENPF_INTERFACE_VERSION, .u.firmware_info.type = XEN_FW_KBD_SHIFT_FLAGS, }; x86_platform.set_legacy_features = xen_dom0_set_legacy_features; xen_init_vga(info, xen_start_info->console.dom0.info_size); xen_start_info->console.domU.mfn = 0; xen_start_info->console.domU.evtchn = 0; if (HYPERVISOR_platform_op(&op) == 0) boot_params.kbd_status = op.u.firmware_info.u.kbd_shift_flags; /* Make sure ACS will be enabled */ pci_request_acs(); xen_acpi_sleep_register(); /* Avoid searching for BIOS MP tables */ x86_init.mpparse.find_smp_config = x86_init_noop; x86_init.mpparse.get_smp_config = x86_init_uint_noop; xen_boot_params_init_edd(); } if (!boot_params.screen_info.orig_video_isVGA) add_preferred_console("tty", 0, NULL); add_preferred_console("hvc", 0, NULL); if (boot_params.screen_info.orig_video_isVGA) add_preferred_console("tty", 0, NULL); #ifdef CONFIG_PCI /* PCI BIOS service won't work from a PV guest. */ pci_probe &= ~PCI_PROBE_BIOS; #endif xen_raw_console_write("about to get started...\n"); /* We need this for printk timestamps */ xen_setup_runstate_info(0); xen_efi_init(&boot_params); /* Start the world */ #ifdef CONFIG_X86_32 i386_start_kernel(); #else cr4_init_shadow(); /* 32b kernel does this in i386_start_kernel() */ x86_64_start_reservations((char *)__pa_symbol(&boot_params)); #endif } static int xen_cpu_up_prepare_pv(unsigned int cpu) { int rc; if (per_cpu(xen_vcpu, cpu) == NULL) return -ENODEV; xen_setup_timer(cpu); rc = xen_smp_intr_init(cpu); if (rc) { WARN(1, "xen_smp_intr_init() for CPU %d failed: %d\n", cpu, rc); return rc; } rc = xen_smp_intr_init_pv(cpu); if (rc) { WARN(1, "xen_smp_intr_init_pv() for CPU %d failed: %d\n", cpu, rc); return rc; } return 0; } static int xen_cpu_dead_pv(unsigned int cpu) { xen_smp_intr_free(cpu); xen_smp_intr_free_pv(cpu); xen_teardown_timer(cpu); return 0; } static uint32_t __init xen_platform_pv(void) { if (xen_pv_domain()) return xen_cpuid_base(); return 0; } const __initconst struct hypervisor_x86 x86_hyper_xen_pv = { .name = "Xen PV", .detect = xen_platform_pv, .type = X86_HYPER_XEN_PV, .runtime.pin_vcpu = xen_pin_vcpu, .ignore_nopv = true, };
./CrossVul/dataset_final_sorted/CWE-276/c/bad_4225_5
crossvul-cpp_data_bad_5205_2
/** @file bzrtpParserTests.c @brief Test parsing and building ZRTP packet. @author Johan Pascal @copyright Copyright (C) 2014 Belledonne Communications, Grenoble, France 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "CUnit/Basic.h" #ifndef _WIN32 #include <time.h> #else #include <windows.h> #endif #include "bzrtp/bzrtp.h" #include "typedef.h" #include "packetParser.h" #include "cryptoUtils.h" #include "zidCache.h" #include "testUtils.h" /** * Test pattern : the packet data in the patternZRTPPackets, length, sequence number and SSRC in patternZRTPMetaData * Pattern generated from wireshark trace * */ #define TEST_PACKET_NUMBER 9 /* meta data: length, sequence number, SSRC */ static uint32_t patternZRTPMetaData[TEST_PACKET_NUMBER][3] = { {136, 0x09f1, 0x12345678}, /* hello */ {136, 0x02ce, 0x87654321}, /* hello */ {28, 0x09f2, 0x12345678}, /* hello ack */ {132, 0x02d0, 0x87654321}, /* commit */ {484, 0x09f5, 0x12345678}, /* dhpart1 */ {484, 0x02d1, 0x87654321}, /* dhpart2 */ {92, 0x09f6, 0x12345678}, /* confirm 1 */ {92, 0x02d2, 0x87654321}, /* confirm 2 */ {28, 0x09f7, 0x12345678} /* conf2ACK*/ }; static const uint8_t patternZRTPPackets[TEST_PACKET_NUMBER][512] = { /* This is a Hello packet, sequence number is 0x09f1, SSRC 0x12345678 */ {0x10, 0x00, 0x09, 0xf1, 0x5a, 0x52, 0x54, 0x50, 0x12, 0x34, 0x56, 0x78, 0x50, 0x5a, 0x00, 0x1e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x20, 0x20, 0x31, 0x2e, 0x31, 0x30, 0x4c, 0x49, 0x4e, 0x50, 0x48, 0x4f, 0x4e, 0x45, 0x2d, 0x5a, 0x52, 0x54, 0x50, 0x43, 0x50, 0x50, 0xe8, 0xd5, 0x26, 0xc1, 0x3a, 0x0c, 0x4c, 0x6a, 0xce, 0x18, 0xaa, 0xc7, 0xc4, 0xa4, 0x07, 0x0e, 0x65, 0x7a, 0x4d, 0xca, 0x78, 0xf2, 0xcc, 0xcd, 0x20, 0x50, 0x38, 0x73, 0xe9, 0x7e, 0x08, 0x29, 0x7e, 0xb0, 0x04, 0x97, 0xc0, 0xfe, 0xb2, 0xc9, 0x24, 0x31, 0x49, 0x7f, 0x00, 0x01, 0x12, 0x31, 0x53, 0x32, 0x35, 0x36, 0x41, 0x45, 0x53, 0x31, 0x48, 0x53, 0x33, 0x32, 0x48, 0x53, 0x38, 0x30, 0x44, 0x48, 0x33, 0x6b, 0x44, 0x48, 0x32, 0x6b, 0x4d, 0x75, 0x6c, 0x74, 0x42, 0x33, 0x32, 0x20, 0xa0, 0xfd, 0x0f, 0xad, 0xeb, 0xe0, 0x86, 0x56, 0xe3, 0x65, 0x81, 0x02}, /* This is a Hello packet, sequence number is 0x02ce, SSRC 0x87654321 */ {0x10, 0x00, 0x02, 0xce, 0x5a, 0x52, 0x54, 0x50, 0x87, 0x65, 0x43, 0x21, 0x50, 0x5a, 0x00, 0x1e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x20, 0x20, 0x31, 0x2e, 0x31, 0x30, 0x4c, 0x49, 0x4e, 0x50, 0x48, 0x4f, 0x4e, 0x45, 0x2d, 0x5a, 0x52, 0x54, 0x50, 0x43, 0x50, 0x50, 0x8d, 0x0f, 0x5a, 0x20, 0x79, 0x97, 0x42, 0x01, 0x99, 0x45, 0x45, 0xf7, 0x0e, 0x31, 0x06, 0xe1, 0x05, 0xc0, 0xb9, 0x24, 0xe9, 0xc9, 0x78, 0xc7, 0x38, 0xf5, 0x97, 0x48, 0xef, 0x42, 0x6a, 0x3e, 0x92, 0x42, 0xc2, 0xcf, 0x44, 0xee, 0x9c, 0x65, 0xca, 0x58, 0x78, 0xf1, 0x00, 0x01, 0x12, 0x31, 0x53, 0x32, 0x35, 0x36, 0x41, 0x45, 0x53, 0x31, 0x48, 0x53, 0x33, 0x32, 0x48, 0x53, 0x38, 0x30, 0x44, 0x48, 0x33, 0x6b, 0x44, 0x48, 0x32, 0x6b, 0x4d, 0x75, 0x6c, 0x74, 0x42, 0x33, 0x32, 0x20, 0xb3, 0x90, 0x91, 0x95, 0xe4, 0x67, 0xa3, 0x21, 0xe3, 0x5f, 0x9c, 0x92}, /* This is a Hello ack packet, sequence number is 0x09f2, SSRC 0x12345678*/ {0x10, 0x00, 0x09, 0xf2, 0x5a, 0x52, 0x54, 0x50, 0x12, 0x34, 0x56, 0x78, 0x50, 0x5a, 0x00, 0x03, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x41, 0x43, 0x4b, 0x77, 0x0e, 0x44, 0x07}, /* This is a Commit packet, sequence number is 0x02d0, SSRC 0x87654321 */ {0x10, 0x00, 0x02, 0xd0, 0x5a, 0x52, 0x54, 0x50, 0x87, 0x65, 0x43, 0x21, 0x50, 0x5a, 0x00, 0x1d, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x20, 0x20, 0xd9, 0xff, 0x14, 0x8b, 0x34, 0xaa, 0x69, 0xe9, 0x33, 0xc1, 0x62, 0xe6, 0x6b, 0xe8, 0xcd, 0x9d, 0xe3, 0x0f, 0xb7, 0x6a, 0xe8, 0x6a, 0x62, 0x2b, 0xcb, 0xe4, 0x6b, 0x91, 0x05, 0xc7, 0xc8, 0x7e, 0x92, 0x42, 0xc2, 0xcf, 0x44, 0xee, 0x9c, 0x65, 0xca, 0x58, 0x78, 0xf1, 0x53, 0x32, 0x35, 0x36, 0x41, 0x45, 0x53, 0x31, 0x48, 0x53, 0x33, 0x32, 0x44, 0x48, 0x33, 0x6b, 0x42, 0x33, 0x32, 0x20, 0x1e, 0xc0, 0xfe, 0x2e, 0x72, 0x06, 0x4d, 0xfb, 0xfc, 0x92, 0x02, 0x8c, 0x03, 0x0f, 0xb8, 0xf8, 0x91, 0xb4, 0xe7, 0x96, 0xac, 0x25, 0xfd, 0xf9, 0x68, 0xc6, 0xe9, 0x67, 0xa9, 0x42, 0xb1, 0x5b, 0xbb, 0x6d, 0x9c, 0xd2, 0x4b, 0x13, 0xa9, 0xae, 0x25, 0x5c, 0xa9, 0xc1}, /* This is a DHPart1 packet, sequence number is 0x09f5, SSRC 0x12345678 */ {0x10, 0x00, 0x09, 0xf5, 0x5a, 0x52, 0x54, 0x50, 0x12, 0x34, 0x56, 0x78, 0x50, 0x5a, 0x00, 0x75, 0x44, 0x48, 0x50, 0x61, 0x72, 0x74, 0x31, 0x20, 0x28, 0x7c, 0x28, 0xe4, 0xd7, 0x3d, 0x14, 0x39, 0xb5, 0x6d, 0x1c, 0x47, 0x9d, 0x59, 0x0a, 0xf2, 0x10, 0x33, 0xde, 0x6b, 0xd5, 0x2b, 0xfb, 0x26, 0xa5, 0x87, 0x4d, 0xe9, 0x20, 0x6b, 0x9f, 0xdd, 0xab, 0xbc, 0xc6, 0x8d, 0xbd, 0x5d, 0xe6, 0x67, 0x00, 0x69, 0x44, 0xb1, 0x84, 0x2c, 0x27, 0x10, 0x8c, 0x4e, 0x58, 0x8a, 0xed, 0x7e, 0x8b, 0x44, 0x2c, 0x3a, 0x13, 0x02, 0xdf, 0x58, 0xb6, 0xda, 0x80, 0x55, 0xec, 0xb0, 0x20, 0xc7, 0x76, 0x50, 0xc4, 0x1b, 0xa8, 0x26, 0x11, 0x5c, 0xf5, 0x71, 0x7e, 0xb4, 0x86, 0x22, 0x17, 0xde, 0x14, 0x08, 0x46, 0x5c, 0xac, 0x88, 0x8c, 0x41, 0x6b, 0x95, 0x22, 0xba, 0xf8, 0x3e, 0x67, 0x20, 0x94, 0xa0, 0x84, 0xa3, 0x93, 0x41, 0x9a, 0x1a, 0x7c, 0x2f, 0x04, 0xf4, 0x14, 0x3f, 0x11, 0x54, 0x02, 0xba, 0xee, 0xc2, 0x20, 0xfa, 0x38, 0xf7, 0xba, 0xa4, 0xbf, 0x4a, 0x70, 0x02, 0x68, 0xdc, 0xb2, 0xe9, 0x1a, 0x8a, 0x87, 0xa5, 0xe4, 0x9c, 0x42, 0x07, 0x82, 0x26, 0xb4, 0xda, 0xe3, 0x1b, 0xdc, 0x78, 0xc7, 0xd8, 0xa8, 0x00, 0x5c, 0x00, 0x14, 0xe4, 0x00, 0xfe, 0x6c, 0x2d, 0xce, 0x62, 0xc9, 0x71, 0x5d, 0xed, 0x4e, 0x66, 0x9f, 0xf5, 0x30, 0xc0, 0x04, 0x53, 0xf6, 0x15, 0x2f, 0xe1, 0x85, 0x3b, 0xd9, 0x40, 0x9b, 0x50, 0x07, 0x43, 0x7c, 0x36, 0x01, 0xa1, 0xda, 0x66, 0xc4, 0x20, 0x2f, 0x45, 0xc0, 0xcc, 0xb2, 0x64, 0x63, 0x9c, 0x07, 0x9d, 0x23, 0x27, 0x80, 0xa1, 0x7f, 0xc2, 0xe0, 0xa0, 0xfd, 0xc3, 0x98, 0x83, 0xa3, 0xaa, 0x6b, 0xdc, 0x9f, 0x6a, 0xc3, 0x32, 0x94, 0xf0, 0x80, 0xa0, 0xd9, 0xf1, 0x83, 0x41, 0x48, 0xa9, 0xb5, 0xed, 0x62, 0x50, 0x88, 0xec, 0x33, 0x32, 0xd2, 0x5f, 0xdc, 0xcc, 0xae, 0xc9, 0x74, 0xca, 0x0a, 0xab, 0x82, 0x06, 0x01, 0x46, 0x35, 0x30, 0xcd, 0x68, 0xec, 0x09, 0xab, 0x8c, 0xb0, 0x39, 0xe5, 0xd8, 0x5c, 0xa2, 0xe4, 0x82, 0xfe, 0x46, 0x01, 0xbd, 0xe7, 0x7f, 0x60, 0x1b, 0x50, 0x62, 0xfb, 0x6f, 0xee, 0x6c, 0xf1, 0xf7, 0x9b, 0xb7, 0x1c, 0x76, 0x48, 0xb5, 0xbe, 0xa5, 0x83, 0x73, 0x07, 0xa2, 0xe2, 0x73, 0xc7, 0x68, 0x34, 0xc8, 0xef, 0x12, 0xc4, 0x32, 0xdf, 0x37, 0x3d, 0xdc, 0x07, 0x0e, 0xa6, 0x92, 0x82, 0xbd, 0xba, 0x20, 0xc4, 0xb4, 0x8d, 0x1f, 0x19, 0x1c, 0x15, 0x0f, 0x5f, 0x01, 0xdf, 0x67, 0x1f, 0x59, 0xd1, 0x5e, 0x99, 0x60, 0xf6, 0xb8, 0x67, 0xe2, 0x46, 0x62, 0x11, 0x30, 0xfb, 0x81, 0x9d, 0x0b, 0xec, 0x36, 0xe9, 0x8d, 0x43, 0xfe, 0x55, 0xd9, 0x61, 0x98, 0x3f, 0x2e, 0x39, 0x6a, 0x26, 0x43, 0xb0, 0x6d, 0x08, 0xec, 0x2e, 0x42, 0x7e, 0x23, 0x82, 0x6f, 0xd9, 0xbb, 0xfd, 0x0a, 0xcd, 0x48, 0xe7, 0xd5, 0x8b, 0xa5, 0x80, 0x34, 0xca, 0x96, 0x4f, 0x58, 0x25, 0xba, 0x43, 0x5e, 0x3d, 0x1c, 0xee, 0x72, 0xb8, 0x35, 0x8c, 0x5d, 0xd9, 0x69, 0x24, 0x58, 0x36, 0x21, 0xb0, 0x45, 0xa4, 0xad, 0x40, 0xda, 0x94, 0x98, 0x0f, 0xb1, 0xed, 0x6c, 0xad, 0x26, 0x03, 0x04, 0x82, 0xff, 0x15, 0x00, 0x41, 0x87, 0x06, 0x93, 0xd4, 0x86, 0xa9, 0x7e, 0xb8, 0xd9, 0x70, 0x34, 0x6d, 0x8e, 0x6a, 0x16, 0xe2, 0x46, 0x52, 0xb0, 0x78, 0x54, 0x53, 0xaf}, /* This is a DHPart2 packet, sequence number is 0x02d1, SSRC 0x87654321 */ {0x10, 0x00, 0x02, 0xd1, 0x5a, 0x52, 0x54, 0x50, 0x87, 0x65, 0x43, 0x21, 0x50, 0x5a, 0x00, 0x75, 0x44, 0x48, 0x50, 0x61, 0x72, 0x74, 0x32, 0x20, 0x9e, 0xb2, 0xa5, 0x8b, 0xe8, 0x96, 0x37, 0xf5, 0x5a, 0x41, 0x34, 0xb2, 0xec, 0xda, 0x84, 0x95, 0xf0, 0xf8, 0x9b, 0xab, 0x61, 0x4f, 0x7c, 0x9e, 0x56, 0xb7, 0x3b, 0xd3, 0x46, 0xba, 0xbe, 0x9a, 0xae, 0x97, 0x97, 0xda, 0x5f, 0x9f, 0x89, 0xba, 0xfe, 0x61, 0x66, 0x5f, 0x9e, 0xa4, 0x5b, 0xcb, 0xd5, 0x69, 0xcf, 0xfb, 0xfd, 0xdc, 0xac, 0x79, 0xac, 0x1d, 0x0b, 0xe5, 0x15, 0x75, 0x39, 0x2e, 0xe5, 0xa9, 0x2a, 0x60, 0xd7, 0xe3, 0x48, 0xd0, 0x1f, 0xd8, 0x61, 0x65, 0xfd, 0x2e, 0x5c, 0xef, 0x43, 0xf5, 0x63, 0x99, 0xb3, 0x45, 0x25, 0xe3, 0xbc, 0xf0, 0xe1, 0xad, 0xf7, 0x84, 0xcd, 0x82, 0x20, 0xe3, 0x6f, 0x2c, 0x77, 0x51, 0xf1, 0x11, 0x2e, 0x4a, 0x2c, 0xfd, 0x2f, 0x5e, 0x74, 0xa9, 0x37, 0x99, 0xff, 0xf7, 0x4c, 0x2d, 0xa8, 0xcf, 0x51, 0xfd, 0x5b, 0xe7, 0x51, 0x14, 0x6d, 0xbc, 0x2f, 0x5b, 0xb9, 0x77, 0x85, 0xad, 0xb4, 0x72, 0x99, 0xad, 0x7b, 0x6c, 0x6a, 0xdf, 0x4d, 0xca, 0x2f, 0xef, 0x8b, 0x5e, 0x4b, 0xf3, 0xd9, 0xfd, 0xbd, 0x47, 0x1a, 0x72, 0xe2, 0x41, 0xd8, 0xfa, 0xa1, 0x25, 0x00, 0xa3, 0xfe, 0x12, 0xda, 0xf6, 0x16, 0xb3, 0xb3, 0x08, 0x02, 0xfd, 0x0a, 0x6a, 0xab, 0x85, 0x17, 0xd7, 0x0f, 0xf4, 0x6b, 0xdf, 0x8f, 0xe2, 0x05, 0xf4, 0x5b, 0x13, 0x26, 0xa9, 0xe2, 0x57, 0xb6, 0xda, 0x76, 0x17, 0x3c, 0x52, 0x13, 0x8d, 0x83, 0xc0, 0x2b, 0xe7, 0x2e, 0xbd, 0xb0, 0xde, 0x98, 0x4f, 0x7a, 0x95, 0xa1, 0x75, 0x19, 0x6e, 0xda, 0x19, 0xff, 0x7f, 0xdd, 0x70, 0x01, 0x12, 0x3c, 0x9e, 0xd7, 0xfe, 0xc3, 0x22, 0x39, 0xce, 0x4f, 0x86, 0xd8, 0x85, 0x40, 0x75, 0xd4, 0xfe, 0x93, 0x57, 0xbc, 0x9b, 0x01, 0xa4, 0x71, 0x35, 0x70, 0x9d, 0x62, 0x91, 0x47, 0x4e, 0x32, 0xa2, 0x76, 0x16, 0x06, 0xaf, 0xc7, 0xe3, 0xe5, 0xdc, 0x25, 0xac, 0xe7, 0x68, 0x25, 0x69, 0x0f, 0x97, 0x8d, 0x91, 0x32, 0x81, 0x23, 0xb1, 0x08, 0xf3, 0xa3, 0x2b, 0x3d, 0xfb, 0xcf, 0x99, 0x12, 0x0a, 0x59, 0xb9, 0xbb, 0x76, 0x16, 0x71, 0xa2, 0x0b, 0x0a, 0x5a, 0x6c, 0x37, 0x99, 0x9d, 0xe6, 0x3a, 0x05, 0x89, 0xf7, 0xc6, 0xfc, 0xf3, 0xfe, 0x36, 0x97, 0x77, 0x86, 0xe4, 0x7c, 0x48, 0x93, 0x0b, 0x26, 0x8e, 0x31, 0xe9, 0x22, 0xcc, 0xd3, 0xe0, 0x56, 0x29, 0xc8, 0x26, 0xe6, 0x1f, 0xa8, 0xb8, 0x93, 0x98, 0xec, 0xd9, 0x7c, 0x4a, 0x45, 0xd3, 0x71, 0x35, 0x9f, 0x14, 0xc1, 0x99, 0xd5, 0x21, 0x0b, 0xfa, 0x0f, 0xfb, 0x31, 0x7a, 0xa0, 0x70, 0x35, 0xb3, 0x9b, 0x1b, 0xe7, 0x65, 0xfd, 0xe3, 0x7d, 0x0b, 0xcc, 0x34, 0x4b, 0xf1, 0x5a, 0x9f, 0x19, 0xa4, 0x8f, 0xc8, 0x30, 0xf1, 0x87, 0x99, 0xc2, 0x75, 0x55, 0x2a, 0x34, 0xd7, 0x81, 0x9c, 0x54, 0x12, 0x82, 0x69, 0x5f, 0x8b, 0x01, 0xc1, 0x45, 0x95, 0xf5, 0xb1, 0x2d, 0x27, 0x0d, 0xa9, 0xc3, 0x93, 0x54, 0x2f, 0x57, 0x04, 0x7b, 0x20, 0xb7, 0xac, 0x33, 0x68, 0xb3, 0xef, 0x9a, 0x33, 0x95, 0x82, 0x9d, 0xfa, 0x2a, 0xb9, 0x88, 0x06, 0x04, 0x88, 0x51, 0x2c, 0x46, 0xdb, 0x83, 0xd7, 0x2f, 0xea, 0x1f, 0x0f, 0x24, 0xab, 0x03, 0xef, 0xb0, 0x61, 0xc7, 0x90, 0xdc, 0x78, 0x17, 0xf2, 0x9a, 0xab}, /* This is a confirm1 packet, sequence number is 0x09f6, SSRC 0x12345678 */ {0x10, 0x00, 0x09, 0xf6, 0x5a, 0x52, 0x54, 0x50, 0x12, 0x34, 0x56, 0x78, 0x50, 0x5a, 0x00, 0x13, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x31, 0xb1, 0x21, 0xee, 0xe2, 0x67, 0xa4, 0xfd, 0xa6, 0x94, 0x24, 0x9a, 0x60, 0xf0, 0x2e, 0x5e, 0xd9, 0x33, 0xe1, 0xd8, 0x41, 0x54, 0xa3, 0x7c, 0xea, 0xe9, 0x61, 0xae, 0xf9, 0x19, 0x0d, 0xb3, 0x68, 0x68, 0x9e, 0xf8, 0x1a, 0x18, 0x91, 0x87, 0xc5, 0x6e, 0x5e, 0x2d, 0x5e, 0x32, 0xa2, 0xb2, 0x66, 0x31, 0xb8, 0xe5, 0x59, 0xc9, 0x10, 0xbb, 0xa0, 0x00, 0x6c, 0xee, 0x0c, 0x6d, 0xfb, 0xeb, 0x32, 0x85, 0xb6, 0x6e, 0x93}, /* This is a confirm2 packet, sequence number is 0x02d2, SSRC 0x87654321 */ {0x10, 0x00, 0x02, 0xd2, 0x5a, 0x52, 0x54, 0x50, 0x87, 0x65, 0x43, 0x21, 0x50, 0x5a, 0x00, 0x13, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x32, 0x0f, 0xec, 0xfa, 0x4b, 0x45, 0x17, 0x9d, 0xb3, 0x92, 0x7d, 0x1c, 0x53, 0x86, 0x01, 0x12, 0xd9, 0x25, 0x48, 0xca, 0x18, 0xb9, 0x10, 0x95, 0x04, 0xb7, 0xc8, 0xee, 0x87, 0x2b, 0xec, 0x59, 0x39, 0x92, 0x96, 0x11, 0x73, 0xa6, 0x69, 0x2b, 0x11, 0xcd, 0x1d, 0xa1, 0x73, 0xb2, 0xc9, 0x29, 0x6f, 0x82, 0x32, 0x6a, 0x0a, 0x56, 0x40, 0x57, 0xfb, 0xac, 0xab, 0x20, 0xb8, 0xe2, 0xa9, 0x2c, 0x61, 0x6a, 0x05, 0xe8, 0xb5}, /* This is a conf2ACK packet, sequence number 0x09f7, SSRC 0x12345678 */ {0x10, 0x00, 0x09, 0xf7, 0x5a, 0x52, 0x54, 0x50, 0x12, 0x34, 0x56, 0x78, 0x50, 0x5a, 0x00, 0x03, 0x43, 0x6f, 0x6e, 0x66, 0x32, 0x41, 0x43, 0x4b, 0x23, 0xc1, 0x1b, 0x45}, }; /* Hash images for both sides */ uint8_t H12345678[4][32] = { {0xbb, 0xbf, 0x7e, 0xb1, 0x14, 0xd5, 0xd4, 0x0c, 0x6b, 0xb0, 0x79, 0x58, 0x19, 0xc1, 0xd0, 0x83, 0xc9, 0xe1, 0xf4, 0x2e, 0x11, 0xcd, 0x7e, 0xc3, 0xaa, 0xd8, 0xb9, 0x17, 0xe6, 0xb5, 0x9e, 0x86}, {0x28, 0x7c, 0x28, 0xe4, 0xd7, 0x3d, 0x14, 0x39, 0xb5, 0x6d, 0x1c, 0x47, 0x9d, 0x59, 0x0a, 0xf2, 0x10, 0x33, 0xde, 0x6b, 0xd5, 0x2b, 0xfb, 0x26, 0xa5, 0x87, 0x4d, 0xe9, 0x20, 0x6b, 0x9f, 0xdd}, {0x70, 0x12, 0xef, 0x2e, 0x85, 0x2f, 0xfc, 0x84, 0xb8, 0x8d, 0xcc, 0x03, 0xd7, 0x8f, 0x53, 0x01, 0x63, 0xfb, 0xd3, 0xb0, 0x2d, 0xbb, 0x9e, 0x98, 0x22, 0x0d, 0xe3, 0xe3, 0x64, 0x25, 0x04, 0x0f}, {0xe8, 0xd5, 0x26, 0xc1, 0x3a, 0x0c, 0x4c, 0x6a, 0xce, 0x18, 0xaa, 0xc7, 0xc4, 0xa4, 0x07, 0x0e, 0x65, 0x7a, 0x4d, 0xca, 0x78, 0xf2, 0xcc, 0xcd, 0x20, 0x50, 0x38, 0x73, 0xe9, 0x7e, 0x08, 0x29} }; uint8_t H87654321[4][32] = { {0x09, 0x02, 0xcc, 0x13, 0xc4, 0x84, 0x03, 0x31, 0x68, 0x91, 0x05, 0x4d, 0xe0, 0x6d, 0xf4, 0xc9, 0x6a, 0xb5, 0xbe, 0x82, 0xe8, 0x37, 0x33, 0xb7, 0xa9, 0xce, 0xbe, 0xb5, 0x42, 0xaa, 0x54, 0xba}, {0x9e, 0xb2, 0xa5, 0x8b, 0xe8, 0x96, 0x37, 0xf5, 0x5a, 0x41, 0x34, 0xb2, 0xec, 0xda, 0x84, 0x95, 0xf0, 0xf8, 0x9b, 0xab, 0x61, 0x4f, 0x7c, 0x9e, 0x56, 0xb7, 0x3b, 0xd3, 0x46, 0xba, 0xbe, 0x9a}, {0xd9, 0xff, 0x14, 0x8b, 0x34, 0xaa, 0x69, 0xe9, 0x33, 0xc1, 0x62, 0xe6, 0x6b, 0xe8, 0xcd, 0x9d, 0xe3, 0x0f, 0xb7, 0x6a, 0xe8, 0x6a, 0x62, 0x2b, 0xcb, 0xe4, 0x6b, 0x91, 0x05, 0xc7, 0xc8, 0x7e}, {0x8d, 0x0f, 0x5a, 0x20, 0x79, 0x97, 0x42, 0x01, 0x99, 0x45, 0x45, 0xf7, 0x0e, 0x31, 0x06, 0xe1, 0x05, 0xc0, 0xb9, 0x24, 0xe9, 0xc9, 0x78, 0xc7, 0x38, 0xf5, 0x97, 0x48, 0xef, 0x42, 0x6a, 0x3e} }; /* mac and zrtp keys */ uint8_t mackeyi[32] = {0xdc, 0x47, 0xe1, 0xc7, 0x48, 0x11, 0xb1, 0x54, 0x14, 0x2a, 0x91, 0x29, 0x9f, 0xa4, 0x8b, 0x45, 0x87, 0x16, 0x8d, 0x3a, 0xe6, 0xb0, 0x0c, 0x08, 0x4f, 0xa5, 0x48, 0xd5, 0x96, 0x67, 0x1a, 0x1b}; uint8_t mackeyr[32] = {0x3a, 0xa5, 0x22, 0x43, 0x26, 0x13, 0x8f, 0xd6, 0x54, 0x59, 0x40, 0xb8, 0x5c, 0xf4, 0x0f, 0x0c, 0xbc, 0x9c, 0x4f, 0x7d, 0x55, 0xeb, 0x4b, 0xa5, 0x1e, 0x1c, 0x42, 0xd0, 0x5e, 0xac, 0x12, 0x06}; uint8_t zrtpkeyi[16] = {0x22, 0xf6, 0xea, 0xaa, 0xa4, 0xad, 0x53, 0x30, 0x71, 0x97, 0xcc, 0x68, 0x6b, 0xb0, 0xcb, 0x55}; uint8_t zrtpkeyr[16] = {0x09, 0x50, 0xcd, 0x9e, 0xc2, 0x78, 0x54, 0x31, 0x93, 0x2e, 0x99, 0x31, 0x15, 0x58, 0xd0, 0x2a}; void test_parser(void) { int i, retval; bzrtpPacket_t *zrtpPacket; /* Create zrtp Context to use H0-H3 chains and others */ bzrtpContext_t *context87654321 = bzrtp_createBzrtpContext(0x87654321); bzrtpContext_t *context12345678 = bzrtp_createBzrtpContext(0x12345678); /* replace created H by the patterns one to be able to generate the correct packet */ memcpy (context12345678->channelContext[0]->selfH[0], H12345678[0], 32); memcpy (context12345678->channelContext[0]->selfH[1], H12345678[1], 32); memcpy (context12345678->channelContext[0]->selfH[2], H12345678[2], 32); memcpy (context12345678->channelContext[0]->selfH[3], H12345678[3], 32); memcpy (context87654321->channelContext[0]->selfH[0], H87654321[0], 32); memcpy (context87654321->channelContext[0]->selfH[1], H87654321[1], 32); memcpy (context87654321->channelContext[0]->selfH[2], H87654321[2], 32); memcpy (context87654321->channelContext[0]->selfH[3], H87654321[3], 32); /* preset the key agreement algo in the contexts */ context87654321->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context12345678->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context87654321->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context12345678->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context87654321->channelContext[0]->hashAlgo = ZRTP_HASH_S256; context12345678->channelContext[0]->hashAlgo = ZRTP_HASH_S256; updateCryptoFunctionPointers(context87654321->channelContext[0]); updateCryptoFunctionPointers(context12345678->channelContext[0]); /* set the zrtp and mac keys */ context87654321->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context87654321->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context87654321->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context87654321->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); memcpy(context12345678->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context12345678->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context12345678->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context12345678->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); memcpy(context87654321->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context87654321->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context87654321->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context87654321->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); /* set the role: 87654321 is initiator in our exchange pattern */ context12345678->channelContext[0]->role = RESPONDER; for (i=0; i<TEST_PACKET_NUMBER; i++) { uint8_t freePacketFlag = 1; /* parse a packet string from patterns */ zrtpPacket = bzrtp_packetCheck(patternZRTPPackets[i], patternZRTPMetaData[i][0], (patternZRTPMetaData[i][1])-1, &retval); retval += bzrtp_packetParser((patternZRTPMetaData[i][2]==0x87654321)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x87654321)?context12345678->channelContext[0]:context87654321->channelContext[0], patternZRTPPackets[i], patternZRTPMetaData[i][0], zrtpPacket); /*printf("parsing Ret val is %x index is %d\n", retval, i);*/ /* We must store some packets in the context if we want to be able to parse further packets */ if (zrtpPacket->messageType==MSGTYPE_HELLO) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_DHPART1 || zrtpPacket->messageType==MSGTYPE_DHPART2) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } /* free the packet string as will be created again by the packetBuild function and might have been copied by packetParser */ free(zrtpPacket->packetString); /* build a packet string from the parser packet*/ retval = bzrtp_packetBuild((patternZRTPMetaData[i][2]==0x12345678)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x12345678)?context12345678->channelContext[0]:context87654321->channelContext[0], zrtpPacket, patternZRTPMetaData[i][1]); /* if (retval ==0) { packetDump(zrtpPacket, 1); } else { bzrtp_message("Ret val is %x index is %d\n", retval, i); }*/ /* check they are the same */ if (zrtpPacket->packetString != NULL) { CU_ASSERT_TRUE(memcmp(zrtpPacket->packetString, patternZRTPPackets[i], patternZRTPMetaData[i][0]) == 0); } else { CU_FAIL("Unable to build packet"); } if (freePacketFlag == 1) { bzrtp_freeZrtpPacket(zrtpPacket); } } bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); } /* context structure mainly used by statemachine test, but also needed by parserComplete to get the zid Filename */ typedef struct my_Context_struct { unsigned char nom[30]; /* nom du contexte */ bzrtpContext_t *peerContext; bzrtpChannelContext_t *peerChannelContext; char zidFilename[80]; /* nom du fichier de cache */ } my_Context_t; static void freeBuf(void* p){ free(p); } int floadAlice(void *clientData, uint8_t **output, uint32_t *size, zrtpFreeBuffer_callback *cb) { /* get filename from ClientData */ my_Context_t *clientContext = (my_Context_t *)clientData; char *filename = clientContext->zidFilename; FILE *ALICECACHE = fopen(filename, "r+"); fseek(ALICECACHE, 0L, SEEK_END); /* Position to end of file */ *size = ftell(ALICECACHE); /* Get file length */ rewind(ALICECACHE); /* Back to start of file */ *output = (uint8_t *)malloc(*size*sizeof(uint8_t)+1); if (fread(*output, 1, *size, ALICECACHE)==0){ fprintf(stderr,"floadAlice() fread() error\n"); } *(*output+*size) = '\0'; *size += 1; fclose(ALICECACHE); *cb=freeBuf; return *size; } int fwriteAlice(void *clientData, const uint8_t *input, uint32_t size) { /* get filename from ClientData */ my_Context_t *clientContext = (my_Context_t *)clientData; char *filename = clientContext->zidFilename; FILE *ALICECACHE = fopen(filename, "w+"); int retval = fwrite(input, 1, size, ALICECACHE); fclose(ALICECACHE); return retval; } int floadBob(void *clientData, uint8_t **output, uint32_t *size, zrtpFreeBuffer_callback *cb) { /* get filename from ClientData */ my_Context_t *clientContext = (my_Context_t *)clientData; char *filename = clientContext->zidFilename; FILE *BOBCACHE = fopen(filename, "r+"); fseek(BOBCACHE, 0L, SEEK_END); /* Position to end of file */ *size = ftell(BOBCACHE); /* Get file length */ rewind(BOBCACHE); /* Back to start of file */ *output = (uint8_t *)malloc(*size*sizeof(uint8_t)+1); if (fread(*output, 1, *size, BOBCACHE)==0){ fprintf(stderr,"floadBob(): fread error.\n"); return -1; } *(*output+*size) = '\0'; *size += 1; fclose(BOBCACHE); *cb=freeBuf; return *size; } int fwriteBob(void *clientData, const uint8_t *input, uint32_t size) { /* get filename from ClientData */ my_Context_t *clientContext = (my_Context_t *)clientData; char *filename = clientContext->zidFilename; FILE *BOBCACHE = fopen(filename, "w+"); int retval = fwrite(input, 1, size, BOBCACHE); fclose(BOBCACHE); return retval; } void test_parserComplete() { int retval; /* alice's maintained packet */ bzrtpPacket_t *alice_Hello, *alice_HelloFromBob, *alice_HelloACK, *alice_HelloACKFromBob; /* bob's maintained packet */ bzrtpPacket_t *bob_Hello, *bob_HelloFromAlice, *bob_HelloACK, *bob_HelloACKFromAlice; /* Create zrtp Context */ bzrtpContext_t *contextAlice = bzrtp_createBzrtpContext(0x12345678); /* Alice's SSRC of main channel is 12345678 */ bzrtpContext_t *contextBob = bzrtp_createBzrtpContext(0x87654321); /* Bob's SSRC of main channel is 87654321 */ bzrtpHelloMessage_t *alice_HelloFromBob_message; bzrtpHelloMessage_t *bob_HelloFromAlice_message; bzrtpPacket_t *alice_selfDHPart; bzrtpPacket_t *bob_selfDHPart; bzrtpPacket_t *alice_Commit; bzrtpPacket_t *bob_Commit; bzrtpPacket_t *bob_CommitFromAlice; bzrtpPacket_t *alice_CommitFromBob; uint8_t tmpBuffer[8]; bzrtpDHPartMessage_t *bob_DHPart1; bzrtpPacket_t *alice_DHPart1FromBob; bzrtpDHPartMessage_t *alice_DHPart1FromBob_message=NULL; bzrtpPacket_t *bob_DHPart2FromAlice; bzrtpDHPartMessage_t *bob_DHPart2FromAlice_message=NULL; uint16_t secretLength; uint16_t totalHashDataLength; uint8_t *dataToHash; uint16_t hashDataIndex = 0; uint8_t alice_totalHash[32]; /* Note : actual length of hash depends on the choosen algo */ uint8_t bob_totalHash[32]; /* Note : actual length of hash depends on the choosen algo */ uint8_t *s1=NULL; uint32_t s1Length=0; uint8_t *s2=NULL; uint32_t s2Length=0; uint8_t *s3=NULL; uint32_t s3Length=0; uint8_t alice_sasHash[32]; uint8_t bob_sasHash[32]; uint32_t sasValue; char sas[32]; bzrtpPacket_t *bob_Confirm1; bzrtpPacket_t *alice_Confirm1FromBob; bzrtpConfirmMessage_t *alice_Confirm1FromBob_message=NULL; bzrtpPacket_t *alice_Confirm2; bzrtpPacket_t *bob_Confirm2FromAlice; bzrtpConfirmMessage_t *bob_Confirm2FromAlice_message=NULL; bzrtpPacket_t *bob_Conf2ACK; bzrtpPacket_t *alice_Conf2ACKFromBob; bzrtpPacket_t *alice_Confirm1; bzrtpPacket_t *bob_Confirm1FromAlice; bzrtpConfirmMessage_t *bob_Confirm1FromAlice_message=NULL; bzrtpPacket_t *bob_Confirm2; bzrtpPacket_t *alice_Confirm2FromBob; bzrtpConfirmMessage_t *alice_Confirm2FromBob_message=NULL; bzrtpPacket_t *alice_Conf2ACK; bzrtpPacket_t *bob_Conf2ACKFromAlice; bzrtpCallbacks_t cbs={0}; /* Create the client context, used for zidFilename only */ my_Context_t clientContextAlice; my_Context_t clientContextBob; strcpy(clientContextAlice.zidFilename, "./ZIDAlice.txt"); strcpy(clientContextBob.zidFilename, "./ZIDBob.txt"); /* attach the clientContext to the bzrtp Context */ retval = bzrtp_setClientData(contextAlice, 0x12345678, (void *)&clientContextAlice); retval += bzrtp_setClientData(contextBob, 0x87654321, (void *)&clientContextBob); /* set the cache related callback functions */ cbs.bzrtp_loadCache=floadAlice; cbs.bzrtp_writeCache=fwriteAlice; bzrtp_setCallbacks(contextAlice, &cbs); cbs.bzrtp_loadCache=floadBob; cbs.bzrtp_writeCache=fwriteBob; bzrtp_setCallbacks(contextBob, &cbs); bzrtp_message ("Init the contexts\n"); /* end the context init */ bzrtp_initBzrtpContext(contextAlice); bzrtp_initBzrtpContext(contextBob); /* now create Alice and BOB Hello packet */ alice_Hello = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[0], MSGTYPE_HELLO, &retval); if (bzrtp_packetBuild(contextAlice, contextAlice->channelContext[0], alice_Hello, contextAlice->channelContext[0]->selfSequenceNumber) ==0) { contextAlice->channelContext[0]->selfSequenceNumber++; contextAlice->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = alice_Hello; } bob_Hello = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_HELLO, &retval); if (bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_Hello, contextBob->channelContext[0]->selfSequenceNumber) ==0) { contextBob->channelContext[0]->selfSequenceNumber++; contextBob->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = bob_Hello; } /* now send Alice Hello's to Bob and vice-versa, so they parse them */ alice_HelloFromBob = bzrtp_packetCheck(bob_Hello->packetString, bob_Hello->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_Hello->packetString, bob_Hello->messageLength+16, alice_HelloFromBob); bzrtp_message ("Alice parsing returns %x\n", retval); if (retval==0) { bzrtpHelloMessage_t *alice_HelloFromBob_message; int i; contextAlice->channelContext[0]->peerSequenceNumber = alice_HelloFromBob->sequenceNumber; /* save bob's Hello packet in Alice's context */ contextAlice->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = alice_HelloFromBob; /* determine crypto Algo to use */ alice_HelloFromBob_message = (bzrtpHelloMessage_t *)alice_HelloFromBob->messageData; retval = crypoAlgoAgreement(contextAlice, contextAlice->channelContext[0], contextAlice->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData); if (retval == 0) { bzrtp_message ("Alice selected algo %x\n", contextAlice->channelContext[0]->keyAgreementAlgo); memcpy(contextAlice->peerZID, alice_HelloFromBob_message->ZID, 12); } /* check if the peer accept MultiChannel */ for (i=0; i<alice_HelloFromBob_message->kc; i++) { if (alice_HelloFromBob_message->supportedKeyAgreement[i] == ZRTP_KEYAGREEMENT_Mult) { contextAlice->peerSupportMultiChannel = 1; } } } bob_HelloFromAlice = bzrtp_packetCheck(alice_Hello->packetString, alice_Hello->messageLength+16, contextBob->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[0], alice_Hello->packetString, alice_Hello->messageLength+16, bob_HelloFromAlice); bzrtp_message ("Bob parsing returns %x\n", retval); if (retval==0) { bzrtpHelloMessage_t *bob_HelloFromAlice_message; int i; contextBob->channelContext[0]->peerSequenceNumber = bob_HelloFromAlice->sequenceNumber; /* save alice's Hello packet in bob's context */ contextBob->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = bob_HelloFromAlice; /* determine crypto Algo to use */ bob_HelloFromAlice_message = (bzrtpHelloMessage_t *)bob_HelloFromAlice->messageData; retval = crypoAlgoAgreement(contextBob, contextBob->channelContext[0], contextBob->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData); if (retval == 0) { bzrtp_message ("Bob selected algo %x\n", contextBob->channelContext[0]->keyAgreementAlgo); memcpy(contextBob->peerZID, bob_HelloFromAlice_message->ZID, 12); } /* check if the peer accept MultiChannel */ for (i=0; i<bob_HelloFromAlice_message->kc; i++) { if (bob_HelloFromAlice_message->supportedKeyAgreement[i] == ZRTP_KEYAGREEMENT_Mult) { contextBob->peerSupportMultiChannel = 1; } } } /* update context with hello message information : H3 and compute initiator and responder's shared secret Hashs */ alice_HelloFromBob_message = (bzrtpHelloMessage_t *)alice_HelloFromBob->messageData; memcpy(contextAlice->channelContext[0]->peerH[3], alice_HelloFromBob_message->H3, 32); bob_HelloFromAlice_message = (bzrtpHelloMessage_t *)bob_HelloFromAlice->messageData; memcpy(contextBob->channelContext[0]->peerH[3], bob_HelloFromAlice_message->H3, 32); /* get the secrets associated to peer ZID */ bzrtp_getPeerAssociatedSecretsHash(contextAlice, alice_HelloFromBob_message->ZID); bzrtp_getPeerAssociatedSecretsHash(contextBob, bob_HelloFromAlice_message->ZID); /* compute the initiator hashed secret as in rfc section 4.3.1 */ if (contextAlice->cachedSecret.rs1!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.rs1, contextAlice->cachedSecret.rs1Length, (uint8_t *)"Initiator", 9, 8, contextAlice->initiatorCachedSecretHash.rs1ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->initiatorCachedSecretHash.rs1ID, 8); } if (contextAlice->cachedSecret.rs2!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.rs2, contextAlice->cachedSecret.rs2Length, (uint8_t *)"Initiator", 9, 8, contextAlice->initiatorCachedSecretHash.rs2ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->initiatorCachedSecretHash.rs2ID, 8); } if (contextAlice->cachedSecret.auxsecret!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.auxsecret, contextAlice->cachedSecret.auxsecretLength, contextAlice->channelContext[0]->selfH[3], 32, 8, contextAlice->channelContext[0]->initiatorAuxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->channelContext[0]->initiatorAuxsecretID, 8); } if (contextAlice->cachedSecret.pbxsecret!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.pbxsecret, contextAlice->cachedSecret.pbxsecretLength, (uint8_t *)"Initiator", 9, 8, contextAlice->initiatorCachedSecretHash.pbxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->initiatorCachedSecretHash.pbxsecretID, 8); } if (contextAlice->cachedSecret.rs1!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.rs1, contextAlice->cachedSecret.rs1Length, (uint8_t *)"Responder", 9, 8, contextAlice->responderCachedSecretHash.rs1ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->responderCachedSecretHash.rs1ID, 8); } if (contextAlice->cachedSecret.rs2!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.rs2, contextAlice->cachedSecret.rs2Length, (uint8_t *)"Responder", 9, 8, contextAlice->responderCachedSecretHash.rs2ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->responderCachedSecretHash.rs2ID, 8); } if (contextAlice->cachedSecret.auxsecret!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.auxsecret, contextAlice->cachedSecret.auxsecretLength, contextAlice->channelContext[0]->peerH[3], 32, 8, contextAlice->channelContext[0]->responderAuxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->channelContext[0]->responderAuxsecretID, 8); } if (contextAlice->cachedSecret.pbxsecret!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.pbxsecret, contextAlice->cachedSecret.pbxsecretLength, (uint8_t *)"Responder", 9, 8, contextAlice->responderCachedSecretHash.pbxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->responderCachedSecretHash.pbxsecretID, 8); } /* Bob hashes*/ if (contextBob->cachedSecret.rs1!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.rs1, contextBob->cachedSecret.rs1Length, (uint8_t *)"Initiator", 9, 8, contextBob->initiatorCachedSecretHash.rs1ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->initiatorCachedSecretHash.rs1ID, 8); } if (contextBob->cachedSecret.rs2!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.rs2, contextBob->cachedSecret.rs2Length, (uint8_t *)"Initiator", 9, 8, contextBob->initiatorCachedSecretHash.rs2ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->initiatorCachedSecretHash.rs2ID, 8); } if (contextBob->cachedSecret.auxsecret!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.auxsecret, contextBob->cachedSecret.auxsecretLength, contextBob->channelContext[0]->selfH[3], 32, 8, contextBob->channelContext[0]->initiatorAuxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->channelContext[0]->initiatorAuxsecretID, 8); } if (contextBob->cachedSecret.pbxsecret!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.pbxsecret, contextBob->cachedSecret.pbxsecretLength, (uint8_t *)"Initiator", 9, 8, contextBob->initiatorCachedSecretHash.pbxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->initiatorCachedSecretHash.pbxsecretID, 8); } if (contextBob->cachedSecret.rs1!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.rs1, contextBob->cachedSecret.rs1Length, (uint8_t *)"Responder", 9, 8, contextBob->responderCachedSecretHash.rs1ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->responderCachedSecretHash.rs1ID, 8); } if (contextBob->cachedSecret.rs2!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.rs2, contextBob->cachedSecret.rs2Length, (uint8_t *)"Responder", 9, 8, contextBob->responderCachedSecretHash.rs2ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->responderCachedSecretHash.rs2ID, 8); } if (contextBob->cachedSecret.auxsecret!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.auxsecret, contextBob->cachedSecret.auxsecretLength, contextBob->channelContext[0]->peerH[3], 32, 8, contextBob->channelContext[0]->responderAuxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->channelContext[0]->responderAuxsecretID, 8); } if (contextBob->cachedSecret.pbxsecret!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.pbxsecret, contextBob->cachedSecret.pbxsecretLength, (uint8_t *)"Responder", 9, 8, contextBob->responderCachedSecretHash.pbxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->responderCachedSecretHash.pbxsecretID, 8); } /* dump alice's packet on both sides */ bzrtp_message ("\nAlice original Packet is \n"); packetDump(alice_Hello, 1); bzrtp_message ("\nBob's parsed Alice Packet is \n"); packetDump(bob_HelloFromAlice, 0); /* Create the DHPart2 packet (that we then may change to DHPart1 if we ended to be the responder) */ alice_selfDHPart = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[0], MSGTYPE_DHPART2, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[0], alice_selfDHPart, 0); /* we don't care now about sequence number as we just need to build the message to be able to insert a hash of it into the commit packet */ if (retval == 0) { /* ok, insert it in context as we need it to build the commit packet */ contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID] = alice_selfDHPart; } else { bzrtp_message ("Alice building DHPart packet returns %x\n", retval); } bob_selfDHPart = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_DHPART2, &retval); retval +=bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_selfDHPart, 0); /* we don't care now about sequence number as we just need to build the message to be able to insert a hash of it into the commit packet */ if (retval == 0) { /* ok, insert it in context as we need it to build the commit packet */ contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID] = bob_selfDHPart; } else { bzrtp_message ("Bob building DHPart packet returns %x\n", retval); } bzrtp_message("Alice DHPart packet:\n"); packetDump(alice_selfDHPart,0); bzrtp_message("Bob DHPart packet:\n"); packetDump(bob_selfDHPart,0); /* respond to HELLO packet with an HelloACK - 1 create packets */ alice_HelloACK = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[0], MSGTYPE_HELLOACK, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[0], alice_HelloACK, contextAlice->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextAlice->channelContext[0]->selfSequenceNumber++; } else { bzrtp_message("Alice building HelloACK return %x\n", retval); } bob_HelloACK = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_HELLOACK, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_HelloACK, contextBob->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[0]->selfSequenceNumber++; } else { bzrtp_message("Bob building HelloACK return %x\n", retval); } /* exchange the HelloACK */ alice_HelloACKFromBob = bzrtp_packetCheck(bob_HelloACK->packetString, bob_HelloACK->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_HelloACK->packetString, bob_HelloACK->messageLength+16, alice_HelloACKFromBob); bzrtp_message ("Alice parsing Hello ACK returns %x\n", retval); if (retval==0) { contextAlice->channelContext[0]->peerSequenceNumber = alice_HelloACKFromBob->sequenceNumber; } bob_HelloACKFromAlice = bzrtp_packetCheck(alice_HelloACK->packetString, alice_HelloACK->messageLength+16, contextBob->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[0], alice_HelloACK->packetString, alice_HelloACK->messageLength+16, bob_HelloACKFromAlice); bzrtp_message ("Bob parsing Hello ACK returns %x\n", retval); if (retval==0) { contextBob->channelContext[0]->peerSequenceNumber = bob_HelloACKFromAlice->sequenceNumber; } bzrtp_freeZrtpPacket(alice_HelloACK); bzrtp_freeZrtpPacket(bob_HelloACK); bzrtp_freeZrtpPacket(alice_HelloACKFromBob); bzrtp_freeZrtpPacket(bob_HelloACKFromAlice); /* now build the commit message (both Alice and Bob will send it, then use the mechanism of rfc section 4.2 to determine who will be the initiator)*/ alice_Commit = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[0], MSGTYPE_COMMIT, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[0], alice_Commit, contextAlice->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextAlice->channelContext[0]->selfSequenceNumber++; contextAlice->channelContext[0]->selfPackets[COMMIT_MESSAGE_STORE_ID] = alice_Commit; } bzrtp_message("Alice building Commit return %x\n", retval); bob_Commit = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_COMMIT, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_Commit, contextBob->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[0]->selfSequenceNumber++; contextBob->channelContext[0]->selfPackets[COMMIT_MESSAGE_STORE_ID] = bob_Commit; } bzrtp_message("Bob building Commit return %x\n", retval); /* and exchange the commits */ bob_CommitFromAlice = bzrtp_packetCheck(alice_Commit->packetString, alice_Commit->messageLength+16, contextBob->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[0], alice_Commit->packetString, alice_Commit->messageLength+16, bob_CommitFromAlice); bzrtp_message ("Bob parsing Commit returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ bzrtpCommitMessage_t *bob_CommitFromAlice_message = (bzrtpCommitMessage_t *)bob_CommitFromAlice->messageData; contextBob->channelContext[0]->peerSequenceNumber = bob_CommitFromAlice->sequenceNumber; memcpy(contextBob->channelContext[0]->peerH[2], bob_CommitFromAlice_message->H2, 32); contextBob->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = bob_CommitFromAlice; } packetDump(bob_CommitFromAlice, 0); alice_CommitFromBob = bzrtp_packetCheck(bob_Commit->packetString, bob_Commit->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_Commit->packetString, bob_Commit->messageLength+16, alice_CommitFromBob); bzrtp_message ("Alice parsing Commit returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextAlice->channelContext[0]->peerSequenceNumber = alice_CommitFromBob->sequenceNumber; /* Alice will be the initiator (commit contention not implemented in this test) so just discard bob's commit */ /*bzrtpCommirMessage_t *alice_CommitFromBob_message = (bzrtpCommitMessage_t *)alice_CommitFromBob->messageData; memcpy(contextAlice->channelContext[0]->peerH[2], alice_CommitFromBob_message->H2, 32); contextAlice->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = alice_CommitFromBob;*/ } packetDump(alice_CommitFromBob, 0); bzrtp_freeZrtpPacket(alice_CommitFromBob); /* Now determine who shall be the initiator : rfc section 4.2 */ /* select the one with the lowest value of hvi */ /* for test purpose, we will set Alice as the initiator */ contextBob->channelContext[0]->role = RESPONDER; /* Bob (responder) shall update his selected algo list to match Alice selection */ /* no need to do this here as we have the same selection */ /* Bob is the responder, rebuild his DHPart packet to be responder and not initiator : */ /* as responder, bob must also swap his aux shared secret between responder and initiator as they are computed using the H3 and not a constant string */ memcpy(tmpBuffer, contextBob->channelContext[0]->initiatorAuxsecretID, 8); memcpy(contextBob->channelContext[0]->initiatorAuxsecretID, contextBob->channelContext[0]->responderAuxsecretID, 8); memcpy(contextBob->channelContext[0]->responderAuxsecretID, tmpBuffer, 8); contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageType = MSGTYPE_DHPART1; /* we are now part 1*/ bob_DHPart1 = (bzrtpDHPartMessage_t *)contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageData; /* change the shared secret ID to the responder one (we set them by default to the initiator's one) */ memcpy(bob_DHPart1->rs1ID, contextBob->responderCachedSecretHash.rs1ID, 8); memcpy(bob_DHPart1->rs2ID, contextBob->responderCachedSecretHash.rs2ID, 8); memcpy(bob_DHPart1->auxsecretID, contextBob->channelContext[0]->responderAuxsecretID, 8); memcpy(bob_DHPart1->pbxsecretID, contextBob->responderCachedSecretHash.pbxsecretID, 8); retval +=bzrtp_packetBuild(contextBob, contextBob->channelContext[0], contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID],contextBob->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[0]->selfSequenceNumber++; } bzrtp_message("Bob building DHPart1 return %x\n", retval); /* Alice parse bob's DHPart1 message */ alice_DHPart1FromBob = bzrtp_packetCheck(contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+16, alice_DHPart1FromBob); bzrtp_message ("Alice parsing DHPart1 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextAlice->channelContext[0]->peerSequenceNumber = alice_DHPart1FromBob->sequenceNumber; alice_DHPart1FromBob_message = (bzrtpDHPartMessage_t *)alice_DHPart1FromBob->messageData; memcpy(contextAlice->channelContext[0]->peerH[1], alice_DHPart1FromBob_message->H1, 32); contextAlice->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = alice_DHPart1FromBob; } packetDump(alice_DHPart1FromBob, 1); /* Now Alice may check which shared secret she expected and if they are valid in bob's DHPart1 */ if (contextAlice->cachedSecret.rs1!=NULL) { if (memcmp(contextAlice->responderCachedSecretHash.rs1ID, alice_DHPart1FromBob_message->rs1ID,8) != 0) { bzrtp_message ("Alice found that requested shared secret rs1 ID differs!\n"); } else { bzrtp_message("Alice validate rs1ID from bob DHPart1\n"); } } if (contextAlice->cachedSecret.rs2!=NULL) { if (memcmp(contextAlice->responderCachedSecretHash.rs2ID, alice_DHPart1FromBob_message->rs2ID,8) != 0) { bzrtp_message ("Alice found that requested shared secret rs2 ID differs!\n"); } else { bzrtp_message("Alice validate rs2ID from bob DHPart1\n"); } } if (contextAlice->cachedSecret.auxsecret!=NULL) { if (memcmp(contextAlice->channelContext[0]->responderAuxsecretID, alice_DHPart1FromBob_message->auxsecretID,8) != 0) { bzrtp_message ("Alice found that requested shared secret aux secret ID differs!\n"); } else { bzrtp_message("Alice validate aux secret ID from bob DHPart1\n"); } } if (contextAlice->cachedSecret.pbxsecret!=NULL) { if (memcmp(contextAlice->responderCachedSecretHash.pbxsecretID, alice_DHPart1FromBob_message->pbxsecretID,8) != 0) { bzrtp_message ("Alice found that requested shared secret pbx secret ID differs!\n"); } else { bzrtp_message("Alice validate pbxsecretID from bob DHPart1\n"); } } /* Now Alice shall check that the PV from bob is not 1 or Prime-1 TODO*/ /* Compute the shared DH secret */ contextAlice->DHMContext->peer = (uint8_t *)malloc(contextAlice->channelContext[0]->keyAgreementLength*sizeof(uint8_t)); memcpy (contextAlice->DHMContext->peer, alice_DHPart1FromBob_message->pv, contextAlice->channelContext[0]->keyAgreementLength); bctoolbox_DHMComputeSecret(contextAlice->DHMContext, (int (*)(void *, uint8_t *, size_t))bctoolbox_rng_get, (void *)contextAlice->RNGContext); /* So Alice send bob her DHPart2 message which is already prepared and stored (we just need to update the sequence number) */ bzrtp_packetUpdateSequenceNumber(contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID], contextAlice->channelContext[0]->selfSequenceNumber); contextAlice->channelContext[0]->selfSequenceNumber++; /* Bob parse Alice's DHPart2 message */ bob_DHPart2FromAlice = bzrtp_packetCheck(contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+16, contextBob->channelContext[0]->peerSequenceNumber, &retval); bzrtp_message ("Bob checking DHPart2 returns %x\n", retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[0], contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+16, bob_DHPart2FromAlice); bzrtp_message ("Bob parsing DHPart2 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextBob->channelContext[0]->peerSequenceNumber = bob_DHPart2FromAlice->sequenceNumber; bob_DHPart2FromAlice_message = (bzrtpDHPartMessage_t *)bob_DHPart2FromAlice->messageData; memcpy(contextBob->channelContext[0]->peerH[1], bob_DHPart2FromAlice_message->H1, 32); contextBob->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = bob_DHPart2FromAlice; } packetDump(bob_DHPart2FromAlice, 0); /* Now Bob may check which shared secret she expected and if they are valid in bob's DHPart1 */ if (contextBob->cachedSecret.rs1!=NULL) { if (memcmp(contextBob->initiatorCachedSecretHash.rs1ID, bob_DHPart2FromAlice_message->rs1ID,8) != 0) { bzrtp_message ("Bob found that requested shared secret rs1 ID differs!\n"); } else { bzrtp_message("Bob validate rs1ID from Alice DHPart2\n"); } } if (contextBob->cachedSecret.rs2!=NULL) { if (memcmp(contextBob->initiatorCachedSecretHash.rs2ID, bob_DHPart2FromAlice_message->rs2ID,8) != 0) { bzrtp_message ("Bob found that requested shared secret rs2 ID differs!\n"); } else { bzrtp_message("Bob validate rs2ID from Alice DHPart2\n"); } } if (contextBob->cachedSecret.auxsecret!=NULL) { if (memcmp(contextBob->channelContext[0]->initiatorAuxsecretID, bob_DHPart2FromAlice_message->auxsecretID,8) != 0) { bzrtp_message ("Bob found that requested shared secret aux secret ID differs!\n"); } else { bzrtp_message("Bob validate aux secret ID from Alice DHPart2\n"); } } if (contextBob->cachedSecret.pbxsecret!=NULL) { if (memcmp(contextBob->initiatorCachedSecretHash.pbxsecretID, bob_DHPart2FromAlice_message->pbxsecretID,8) != 0) { bzrtp_message ("Bob found that requested shared secret pbx secret ID differs!\n"); } else { bzrtp_message("Bob validate pbxsecretID from Alice DHPart2\n"); } } /* Now Bob shall check that the PV from Alice is not 1 or Prime-1 TODO*/ /* Compute the shared DH secret */ contextBob->DHMContext->peer = (uint8_t *)malloc(contextBob->channelContext[0]->keyAgreementLength*sizeof(uint8_t)); memcpy (contextBob->DHMContext->peer, bob_DHPart2FromAlice_message->pv, contextBob->channelContext[0]->keyAgreementLength); bctoolbox_DHMComputeSecret(contextBob->DHMContext, (int (*)(void *, uint8_t *, size_t))bctoolbox_rng_get, (void *)contextAlice->RNGContext); /* JUST FOR TEST: check that the generated secrets are the same */ secretLength = bob_DHPart2FromAlice->messageLength-84; /* length of generated secret is the same than public value */ if (memcmp(contextBob->DHMContext->key, contextAlice->DHMContext->key, secretLength)==0) { bzrtp_message("Secret Key correctly exchanged \n"); CU_PASS("Secret Key exchange OK"); } else { CU_FAIL("Secret Key exchange failed"); bzrtp_message("ERROR : secretKey exchange failed!!\n"); } /* now compute the total_hash as in rfc section 4.4.1.4 * total_hash = hash(Hello of responder || Commit || DHPart1 || DHPart2) */ totalHashDataLength = bob_Hello->messageLength + alice_Commit->messageLength + contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength + alice_selfDHPart->messageLength; dataToHash = (uint8_t *)malloc(totalHashDataLength*sizeof(uint8_t)); /* get all data from Alice */ memcpy(dataToHash, contextAlice->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextAlice->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextAlice->channelContext[0]->selfPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[0]->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextAlice->channelContext[0]->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextAlice->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextAlice->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength); contextAlice->channelContext[0]->hashFunction(dataToHash, totalHashDataLength, 32, alice_totalHash); /* get all data from Bob */ hashDataIndex = 0; memcpy(dataToHash, contextBob->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextBob->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextBob->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextBob->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextBob->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength); contextBob->channelContext[0]->hashFunction(dataToHash, totalHashDataLength, 32, bob_totalHash); if (memcmp(bob_totalHash, alice_totalHash, 32) == 0) { bzrtp_message("Got the same total hash\n"); CU_PASS("Total Hash match"); } else { bzrtp_message("AARGG!! total hash mismatch"); CU_FAIL("Total Hash mismatch"); } /* now compute s0 and KDF_context as in rfc section 4.4.1.4 s0 = hash(counter || DHResult || "ZRTP-HMAC-KDF" || ZIDi || ZIDr || total_hash || len(s1) || s1 || len(s2) || s2 || len(s3) || s3) counter is a fixed 32 bits integer in big endian set to 1 : 0x00000001 */ free(dataToHash); contextAlice->channelContext[0]->KDFContextLength = 24+32;/* actual depends on selected hash length*/ contextAlice->channelContext[0]->KDFContext = (uint8_t *)malloc(contextAlice->channelContext[0]->KDFContextLength*sizeof(uint8_t)); memcpy(contextAlice->channelContext[0]->KDFContext, contextAlice->selfZID, 12); /* ZIDi*/ memcpy(contextAlice->channelContext[0]->KDFContext+12, contextAlice->peerZID, 12); /* ZIDr */ memcpy(contextAlice->channelContext[0]->KDFContext+24, alice_totalHash, 32); /* total Hash*/ /* get s1 from rs1 or rs2 */ if (contextAlice->cachedSecret.rs1 != NULL) { /* if there is a s1 (already validated when received the DHpacket) */ s1 = contextAlice->cachedSecret.rs1; s1Length = contextAlice->cachedSecret.rs1Length; } else if (contextAlice->cachedSecret.rs2 != NULL) { /* otherwise if there is a s2 (already validated when received the DHpacket) */ s1 = contextAlice->cachedSecret.rs2; s1Length = contextAlice->cachedSecret.rs2Length; } /* s2 is the auxsecret */ s2 = contextAlice->cachedSecret.auxsecret; /* this may be null if no match or no aux secret where found */ s2Length = contextAlice->cachedSecret.auxsecretLength; /* this may be 0 if no match or no aux secret where found */ /* s3 is the pbxsecret */ s3 = contextAlice->cachedSecret.pbxsecret; /* this may be null if no match or no pbx secret where found */ s3Length = contextAlice->cachedSecret.pbxsecretLength; /* this may be 0 if no match or no pbx secret where found */ totalHashDataLength = 4+secretLength+13/*ZRTP-HMAC-KDF string*/ + 12 + 12 + 32 + 4 +s1Length + 4 +s2Length + 4 + s3Length; /* secret length was computed before as the length of DH secret data */ dataToHash = (uint8_t *)malloc(totalHashDataLength*sizeof(uint8_t)); dataToHash[0] = 0x00; dataToHash[1] = 0x00; dataToHash[2] = 0x00; dataToHash[3] = 0x01; hashDataIndex = 4; memcpy(dataToHash+hashDataIndex, contextAlice->DHMContext->key, secretLength); hashDataIndex += secretLength; memcpy(dataToHash+hashDataIndex, "ZRTP-HMAC-KDF", 13); hashDataIndex += 13; memcpy(dataToHash+hashDataIndex, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength); hashDataIndex += 56; dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s1Length&0xFF); if (s1!=NULL) { memcpy(dataToHash+hashDataIndex, s1, s1Length); hashDataIndex += s1Length; } dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s2Length&0xFF); if (s2!=NULL) { memcpy(dataToHash+hashDataIndex, s2, s2Length); hashDataIndex += s2Length; } dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s3Length&0xFF); if (s3!=NULL) { memcpy(dataToHash+hashDataIndex, s3, s3Length); hashDataIndex += s3Length; } contextAlice->channelContext[0]->s0 = (uint8_t *)malloc(32*sizeof(uint8_t)); contextAlice->channelContext[0]->hashFunction(dataToHash, totalHashDataLength, 32, contextAlice->channelContext[0]->s0); /* destroy all cached keys in context */ if (contextAlice->cachedSecret.rs1!=NULL) { bzrtp_DestroyKey(contextAlice->cachedSecret.rs1, contextAlice->cachedSecret.rs1Length, contextAlice->RNGContext); free(contextAlice->cachedSecret.rs1); contextAlice->cachedSecret.rs1 = NULL; } if (contextAlice->cachedSecret.rs2!=NULL) { bzrtp_DestroyKey(contextAlice->cachedSecret.rs2, contextAlice->cachedSecret.rs2Length, contextAlice->RNGContext); free(contextAlice->cachedSecret.rs2); contextAlice->cachedSecret.rs2 = NULL; } if (contextAlice->cachedSecret.auxsecret!=NULL) { bzrtp_DestroyKey(contextAlice->cachedSecret.auxsecret, contextAlice->cachedSecret.auxsecretLength, contextAlice->RNGContext); free(contextAlice->cachedSecret.auxsecret); contextAlice->cachedSecret.auxsecret = NULL; } if (contextAlice->cachedSecret.pbxsecret!=NULL) { bzrtp_DestroyKey(contextAlice->cachedSecret.pbxsecret, contextAlice->cachedSecret.pbxsecretLength, contextAlice->RNGContext); free(contextAlice->cachedSecret.pbxsecret); contextAlice->cachedSecret.pbxsecret = NULL; } /*** Do the same for bob ***/ /* get s1 from rs1 or rs2 */ s1=NULL; s2=NULL; s3=NULL; contextBob->channelContext[0]->KDFContextLength = 24+32;/* actual depends on selected hash length*/ contextBob->channelContext[0]->KDFContext = (uint8_t *)malloc(contextBob->channelContext[0]->KDFContextLength*sizeof(uint8_t)); memcpy(contextBob->channelContext[0]->KDFContext, contextBob->peerZID, 12); /* ZIDi*/ memcpy(contextBob->channelContext[0]->KDFContext+12, contextBob->selfZID, 12); /* ZIDr */ memcpy(contextBob->channelContext[0]->KDFContext+24, bob_totalHash, 32); /* total Hash*/ if (contextBob->cachedSecret.rs1 != NULL) { /* if there is a s1 (already validated when received the DHpacket) */ s1 = contextBob->cachedSecret.rs1; s1Length = contextBob->cachedSecret.rs1Length; } else if (contextBob->cachedSecret.rs2 != NULL) { /* otherwise if there is a s2 (already validated when received the DHpacket) */ s1 = contextBob->cachedSecret.rs2; s1Length = contextBob->cachedSecret.rs2Length; } /* s2 is the auxsecret */ s2 = contextBob->cachedSecret.auxsecret; /* this may be null if no match or no aux secret where found */ s2Length = contextBob->cachedSecret.auxsecretLength; /* this may be 0 if no match or no aux secret where found */ /* s3 is the pbxsecret */ s3 = contextBob->cachedSecret.pbxsecret; /* this may be null if no match or no pbx secret where found */ s3Length = contextBob->cachedSecret.pbxsecretLength; /* this may be 0 if no match or no pbx secret where found */ free(dataToHash); dataToHash = (uint8_t *)malloc(totalHashDataLength*sizeof(uint8_t)); dataToHash[0] = 0x00; dataToHash[1] = 0x00; dataToHash[2] = 0x00; dataToHash[3] = 0x01; hashDataIndex = 4; memcpy(dataToHash+hashDataIndex, contextBob->DHMContext->key, secretLength); hashDataIndex += secretLength; memcpy(dataToHash+hashDataIndex, "ZRTP-HMAC-KDF", 13); hashDataIndex += 13; memcpy(dataToHash+hashDataIndex, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength); hashDataIndex += 56; dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s1Length&0xFF); if (s1!=NULL) { memcpy(dataToHash+hashDataIndex, s1, s1Length); hashDataIndex += s1Length; } dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s2Length&0xFF); if (s2!=NULL) { memcpy(dataToHash+hashDataIndex, s2, s2Length); hashDataIndex += s2Length; } dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s3Length&0xFF); if (s3!=NULL) { memcpy(dataToHash+hashDataIndex, s3, s3Length); hashDataIndex += s3Length; } contextBob->channelContext[0]->s0 = (uint8_t *)malloc(32*sizeof(uint8_t)); contextBob->channelContext[0]->hashFunction(dataToHash, totalHashDataLength, 32, contextBob->channelContext[0]->s0); free(dataToHash); /* destroy all cached keys in context */ if (contextBob->cachedSecret.rs1!=NULL) { bzrtp_DestroyKey(contextBob->cachedSecret.rs1, contextBob->cachedSecret.rs1Length, contextBob->RNGContext); free(contextBob->cachedSecret.rs1); contextBob->cachedSecret.rs1 = NULL; } if (contextBob->cachedSecret.rs2!=NULL) { bzrtp_DestroyKey(contextBob->cachedSecret.rs2, contextBob->cachedSecret.rs2Length, contextBob->RNGContext); free(contextBob->cachedSecret.rs2); contextBob->cachedSecret.rs2 = NULL; } if (contextBob->cachedSecret.auxsecret!=NULL) { bzrtp_DestroyKey(contextBob->cachedSecret.auxsecret, contextBob->cachedSecret.auxsecretLength, contextBob->RNGContext); free(contextBob->cachedSecret.auxsecret); contextBob->cachedSecret.auxsecret = NULL; } if (contextBob->cachedSecret.pbxsecret!=NULL) { bzrtp_DestroyKey(contextBob->cachedSecret.pbxsecret, contextBob->cachedSecret.pbxsecretLength, contextBob->RNGContext); free(contextBob->cachedSecret.pbxsecret); contextBob->cachedSecret.pbxsecret = NULL; } /* DEBUG compare s0 */ if (memcmp(contextBob->channelContext[0]->s0, contextAlice->channelContext[0]->s0, 32)==0) { bzrtp_message("Got the same s0\n"); CU_PASS("s0 match"); } else { bzrtp_message("ERROR s0 differs\n"); CU_PASS("s0 mismatch"); } /* now compute the ZRTPSession key : section 4.5.2 * ZRTPSess = KDF(s0, "ZRTP Session Key", KDF_Context, negotiated hash length)*/ contextAlice->ZRTPSessLength=32; /* must be set to the length of negotiated hash */ contextAlice->ZRTPSess = (uint8_t *)malloc(contextAlice->ZRTPSessLength*sizeof(uint8_t)); retval = bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"ZRTP Session Key", 16, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, /* this one too depends on selected hash */ contextAlice->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, contextAlice->ZRTPSess); contextBob->ZRTPSessLength=32; /* must be set to the length of negotiated hash */ contextBob->ZRTPSess = (uint8_t *)malloc(contextBob->ZRTPSessLength*sizeof(uint8_t)); retval = bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"ZRTP Session Key", 16, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, /* this one too depends on selected hash */ contextBob->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, contextBob->ZRTPSess); /* DEBUG compare ZRTPSess Key */ if (memcmp(contextBob->ZRTPSess, contextAlice->ZRTPSess, 32)==0) { bzrtp_message("Got the same ZRTPSess\n"); CU_PASS("ZRTPSess match"); } else { bzrtp_message("ERROR ZRTPSess differs\n"); CU_PASS("ZRTPSess mismatch"); } /* compute the sas according to rfc section 4.5.2 sashash = KDF(s0, "SAS", KDF_Context, 256) */ retval = bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"SAS", 3, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, /* this one too depends on selected hash */ 256/8, /* function gets L in bytes */ (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, alice_sasHash); retval = bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"SAS", 3, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, /* this one too depends on selected hash */ 256/8, /* function gets L in bytes */ (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, bob_sasHash); /* DEBUG compare sasHash */ if (memcmp(alice_sasHash, bob_sasHash, 32)==0) { bzrtp_message("Got the same SAS Hash\n"); CU_PASS("SAS Hash match"); } else { bzrtp_message("ERROR SAS Hash differs\n"); CU_PASS("SAS Hash mismatch"); } /* display SAS (we shall not do this now but after the confirm message exchanges) */ sasValue = ((uint32_t)alice_sasHash[0]<<24) | ((uint32_t)alice_sasHash[1]<<16) | ((uint32_t)alice_sasHash[2]<<8) | ((uint32_t)(alice_sasHash[3])); contextAlice->channelContext[0]->sasFunction(sasValue, sas, 5); bzrtp_message("Alice SAS is %.4s\n", sas); sasValue = ((uint32_t)bob_sasHash[0]<<24) | ((uint32_t)bob_sasHash[1]<<16) | ((uint32_t)bob_sasHash[2]<<8) | ((uint32_t)(bob_sasHash[3])); contextBob->channelContext[0]->sasFunction(sasValue, sas, 5); bzrtp_message("Bob SAS is %.4s\n", sas); /* now derive the other keys (mackeyi, mackeyr, zrtpkeyi and zrtpkeyr, srtpkeys and salt) */ contextAlice->channelContext[0]->mackeyi = (uint8_t *)malloc(contextAlice->channelContext[0]->hashLength*(sizeof(uint8_t))); contextAlice->channelContext[0]->mackeyr = (uint8_t *)malloc(contextAlice->channelContext[0]->hashLength*(sizeof(uint8_t))); contextAlice->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(contextAlice->channelContext[0]->cipherKeyLength*(sizeof(uint8_t))); contextAlice->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(contextAlice->channelContext[0]->cipherKeyLength*(sizeof(uint8_t))); contextBob->channelContext[0]->mackeyi = (uint8_t *)malloc(contextBob->channelContext[0]->hashLength*(sizeof(uint8_t))); contextBob->channelContext[0]->mackeyr = (uint8_t *)malloc(contextBob->channelContext[0]->hashLength*(sizeof(uint8_t))); contextBob->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(contextBob->channelContext[0]->cipherKeyLength*(sizeof(uint8_t))); contextBob->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(contextBob->channelContext[0]->cipherKeyLength*(sizeof(uint8_t))); /* Alice */ retval = bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"Initiator HMAC key", 18, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, contextAlice->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, contextAlice->channelContext[0]->mackeyi); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"Responder HMAC key", 18, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, contextAlice->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, contextAlice->channelContext[0]->mackeyr); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"Initiator ZRTP key", 18, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, contextAlice->channelContext[0]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, contextAlice->channelContext[0]->zrtpkeyi); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"Responder ZRTP key", 18, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, contextAlice->channelContext[0]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, contextAlice->channelContext[0]->zrtpkeyr); /* Bob */ retval = bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"Initiator HMAC key", 18, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, contextBob->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, contextBob->channelContext[0]->mackeyi); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"Responder HMAC key", 18, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, contextBob->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, contextBob->channelContext[0]->mackeyr); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"Initiator ZRTP key", 18, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, contextBob->channelContext[0]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, contextBob->channelContext[0]->zrtpkeyi); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"Responder ZRTP key", 18, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, contextBob->channelContext[0]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, contextBob->channelContext[0]->zrtpkeyr); /* DEBUG compare keys */ if ((memcmp(contextAlice->channelContext[0]->mackeyi, contextBob->channelContext[0]->mackeyi, contextAlice->channelContext[0]->hashLength)==0) && (memcmp(contextAlice->channelContext[0]->mackeyr, contextBob->channelContext[0]->mackeyr, contextAlice->channelContext[0]->hashLength)==0) && (memcmp(contextAlice->channelContext[0]->zrtpkeyi, contextBob->channelContext[0]->zrtpkeyi, contextAlice->channelContext[0]->cipherKeyLength)==0) && (memcmp(contextAlice->channelContext[0]->zrtpkeyr, contextBob->channelContext[0]->zrtpkeyr, contextAlice->channelContext[0]->cipherKeyLength)==0)) { bzrtp_message("Got the same keys\n"); CU_PASS("keys match"); } else { bzrtp_message("ERROR keys differ\n"); CU_PASS("Keys mismatch"); } /* now Bob build the CONFIRM1 packet and send it to Alice */ bob_Confirm1 = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_CONFIRM1, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_Confirm1, contextBob->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[0]->selfSequenceNumber++; } bzrtp_message("Bob building Confirm1 return %x\n", retval); alice_Confirm1FromBob = bzrtp_packetCheck(bob_Confirm1->packetString, bob_Confirm1->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_Confirm1->packetString, bob_Confirm1->messageLength+16, alice_Confirm1FromBob); bzrtp_message ("Alice parsing confirm1 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextAlice->channelContext[0]->peerSequenceNumber = alice_Confirm1FromBob->sequenceNumber; alice_Confirm1FromBob_message = (bzrtpConfirmMessage_t *)alice_Confirm1FromBob->messageData; memcpy(contextAlice->channelContext[0]->peerH[0], alice_Confirm1FromBob_message->H0, 32); } packetDump(bob_Confirm1,1); packetDump(alice_Confirm1FromBob,0); bzrtp_freeZrtpPacket(alice_Confirm1FromBob); bzrtp_freeZrtpPacket(bob_Confirm1); /* now Alice build the CONFIRM2 packet and send it to Bob */ alice_Confirm2 = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[0], MSGTYPE_CONFIRM2, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[0], alice_Confirm2, contextAlice->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextAlice->channelContext[0]->selfSequenceNumber++; } bzrtp_message("Alice building Confirm2 return %x\n", retval); bob_Confirm2FromAlice = bzrtp_packetCheck(alice_Confirm2->packetString, alice_Confirm2->messageLength+16, contextBob->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[0], alice_Confirm2->packetString, alice_Confirm2->messageLength+16, bob_Confirm2FromAlice); bzrtp_message ("Bob parsing confirm2 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextBob->channelContext[0]->peerSequenceNumber = bob_Confirm2FromAlice->sequenceNumber; bob_Confirm2FromAlice_message = (bzrtpConfirmMessage_t *)bob_Confirm2FromAlice->messageData; memcpy(contextBob->channelContext[0]->peerH[0], bob_Confirm2FromAlice_message->H0, 32); /* set bob's status to secure */ contextBob->isSecure = 1; } packetDump(alice_Confirm2,1); packetDump(bob_Confirm2FromAlice,0); bzrtp_freeZrtpPacket(bob_Confirm2FromAlice); bzrtp_freeZrtpPacket(alice_Confirm2); /* Bob build the conf2Ack and send it to Alice */ bob_Conf2ACK = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_CONF2ACK, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_Conf2ACK, contextBob->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[0]->selfSequenceNumber++; } bzrtp_message("Bob building Conf2ACK return %x\n", retval); alice_Conf2ACKFromBob = bzrtp_packetCheck(bob_Conf2ACK->packetString, bob_Conf2ACK->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_Conf2ACK->packetString, bob_Conf2ACK->messageLength+16, alice_Conf2ACKFromBob); bzrtp_message ("Alice parsing conf2ACK returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextAlice->channelContext[0]->peerSequenceNumber = alice_Conf2ACKFromBob->sequenceNumber; /* set Alice's status to secure */ contextAlice->isSecure = 1; } bzrtp_freeZrtpPacket(bob_Conf2ACK); bzrtp_freeZrtpPacket(alice_Conf2ACKFromBob); dumpContext("Alice", contextAlice); dumpContext("Bob", contextBob); bzrtp_message("\n\n\n\n\n*************************************************************\n SECOND CHANNEL\n**********************************************\n\n"); /* Now create a second channel for Bob and Alice */ retval = bzrtp_addChannel(contextAlice, 0x45678901); bzrtp_message("Add channel to Alice's context returns %d\n", retval); retval = bzrtp_addChannel(contextBob, 0x54321098); bzrtp_message("Add channel to Bob's context returns %d\n", retval); /* create hello packets for this channel */ alice_Hello = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[1], MSGTYPE_HELLO, &retval); if (bzrtp_packetBuild(contextAlice, contextAlice->channelContext[1], alice_Hello, contextAlice->channelContext[1]->selfSequenceNumber) ==0) { contextAlice->channelContext[1]->selfSequenceNumber++; contextAlice->channelContext[1]->selfPackets[HELLO_MESSAGE_STORE_ID] = alice_Hello; } bob_Hello = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[1], MSGTYPE_HELLO, &retval); if (bzrtp_packetBuild(contextBob, contextBob->channelContext[1], bob_Hello, contextBob->channelContext[1]->selfSequenceNumber) ==0) { contextBob->channelContext[1]->selfSequenceNumber++; contextBob->channelContext[1]->selfPackets[HELLO_MESSAGE_STORE_ID] = bob_Hello; } /* now send Alice Hello's to Bob and vice-versa, so they parse them */ alice_HelloFromBob = bzrtp_packetCheck(bob_Hello->packetString, bob_Hello->messageLength+16, contextAlice->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_Hello->packetString, bob_Hello->messageLength+16, alice_HelloFromBob); bzrtp_message ("Alice parsing returns %x\n", retval); if (retval==0) { bzrtpHelloMessage_t *alice_HelloFromBob_message; int i; uint8_t checkPeerSupportMultiChannel = 0; contextAlice->channelContext[1]->peerSequenceNumber = alice_HelloFromBob->sequenceNumber; /* save bob's Hello packet in Alice's context */ contextAlice->channelContext[1]->peerPackets[HELLO_MESSAGE_STORE_ID] = alice_HelloFromBob; /* we are already secured (shall check isSecure==1), so we just need to check that peer Hello have the Mult in his key agreement list of supported algo */ alice_HelloFromBob_message = (bzrtpHelloMessage_t *)alice_HelloFromBob->messageData; for (i=0; i<alice_HelloFromBob_message->kc; i++) { if (alice_HelloFromBob_message->supportedKeyAgreement[i] == ZRTP_KEYAGREEMENT_Mult) { checkPeerSupportMultiChannel = 1; } } /* ok multi channel is supported*/ if (checkPeerSupportMultiChannel == 1) { bzrtp_message("Alice found that Bob supports multi channel\n"); /* now set the choosen algos, they MUST be the same than main channel (channel 0) except for keyAgreement which is set to mult */ contextAlice->channelContext[1]->hashAlgo = contextAlice->channelContext[0]->hashAlgo; contextAlice->channelContext[1]->hashLength = contextAlice->channelContext[0]->hashLength; contextAlice->channelContext[1]->cipherAlgo = contextAlice->channelContext[0]->cipherAlgo; contextAlice->channelContext[1]->cipherKeyLength = contextAlice->channelContext[0]->cipherKeyLength; contextAlice->channelContext[1]->authTagAlgo = contextAlice->channelContext[0]->authTagAlgo; contextAlice->channelContext[1]->sasAlgo = contextAlice->channelContext[0]->sasAlgo; contextAlice->channelContext[1]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_Mult; contextAlice->channelContext[1]->keyAgreementLength = 0; /* no public values exchanged in Multi channel mode */ updateCryptoFunctionPointers(contextAlice->channelContext[1]); } else { bzrtp_message("ERROR : Alice found that Bob doesn't support multi channel\n"); } } bob_HelloFromAlice = bzrtp_packetCheck(alice_Hello->packetString, alice_Hello->messageLength+16, contextBob->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[1], alice_Hello->packetString, alice_Hello->messageLength+16, bob_HelloFromAlice); bzrtp_message ("Bob parsing returns %x\n", retval); if (retval==0) { bzrtpHelloMessage_t *bob_HelloFromAlice_message; int i; uint8_t checkPeerSupportMultiChannel = 0; contextBob->channelContext[1]->peerSequenceNumber = bob_HelloFromAlice->sequenceNumber; /* save alice's Hello packet in bob's context */ contextBob->channelContext[1]->peerPackets[HELLO_MESSAGE_STORE_ID] = bob_HelloFromAlice; /* we are already secured (shall check isSecure==1), so we just need to check that peer Hello have the Mult in his key agreement list of supported algo */ bob_HelloFromAlice_message = (bzrtpHelloMessage_t *)bob_HelloFromAlice->messageData; for (i=0; i<bob_HelloFromAlice_message->kc; i++) { if (bob_HelloFromAlice_message->supportedKeyAgreement[i] == ZRTP_KEYAGREEMENT_Mult) { checkPeerSupportMultiChannel = 1; } } /* ok multi channel is supported*/ if (checkPeerSupportMultiChannel == 1) { bzrtp_message("Bob found that Alice supports multi channel\n"); /* now set the choosen algos, they MUST be the same than main channel (channel 0) except for keyAgreement which is set to mult */ contextBob->channelContext[1]->hashAlgo = contextBob->channelContext[0]->hashAlgo; contextBob->channelContext[1]->hashLength = contextBob->channelContext[0]->hashLength; contextBob->channelContext[1]->cipherAlgo = contextBob->channelContext[0]->cipherAlgo; contextBob->channelContext[1]->cipherKeyLength = contextBob->channelContext[0]->cipherKeyLength; contextBob->channelContext[1]->authTagAlgo = contextBob->channelContext[0]->authTagAlgo; contextBob->channelContext[1]->sasAlgo = contextBob->channelContext[0]->sasAlgo; contextBob->channelContext[1]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_Mult; contextBob->channelContext[1]->keyAgreementLength = 0; /* no public values exchanged in Multi channel mode */ updateCryptoFunctionPointers(contextBob->channelContext[1]); } else { bzrtp_message("ERROR : Bob found that Alice doesn't support multi channel\n"); } } /* update context with hello message information : H3 and compute initiator and responder's shared secret Hashs */ alice_HelloFromBob_message = (bzrtpHelloMessage_t *)alice_HelloFromBob->messageData; memcpy(contextAlice->channelContext[1]->peerH[3], alice_HelloFromBob_message->H3, 32); bob_HelloFromAlice_message = (bzrtpHelloMessage_t *)bob_HelloFromAlice->messageData; memcpy(contextBob->channelContext[1]->peerH[3], bob_HelloFromAlice_message->H3, 32); /* here we shall exchange Hello ACK but it is just a test and was done already for channel 0, skip it as it is useless for the test */ /* Bob will be the initiator, so compute a commit for him */ bob_Commit = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[1], MSGTYPE_COMMIT, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[1], bob_Commit, contextBob->channelContext[1]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[1]->selfSequenceNumber++; contextBob->channelContext[1]->selfPackets[COMMIT_MESSAGE_STORE_ID] = bob_Commit; } bzrtp_message("Bob building Commit return %x\n", retval); /* and send it to Alice */ alice_CommitFromBob = bzrtp_packetCheck(bob_Commit->packetString, bob_Commit->messageLength+16, contextAlice->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[1], bob_Commit->packetString, bob_Commit->messageLength+16, alice_CommitFromBob); bzrtp_message ("Alice parsing Commit returns %x\n", retval); if (retval==0) { bzrtpCommitMessage_t *alice_CommitFromBob_message; /* update context with the information found in the packet */ contextAlice->channelContext[1]->peerSequenceNumber = alice_CommitFromBob->sequenceNumber; /* Alice will be the initiator (commit contention not implemented in this test) so just discard bob's commit */ alice_CommitFromBob_message = (bzrtpCommitMessage_t *)alice_CommitFromBob->messageData; memcpy(contextAlice->channelContext[1]->peerH[2], alice_CommitFromBob_message->H2, 32); contextAlice->channelContext[1]->peerPackets[COMMIT_MESSAGE_STORE_ID] = alice_CommitFromBob; } packetDump(alice_CommitFromBob, 0); /* for test purpose define Alice as the responder */ contextAlice->channelContext[1]->role = RESPONDER; /* compute the total hash as in rfc section 4.4.3.2 total_hash = hash(Hello of responder || Commit) */ totalHashDataLength = alice_Hello->messageLength + bob_Commit->messageLength; dataToHash = (uint8_t *)malloc(totalHashDataLength*sizeof(uint8_t)); hashDataIndex = 0; /* get all data from Alice */ memcpy(dataToHash, contextAlice->channelContext[1]->selfPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[1]->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextAlice->channelContext[1]->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextAlice->channelContext[1]->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[1]->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength); contextAlice->channelContext[1]->hashFunction(dataToHash, totalHashDataLength, 32, alice_totalHash); /* get all data from Bob */ hashDataIndex = 0; memcpy(dataToHash, contextBob->channelContext[1]->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[1]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextBob->channelContext[1]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextBob->channelContext[1]->selfPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[1]->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageLength); contextBob->channelContext[1]->hashFunction(dataToHash, totalHashDataLength, 32, bob_totalHash); if (memcmp(bob_totalHash, alice_totalHash, 32) == 0) { bzrtp_message("Got the same total hash\n"); CU_PASS("Total Hash match"); } else { bzrtp_message("AARGG!! total hash mismatch"); CU_FAIL("Total Hash mismatch"); } free(dataToHash); /* compute the KDF Context as in rfc section 4.4.3.2 KDF_Context = (ZIDi || ZIDr || total_hash) */ contextAlice->channelContext[1]->KDFContextLength = 24 + contextAlice->channelContext[1]->hashLength; contextAlice->channelContext[1]->KDFContext = (uint8_t *)malloc(contextAlice->channelContext[1]->KDFContextLength*sizeof(uint8_t)); memcpy(contextAlice->channelContext[1]->KDFContext, contextAlice->peerZID, 12); memcpy(contextAlice->channelContext[1]->KDFContext+12, contextAlice->selfZID, 12); memcpy(contextAlice->channelContext[1]->KDFContext+24, alice_totalHash, contextAlice->channelContext[1]->hashLength); contextBob->channelContext[1]->KDFContextLength = 24 + contextBob->channelContext[1]->hashLength; contextBob->channelContext[1]->KDFContext = (uint8_t *)malloc(contextBob->channelContext[1]->KDFContextLength*sizeof(uint8_t)); memcpy(contextBob->channelContext[1]->KDFContext, contextBob->selfZID, 12); memcpy(contextBob->channelContext[1]->KDFContext+12, contextBob->peerZID, 12); memcpy(contextBob->channelContext[1]->KDFContext+24, bob_totalHash, contextBob->channelContext[1]->hashLength); if (memcmp(contextBob->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContext, 56) == 0) { bzrtp_message("Got the same total KDF Context\n"); CU_PASS("KDFContext match"); } else { bzrtp_message("AARGG!! KDF Context mismatch"); CU_FAIL("KDF Context mismatch"); } /* compute s0 as in rfc section 4.4.3.2 s0 = KDF(ZRTPSess, "ZRTP MSK", KDF_Context, negotiated hash length) */ contextBob->channelContext[1]->s0 = (uint8_t *)malloc(contextBob->channelContext[1]->hashLength*sizeof(uint8_t)); contextAlice->channelContext[1]->s0 = (uint8_t *)malloc(contextAlice->channelContext[1]->hashLength*sizeof(uint8_t)); retval = bzrtp_keyDerivationFunction(contextBob->ZRTPSess, contextBob->ZRTPSessLength, (uint8_t *)"ZRTP MSK", 8, contextBob->channelContext[1]->KDFContext, contextBob->channelContext[1]->KDFContextLength, /* this one too depends on selected hash */ contextBob->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[1]->hmacFunction, contextBob->channelContext[1]->s0); retval = bzrtp_keyDerivationFunction(contextAlice->ZRTPSess, contextAlice->ZRTPSessLength, (uint8_t *)"ZRTP MSK", 8, contextAlice->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContextLength, /* this one too depends on selected hash */ contextAlice->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[1]->hmacFunction, contextAlice->channelContext[1]->s0); if (memcmp(contextBob->channelContext[1]->s0, contextAlice->channelContext[1]->s0, contextAlice->channelContext[1]->hashLength) == 0) { bzrtp_message("Got the same s0\n"); CU_PASS("s0 match"); } else { bzrtp_message("AARGG!! s0 mismatch"); CU_FAIL("s0 mismatch"); } /* the rest of key derivation is common to DH mode, no need to test it as it has been done before for channel 0 */ /* we must anyway derive zrtp and mac key for initiator and responder in order to be able to build the confirm packets */ contextAlice->channelContext[1]->mackeyi = (uint8_t *)malloc(contextAlice->channelContext[1]->hashLength*(sizeof(uint8_t))); contextAlice->channelContext[1]->mackeyr = (uint8_t *)malloc(contextAlice->channelContext[1]->hashLength*(sizeof(uint8_t))); contextAlice->channelContext[1]->zrtpkeyi = (uint8_t *)malloc(contextAlice->channelContext[1]->cipherKeyLength*(sizeof(uint8_t))); contextAlice->channelContext[1]->zrtpkeyr = (uint8_t *)malloc(contextAlice->channelContext[1]->cipherKeyLength*(sizeof(uint8_t))); contextBob->channelContext[1]->mackeyi = (uint8_t *)malloc(contextBob->channelContext[1]->hashLength*(sizeof(uint8_t))); contextBob->channelContext[1]->mackeyr = (uint8_t *)malloc(contextBob->channelContext[1]->hashLength*(sizeof(uint8_t))); contextBob->channelContext[1]->zrtpkeyi = (uint8_t *)malloc(contextBob->channelContext[1]->cipherKeyLength*(sizeof(uint8_t))); contextBob->channelContext[1]->zrtpkeyr = (uint8_t *)malloc(contextBob->channelContext[1]->cipherKeyLength*(sizeof(uint8_t))); /* Alice */ retval = bzrtp_keyDerivationFunction(contextAlice->channelContext[1]->s0, contextAlice->channelContext[1]->hashLength, (uint8_t *)"Initiator HMAC key", 18, contextAlice->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContextLength, contextAlice->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[1]->hmacFunction, contextAlice->channelContext[1]->mackeyi); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[1]->s0, contextAlice->channelContext[1]->hashLength, (uint8_t *)"Responder HMAC key", 18, contextAlice->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContextLength, contextAlice->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[1]->hmacFunction, contextAlice->channelContext[1]->mackeyr); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[1]->s0, contextAlice->channelContext[1]->hashLength, (uint8_t *)"Initiator ZRTP key", 18, contextAlice->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContextLength, contextAlice->channelContext[1]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[1]->hmacFunction, contextAlice->channelContext[1]->zrtpkeyi); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[1]->s0, contextAlice->channelContext[1]->hashLength, (uint8_t *)"Responder ZRTP key", 18, contextAlice->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContextLength, contextAlice->channelContext[1]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[1]->hmacFunction, contextAlice->channelContext[1]->zrtpkeyr); /* Bob */ retval = bzrtp_keyDerivationFunction(contextBob->channelContext[1]->s0, contextBob->channelContext[1]->hashLength, (uint8_t *)"Initiator HMAC key", 18, contextBob->channelContext[1]->KDFContext, contextBob->channelContext[1]->KDFContextLength, contextBob->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[1]->hmacFunction, contextBob->channelContext[1]->mackeyi); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[1]->s0, contextBob->channelContext[1]->hashLength, (uint8_t *)"Responder HMAC key", 18, contextBob->channelContext[1]->KDFContext, contextBob->channelContext[1]->KDFContextLength, contextBob->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[1]->hmacFunction, contextBob->channelContext[1]->mackeyr); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[1]->s0, contextBob->channelContext[1]->hashLength, (uint8_t *)"Initiator ZRTP key", 18, contextBob->channelContext[1]->KDFContext, contextBob->channelContext[1]->KDFContextLength, contextBob->channelContext[1]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[1]->hmacFunction, contextBob->channelContext[1]->zrtpkeyi); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[1]->s0, contextBob->channelContext[1]->hashLength, (uint8_t *)"Responder ZRTP key", 18, contextBob->channelContext[1]->KDFContext, contextBob->channelContext[1]->KDFContextLength, contextBob->channelContext[1]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[1]->hmacFunction, contextBob->channelContext[1]->zrtpkeyr); /* DEBUG compare keys */ if ((memcmp(contextAlice->channelContext[1]->mackeyi, contextBob->channelContext[1]->mackeyi, contextAlice->channelContext[1]->hashLength)==0) && (memcmp(contextAlice->channelContext[1]->mackeyr, contextBob->channelContext[1]->mackeyr, contextAlice->channelContext[1]->hashLength)==0) && (memcmp(contextAlice->channelContext[1]->zrtpkeyi, contextBob->channelContext[1]->zrtpkeyi, contextAlice->channelContext[1]->cipherKeyLength)==0) && (memcmp(contextAlice->channelContext[1]->zrtpkeyr, contextBob->channelContext[1]->zrtpkeyr, contextAlice->channelContext[1]->cipherKeyLength)==0)) { bzrtp_message("Got the same keys\n"); CU_PASS("keys match"); } else { bzrtp_message("ERROR keys differ\n"); CU_PASS("Keys mismatch"); } /* now Alice build a confirm1 packet */ alice_Confirm1 = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[1], MSGTYPE_CONFIRM1, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[1], alice_Confirm1, contextAlice->channelContext[1]->selfSequenceNumber); if (retval == 0) { contextAlice->channelContext[1]->selfSequenceNumber++; } bzrtp_message("Alice building Confirm1 return %x\n", retval); bob_Confirm1FromAlice = bzrtp_packetCheck(alice_Confirm1->packetString, alice_Confirm1->messageLength+16, contextBob->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[1], alice_Confirm1->packetString, alice_Confirm1->messageLength+16, bob_Confirm1FromAlice); bzrtp_message ("Bob parsing confirm1 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextBob->channelContext[1]->peerSequenceNumber = bob_Confirm1FromAlice->sequenceNumber; bob_Confirm1FromAlice_message = (bzrtpConfirmMessage_t *)bob_Confirm1FromAlice->messageData; memcpy(contextBob->channelContext[1]->peerH[0], bob_Confirm1FromAlice_message->H0, 32); } packetDump(bob_Confirm1FromAlice,0); bzrtp_freeZrtpPacket(bob_Confirm1FromAlice); bzrtp_freeZrtpPacket(alice_Confirm1); /* now Bob build the CONFIRM2 packet and send it to Alice */ bob_Confirm2 = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[1], MSGTYPE_CONFIRM2, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[1], bob_Confirm2, contextBob->channelContext[1]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[1]->selfSequenceNumber++; } bzrtp_message("Bob building Confirm2 return %x\n", retval); alice_Confirm2FromBob = bzrtp_packetCheck(bob_Confirm2->packetString, bob_Confirm2->messageLength+16, contextAlice->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[1], bob_Confirm2->packetString, bob_Confirm2->messageLength+16, alice_Confirm2FromBob); bzrtp_message ("Alice parsing confirm2 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextAlice->channelContext[1]->peerSequenceNumber = alice_Confirm2FromBob->sequenceNumber; alice_Confirm2FromBob_message = (bzrtpConfirmMessage_t *)alice_Confirm2FromBob->messageData; memcpy(contextAlice->channelContext[1]->peerH[0], alice_Confirm2FromBob_message->H0, 32); } packetDump(alice_Confirm2FromBob,0); bzrtp_freeZrtpPacket(alice_Confirm2FromBob); bzrtp_freeZrtpPacket(bob_Confirm2); /* Alice build the conf2Ack and send it to Bob */ alice_Conf2ACK = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[1], MSGTYPE_CONF2ACK, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[1], alice_Conf2ACK, contextAlice->channelContext[1]->selfSequenceNumber); if (retval == 0) { contextAlice->channelContext[1]->selfSequenceNumber++; } bzrtp_message("Alice building Conf2ACK return %x\n", retval); bob_Conf2ACKFromAlice = bzrtp_packetCheck(alice_Conf2ACK->packetString, alice_Conf2ACK->messageLength+16, contextBob->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[1], alice_Conf2ACK->packetString, alice_Conf2ACK->messageLength+16, bob_Conf2ACKFromAlice); bzrtp_message ("Bob parsing conf2ACK returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextBob->channelContext[1]->peerSequenceNumber = bob_Conf2ACKFromAlice->sequenceNumber; } bzrtp_freeZrtpPacket(alice_Conf2ACK); bzrtp_freeZrtpPacket(bob_Conf2ACKFromAlice); /* dumpContext("\nAlice", contextAlice); dumpContext("\nBob", contextBob); */ bzrtp_message("Destroy the contexts\n"); /* destroy the context */ bzrtp_destroyBzrtpContext(contextAlice, 0x45678901); bzrtp_destroyBzrtpContext(contextBob, 0x54321098); bzrtp_message("Destroy the contexts last channel\n"); bzrtp_destroyBzrtpContext(contextBob, 0x87654321); bzrtp_destroyBzrtpContext(contextAlice, 0x12345678); } typedef struct packetDatas_struct { uint8_t packetString[1000]; uint16_t packetLength; } packetDatas_t; /* Alice and Bob packet queues are globals */ packetDatas_t aliceQueue[10]; packetDatas_t bobQueue[10]; uint8_t aliceQueueIndex = 0; uint8_t bobQueueIndex = 0; uint8_t block_Hello = 0; /* this is a callback function for send data, just dump the packet */ /* client Data is a my_Context_t structure */ int bzrtp_sendData(void *clientData, const uint8_t *packetString, uint16_t packetLength) { /* get the client Data */ my_Context_t *contexts = (my_Context_t *)clientData; /* bzrtp_message ("%s sends a message!\n", contexts->nom); int retval; bzrtpPacket_t *zrtpPacket = bzrtp_packetCheck(packetString, packetLength, contexts->peerChannelContext->peerSequenceNumber, &retval); if (retval==0) { retval = bzrtp_packetParser(contexts->peerContext, contexts->peerChannelContext, packetString, packetLength, zrtpPacket); if (retval == 0) { */ /* packetDump(zrtpPacket,0); */ /* printHex("Data", packetString, packetLength);*/ /* } else { bzrtp_message("Parse says %04x\n", retval); } } else { bzrtp_message("Check says %04x\n", retval); } */ /* put the message in the message queue */ if (contexts->nom[0] == 'A') { /* message sent by Alice, put it in Bob's queue */ /* block the first Hello to force going through wait for hello state and check it is retransmitted */ /* if ((block_Hello == 0) && (zrtpPacket->messageType == MSGTYPE_HELLO)) { block_Hello = 1; } else {*/ memcpy(bobQueue[bobQueueIndex].packetString, packetString, packetLength); bobQueue[bobQueueIndex++].packetLength = packetLength; /* }*/ } else { memcpy(aliceQueue[aliceQueueIndex].packetString, packetString, packetLength); aliceQueue[aliceQueueIndex++].packetLength = packetLength; } /* bzrtp_freeZrtpPacket(zrtpPacket); */ return 0; } uint64_t myCurrentTime = 0; /* we do not need a real time, start at 0 and increment it at each sleep */ uint64_t getCurrentTimeInMs() { return myCurrentTime; } static void sleepMs(int ms){ #ifdef _WIN32 Sleep(ms); #else struct timespec ts; ts.tv_sec=0; ts.tv_nsec=ms*1000000LL; nanosleep(&ts,NULL); #endif myCurrentTime +=ms; } /* Ping message length is 24 bytes (already define in packetParser.c out of this scope) */ #define ZRTP_PINGMESSAGE_FIXED_LENGTH 24 void test_stateMachine() { int retval; my_Context_t aliceClientData, bobClientData; uint64_t initialTime; uint8_t pingPacketString[ZRTP_PACKET_OVERHEAD+ZRTP_PINGMESSAGE_FIXED_LENGTH]; /* there is no builder for ping packet and it is 24 bytes long(12 bytes of message header, 12 of data + packet overhead*/ uint32_t CRC; uint8_t *CRCbuffer; my_Context_t aliceSecondChannelClientData, bobSecondChannelClientData; bzrtpCallbacks_t cbs={0} ; /* Create zrtp Context */ bzrtpContext_t *contextAlice = bzrtp_createBzrtpContext(0x12345678); /* Alice's SSRC of main channel is 12345678 */ bzrtpContext_t *contextBob = bzrtp_createBzrtpContext(0x87654321); /* Bob's SSRC of main channel is 87654321 */ /* set the cache related callback functions */ cbs.bzrtp_loadCache=floadAlice; cbs.bzrtp_writeCache=fwriteAlice; cbs.bzrtp_sendData=bzrtp_sendData; bzrtp_setCallbacks(contextAlice, &cbs); cbs.bzrtp_loadCache=floadBob; cbs.bzrtp_writeCache=fwriteBob; cbs.bzrtp_sendData=bzrtp_sendData; bzrtp_setCallbacks(contextBob, &cbs); /* create the client Data and associate them to the channel contexts */ memcpy(aliceClientData.nom, "Alice", 6); memcpy(bobClientData.nom, "Bob", 4); aliceClientData.peerContext = contextBob; aliceClientData.peerChannelContext = contextBob->channelContext[0]; bobClientData.peerContext = contextAlice; bobClientData.peerChannelContext = contextAlice->channelContext[0]; strcpy(aliceClientData.zidFilename, "./ZIDAlice.txt"); strcpy(bobClientData.zidFilename, "./ZIDBob.txt"); retval = bzrtp_setClientData(contextAlice, 0x12345678, (void *)&aliceClientData); retval += bzrtp_setClientData(contextBob, 0x87654321, (void *)&bobClientData); bzrtp_message("Set client data return %x\n", retval); /* run the init */ bzrtp_initBzrtpContext(contextAlice); bzrtp_initBzrtpContext(contextBob); /* now start the engine */ initialTime = getCurrentTimeInMs(); retval = bzrtp_startChannelEngine(contextAlice, 0x12345678); bzrtp_message ("Alice starts return %x\n", retval); retval = bzrtp_startChannelEngine(contextBob, 0x87654321); bzrtp_message ("Bob starts return %x\n", retval); /* now start infinite loop until we reach secure state */ while ((contextAlice->isSecure == 0 || contextBob->isSecure == 0) && (getCurrentTimeInMs()-initialTime<5000)){ int i; /* first check the message queue */ for (i=0; i<aliceQueueIndex; i++) { bzrtp_message("Process a message for Alice\n"); retval = bzrtp_processMessage(contextAlice, 0x12345678, aliceQueue[i].packetString, aliceQueue[i].packetLength); bzrtp_message("Alice processed message %.8s of %d bytes and return %04x\n\n", aliceQueue[i].packetString+16, aliceQueue[i].packetLength, retval); memset(aliceQueue[i].packetString, 0, 1000); /* destroy the packet after sending it to the ZRTP engine */ } aliceQueueIndex = 0; for (i=0; i<bobQueueIndex; i++) { bzrtp_message("Process a message for Bob\n"); retval = bzrtp_processMessage(contextBob, 0x87654321, bobQueue[i].packetString, bobQueue[i].packetLength); bzrtp_message("Bob processed message %.8s of %d bytes and return %04x\n\n", bobQueue[i].packetString+16, bobQueue[i].packetLength, retval); memset(bobQueue[i].packetString, 0, 1000); /* destroy the packet after sending it to the ZRTP engine */ } bobQueueIndex = 0; /* send the actual time to the zrtpContext */ bzrtp_iterate(contextAlice, 0x12345678, getCurrentTimeInMs()); bzrtp_iterate(contextBob, 0x87654321, getCurrentTimeInMs()); /* sleep for 10 ms */ sleepMs(10); } /* compare SAS and check we are in secure mode */ if ((contextAlice->isSecure == 1) && (contextBob->isSecure == 1)) { /* don't compare sas if we're not secure at we may not have it */ CU_ASSERT_TRUE((memcmp(contextAlice->channelContext[0]->srtpSecrets.sas, contextBob->channelContext[0]->srtpSecrets.sas, 4) == 0)); /* call the set verified Sas function */ bzrtp_SASVerified(contextAlice); bzrtp_SASVerified(contextBob); } else { CU_FAIL("Unable to reach secure state"); } /*** Send alice a ping message from Bob ***/ /* set packet header and CRC */ /* preambule */ pingPacketString[0] = 0x10; pingPacketString[1] = 0x00; /* Sequence number */ pingPacketString[2] = (uint8_t)((contextBob->channelContext[0]->selfSequenceNumber>>8)&0x00FF); pingPacketString[3] = (uint8_t)(contextBob->channelContext[0]->selfSequenceNumber&0x00FF); /* ZRTP magic cookie */ pingPacketString[4] = (uint8_t)((ZRTP_MAGIC_COOKIE>>24)&0xFF); pingPacketString[5] = (uint8_t)((ZRTP_MAGIC_COOKIE>>16)&0xFF); pingPacketString[6] = (uint8_t)((ZRTP_MAGIC_COOKIE>>8)&0xFF); pingPacketString[7] = (uint8_t)(ZRTP_MAGIC_COOKIE&0xFF); /* Source Identifier : insert bob's one: 0x87654321 */ pingPacketString[8] = 0x87; pingPacketString[9] = 0x65; pingPacketString[10] = 0x43; pingPacketString[11] = 0x21; /* message header */ pingPacketString[12] = 0x50; pingPacketString[13] = 0x5a; /* length in 32 bits words */ pingPacketString[14] = 0x00; pingPacketString[15] = 0x06; /* message type "Ping " */ memcpy(pingPacketString+16, "Ping ",8); /* Version on 4 bytes is "1.10" */ memcpy(pingPacketString+24, "1.10", 4); /* a endPointHash, use the first 8 bytes of Bob's ZID */ memcpy(pingPacketString+28, contextBob->selfZID, 8); /* CRC */ CRC = bzrtp_CRC32(pingPacketString, ZRTP_PINGMESSAGE_FIXED_LENGTH+ZRTP_PACKET_HEADER_LENGTH); CRCbuffer = pingPacketString+ZRTP_PINGMESSAGE_FIXED_LENGTH+ZRTP_PACKET_HEADER_LENGTH; *CRCbuffer = (uint8_t)((CRC>>24)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>16)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>8)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)(CRC&0xFF); bzrtp_message("Process a PING message for Alice\n"); retval = bzrtp_processMessage(contextAlice, 0x12345678, pingPacketString, ZRTP_PACKET_OVERHEAD+ZRTP_PINGMESSAGE_FIXED_LENGTH); bzrtp_message("Alice processed PING message and return %04x\n\n", retval); /*** now add a second channel ***/ retval = bzrtp_addChannel(contextAlice, 0x34567890); bzrtp_message("Add a channel to Alice context, return %x\n", retval); retval = bzrtp_addChannel(contextBob, 0x09876543); bzrtp_message("Add a channel to Bob context, return %x\n", retval); /* create the client Data and associate them to the channel contexts */ memcpy(aliceSecondChannelClientData.nom, "Alice", 6); memcpy(bobSecondChannelClientData.nom, "Bob", 4); aliceSecondChannelClientData.peerContext = contextBob; aliceSecondChannelClientData.peerChannelContext = contextBob->channelContext[1]; bobSecondChannelClientData.peerContext = contextAlice; bobSecondChannelClientData.peerChannelContext = contextAlice->channelContext[1]; retval = bzrtp_setClientData(contextAlice, 0x34567890, (void *)&aliceSecondChannelClientData); retval += bzrtp_setClientData(contextBob, 0x09876543, (void *)&bobSecondChannelClientData); bzrtp_message("Set client data return %x\n", retval); /* start the channels */ retval = bzrtp_startChannelEngine(contextAlice, 0x34567890); bzrtp_message ("Alice starts return %x\n", retval); retval = bzrtp_startChannelEngine(contextBob, 0x09876543); bzrtp_message ("Bob starts return %x\n", retval); /* now start infinite loop until we reach secure state */ while ((getCurrentTimeInMs()-initialTime<2000)){ int i; /* first check the message queue */ for (i=0; i<aliceQueueIndex; i++) { bzrtp_message("Process a message for Alice\n"); retval = bzrtp_processMessage(contextAlice, 0x34567890, aliceQueue[i].packetString, aliceQueue[i].packetLength); bzrtp_message("Alice processed message %.8s of %d bytes and return %04x\n\n", aliceQueue[i].packetString+16, aliceQueue[i].packetLength, retval); memset(aliceQueue[i].packetString, 0, 1000); /* destroy the packet after sending it to the ZRTP engine */ } aliceQueueIndex = 0; for (i=0; i<bobQueueIndex; i++) { bzrtp_message("Process a message for Bob\n"); retval = bzrtp_processMessage(contextBob, 0x09876543, bobQueue[i].packetString, bobQueue[i].packetLength); bzrtp_message("Bob processed message %.8s of %d bytes and return %04x\n\n", bobQueue[i].packetString+16, bobQueue[i].packetLength, retval); memset(bobQueue[i].packetString, 0, 1000); /* destroy the packet after sending it to the ZRTP engine */ } bobQueueIndex = 0; /* send the actual time to the zrtpContext */ bzrtp_iterate(contextAlice, 0x34567890, getCurrentTimeInMs()); bzrtp_iterate(contextBob, 0x09876543, getCurrentTimeInMs()); /* sleep for 10 ms */ sleepMs(10); } CU_ASSERT_TRUE((memcmp(contextAlice->channelContext[1]->srtpSecrets.selfSrtpKey, contextBob->channelContext[1]->srtpSecrets.peerSrtpKey, 16) == 0) && (contextAlice->isSecure == 1) && (contextBob->isSecure == 1)); dumpContext("\nAlice", contextAlice); dumpContext("\nBob", contextBob); bzrtp_message("Destroy the contexts\n"); /* destroy the context */ bzrtp_destroyBzrtpContext(contextAlice, 0x34567890); bzrtp_destroyBzrtpContext(contextBob, 0x09876543); bzrtp_message("Destroy the contexts last channel\n"); bzrtp_destroyBzrtpContext(contextBob, 0x87654321); bzrtp_destroyBzrtpContext(contextAlice, 0x12345678); }
./CrossVul/dataset_final_sorted/CWE-254/c/bad_5205_2
crossvul-cpp_data_bad_4886_0
/* * libvirt-domain.c: entry points for virDomainPtr APIs * * Copyright (C) 2006-2015 Red Hat, Inc. * * 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, see * <http://www.gnu.org/licenses/>. */ #include <config.h> #include <sys/stat.h> #include "intprops.h" #include "datatypes.h" #include "viralloc.h" #include "virfile.h" #include "virlog.h" #include "virtypedparam.h" VIR_LOG_INIT("libvirt.domain"); #define VIR_FROM_THIS VIR_FROM_DOMAIN /** * virConnectListDomains: * @conn: pointer to the hypervisor connection * @ids: array to collect the list of IDs of active domains * @maxids: size of @ids * * Collect the list of active domains, and store their IDs in array @ids * * For inactive domains, see virConnectListDefinedDomains(). For more * control over the results, see virConnectListAllDomains(). * * Returns the number of domains found or -1 in case of error. Note that * this command is inherently racy; a domain can be started between a * call to virConnectNumOfDomains() and this call; you are only guaranteed * that all currently active domains were listed if the return is less * than @maxids. */ int virConnectListDomains(virConnectPtr conn, int *ids, int maxids) { VIR_DEBUG("conn=%p, ids=%p, maxids=%d", conn, ids, maxids); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNullArgGoto(ids, error); virCheckNonNegativeArgGoto(maxids, error); if (conn->driver->connectListDomains) { int ret = conn->driver->connectListDomains(conn, ids, maxids); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectNumOfDomains: * @conn: pointer to the hypervisor connection * * Provides the number of active domains. * * Returns the number of domain found or -1 in case of error */ int virConnectNumOfDomains(virConnectPtr conn) { VIR_DEBUG("conn=%p", conn); virResetLastError(); virCheckConnectReturn(conn, -1); if (conn->driver->connectNumOfDomains) { int ret = conn->driver->connectNumOfDomains(conn); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainGetConnect: * @dom: pointer to a domain * * Provides the connection pointer associated with a domain. The * reference counter on the connection is not increased by this * call. * * WARNING: When writing libvirt bindings in other languages, do * not use this function. Instead, store the connection and * the domain object together. * * Returns the virConnectPtr or NULL in case of failure. */ virConnectPtr virDomainGetConnect(virDomainPtr dom) { VIR_DOMAIN_DEBUG(dom); virResetLastError(); virCheckDomainReturn(dom, NULL); return dom->conn; } /** * virDomainCreateXML: * @conn: pointer to the hypervisor connection * @xmlDesc: string containing an XML description of the domain * @flags: bitwise-OR of supported virDomainCreateFlags * * Launch a new guest domain, based on an XML description similar * to the one returned by virDomainGetXMLDesc() * This function may require privileged access to the hypervisor. * The domain is not persistent, so its definition will disappear when it * is destroyed, or if the host is restarted (see virDomainDefineXML() to * define persistent domains). * * If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain * will be started, but its CPUs will remain paused. The CPUs * can later be manually started using virDomainResume. * * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest * domain will be automatically destroyed when the virConnectPtr * object is finally released. This will also happen if the * client application crashes / loses its connection to the * libvirtd daemon. Any domains marked for auto destroy will * block attempts at migration, save-to-file, or snapshots. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure */ virDomainPtr virDomainCreateXML(virConnectPtr conn, const char *xmlDesc, unsigned int flags) { VIR_DEBUG("conn=%p, xmlDesc=%s, flags=%x", conn, NULLSTR(xmlDesc), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(xmlDesc, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainCreateXML) { virDomainPtr ret; ret = conn->driver->domainCreateXML(conn, xmlDesc, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainCreateXMLWithFiles: * @conn: pointer to the hypervisor connection * @xmlDesc: string containing an XML description of the domain * @nfiles: number of file descriptors passed * @files: list of file descriptors passed * @flags: bitwise-OR of supported virDomainCreateFlags * * Launch a new guest domain, based on an XML description similar * to the one returned by virDomainGetXMLDesc() * This function may require privileged access to the hypervisor. * The domain is not persistent, so its definition will disappear when it * is destroyed, or if the host is restarted (see virDomainDefineXML() to * define persistent domains). * * @files provides an array of file descriptors which will be * made available to the 'init' process of the guest. The file * handles exposed to the guest will be renumbered to start * from 3 (ie immediately following stderr). This is only * supported for guests which use container based virtualization * technology. * * If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain * will be started, but its CPUs will remain paused. The CPUs * can later be manually started using virDomainResume. * * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest * domain will be automatically destroyed when the virConnectPtr * object is finally released. This will also happen if the * client application crashes / loses its connection to the * libvirtd daemon. Any domains marked for auto destroy will * block attempts at migration, save-to-file, or snapshots. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure */ virDomainPtr virDomainCreateXMLWithFiles(virConnectPtr conn, const char *xmlDesc, unsigned int nfiles, int *files, unsigned int flags) { VIR_DEBUG("conn=%p, xmlDesc=%s, nfiles=%u, files=%p, flags=%x", conn, NULLSTR(xmlDesc), nfiles, files, flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(xmlDesc, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainCreateXMLWithFiles) { virDomainPtr ret; ret = conn->driver->domainCreateXMLWithFiles(conn, xmlDesc, nfiles, files, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainCreateLinux: * @conn: pointer to the hypervisor connection * @xmlDesc: string containing an XML description of the domain * @flags: extra flags; not used yet, so callers should always pass 0 * * Deprecated after 0.4.6. * Renamed to virDomainCreateXML() providing identical functionality. * This existing name will be left indefinitely for API compatibility. * * Returns a new domain object or NULL in case of failure */ virDomainPtr virDomainCreateLinux(virConnectPtr conn, const char *xmlDesc, unsigned int flags) { return virDomainCreateXML(conn, xmlDesc, flags); } /** * virDomainLookupByID: * @conn: pointer to the hypervisor connection * @id: the domain ID number * * Try to find a domain based on the hypervisor ID number * Note that this won't work for inactive domains which have an ID of -1, * in that case a lookup based on the Name or UUId need to be done instead. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure. If the * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised. */ virDomainPtr virDomainLookupByID(virConnectPtr conn, int id) { VIR_DEBUG("conn=%p, id=%d", conn, id); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNegativeArgGoto(id, error); if (conn->driver->domainLookupByID) { virDomainPtr ret; ret = conn->driver->domainLookupByID(conn, id); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainLookupByUUID: * @conn: pointer to the hypervisor connection * @uuid: the raw UUID for the domain * * Try to lookup a domain on the given hypervisor based on its UUID. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure. If the * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised. */ virDomainPtr virDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid) { VIR_UUID_DEBUG(conn, uuid); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(uuid, error); if (conn->driver->domainLookupByUUID) { virDomainPtr ret; ret = conn->driver->domainLookupByUUID(conn, uuid); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainLookupByUUIDString: * @conn: pointer to the hypervisor connection * @uuidstr: the string UUID for the domain * * Try to lookup a domain on the given hypervisor based on its UUID. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure. If the * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised. */ virDomainPtr virDomainLookupByUUIDString(virConnectPtr conn, const char *uuidstr) { unsigned char uuid[VIR_UUID_BUFLEN]; VIR_DEBUG("conn=%p, uuidstr=%s", conn, NULLSTR(uuidstr)); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(uuidstr, error); if (virUUIDParse(uuidstr, uuid) < 0) { virReportInvalidArg(uuidstr, "%s", _("Invalid UUID")); goto error; } return virDomainLookupByUUID(conn, &uuid[0]); error: virDispatchError(conn); return NULL; } /** * virDomainLookupByName: * @conn: pointer to the hypervisor connection * @name: name for the domain * * Try to lookup a domain on the given hypervisor based on its name. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure. If the * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised. */ virDomainPtr virDomainLookupByName(virConnectPtr conn, const char *name) { VIR_DEBUG("conn=%p, name=%s", conn, NULLSTR(name)); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(name, error); if (conn->driver->domainLookupByName) { virDomainPtr dom; dom = conn->driver->domainLookupByName(conn, name); if (!dom) goto error; return dom; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainDestroy: * @domain: a domain object * * Destroy the domain object. The running instance is shutdown if not down * already and all resources used by it are given back to the hypervisor. This * does not free the associated virDomainPtr object. * This function may require privileged access. * * virDomainDestroy first requests that a guest terminate * (e.g. SIGTERM), then waits for it to comply. After a reasonable * timeout, if the guest still exists, virDomainDestroy will * forcefully terminate the guest (e.g. SIGKILL) if necessary (which * may produce undesirable results, for example unflushed disk cache * in the guest). To avoid this possibility, it's recommended to * instead call virDomainDestroyFlags, sending the * VIR_DOMAIN_DESTROY_GRACEFUL flag. * * If the domain is transient and has any snapshot metadata (see * virDomainSnapshotNum()), then that metadata will automatically * be deleted when the domain quits. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainDestroy(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainDestroy) { int ret; ret = conn->driver->domainDestroy(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainDestroyFlags: * @domain: a domain object * @flags: bitwise-OR of virDomainDestroyFlagsValues * * Destroy the domain object. The running instance is shutdown if not down * already and all resources used by it are given back to the hypervisor. * This does not free the associated virDomainPtr object. * This function may require privileged access. * * Calling this function with no @flags set (equal to zero) is * equivalent to calling virDomainDestroy, and after a reasonable * timeout will forcefully terminate the guest (e.g. SIGKILL) if * necessary (which may produce undesirable results, for example * unflushed disk cache in the guest). Including * VIR_DOMAIN_DESTROY_GRACEFUL in the flags will prevent the forceful * termination of the guest, and virDomainDestroyFlags will instead * return an error if the guest doesn't terminate by the end of the * timeout; at that time, the management application can decide if * calling again without VIR_DOMAIN_DESTROY_GRACEFUL is appropriate. * * Another alternative which may produce cleaner results for the * guest's disks is to use virDomainShutdown() instead, but that * depends on guest support (some hypervisor/guest combinations may * ignore the shutdown request). * * * Returns 0 in case of success and -1 in case of failure. */ int virDomainDestroyFlags(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainDestroyFlags) { int ret; ret = conn->driver->domainDestroyFlags(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainFree: * @domain: a domain object * * Free the domain object. The running instance is kept alive. * The data structure is freed and should not be used thereafter. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainFree(virDomainPtr domain) { VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); virObjectUnref(domain); return 0; } /** * virDomainRef: * @domain: the domain to hold a reference on * * Increment the reference count on the domain. For each * additional call to this method, there shall be a corresponding * call to virDomainFree to release the reference count, once * the caller no longer needs the reference to this object. * * This method is typically useful for applications where multiple * threads are using a connection, and it is required that the * connection remain open until all threads have finished using * it. ie, each new thread using a domain would increment * the reference count. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainRef(virDomainPtr domain) { VIR_DOMAIN_DEBUG(domain, "refs=%d", domain ? domain->object.u.s.refs : 0); virResetLastError(); virCheckDomainReturn(domain, -1); virObjectRef(domain); return 0; } /** * virDomainSuspend: * @domain: a domain object * * Suspends an active domain, the process is frozen without further access * to CPU resources and I/O but the memory used by the domain at the * hypervisor level will stay allocated. Use virDomainResume() to reactivate * the domain. * This function may require privileged access. * Moreover, suspend may not be supported if domain is in some * special state like VIR_DOMAIN_PMSUSPENDED. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSuspend(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainSuspend) { int ret; ret = conn->driver->domainSuspend(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainResume: * @domain: a domain object * * Resume a suspended domain, the process is restarted from the state where * it was frozen by calling virDomainSuspend(). * This function may require privileged access * Moreover, resume may not be supported if domain is in some * special state like VIR_DOMAIN_PMSUSPENDED. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainResume(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainResume) { int ret; ret = conn->driver->domainResume(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainPMSuspendForDuration: * @dom: a domain object * @target: a value from virNodeSuspendTarget * @duration: duration in seconds to suspend, or 0 for indefinite * @flags: extra flags; not used yet, so callers should always pass 0 * * Attempt to have the guest enter the given @target power management * suspension level. If @duration is non-zero, also schedule the guest to * resume normal operation after that many seconds, if nothing else has * resumed it earlier. Some hypervisors require that @duration be 0, for * an indefinite suspension. * * Dependent on hypervisor used, this may require a * guest agent to be available, e.g. QEMU. * * Beware that at least for QEMU, the domain's process will be terminated * when VIR_NODE_SUSPEND_TARGET_DISK is used and a new process will be * launched when libvirt is asked to wake up the domain. As a result of * this, any runtime changes, such as device hotplug or memory settings, * are lost unless such changes were made with VIR_DOMAIN_AFFECT_CONFIG * flag. * * Returns: 0 on success, * -1 on failure. */ int virDomainPMSuspendForDuration(virDomainPtr dom, unsigned int target, unsigned long long duration, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "target=%u duration=%llu flags=%x", target, duration, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainPMSuspendForDuration) { int ret; ret = conn->driver->domainPMSuspendForDuration(dom, target, duration, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainPMWakeup: * @dom: a domain object * @flags: extra flags; not used yet, so callers should always pass 0 * * Inject a wakeup into the guest that previously used * virDomainPMSuspendForDuration, rather than waiting for the * previously requested duration (if any) to elapse. * * Returns: 0 on success, * -1 on failure. */ int virDomainPMWakeup(virDomainPtr dom, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainPMWakeup) { int ret; ret = conn->driver->domainPMWakeup(dom, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainSave: * @domain: a domain object * @to: path for the output file * * This method will suspend a domain and save its memory contents to * a file on disk. After the call, if successful, the domain is not * listed as running anymore (this ends the life of a transient domain). * Use virDomainRestore() to restore a domain after saving. * * See virDomainSaveFlags() for more control. Also, a save file can * be inspected or modified slightly with virDomainSaveImageGetXMLDesc() * and virDomainSaveImageDefineXML(). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSave(virDomainPtr domain, const char *to) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "to=%s", to); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(to, error); if (conn->driver->domainSave) { int ret; char *absolute_to; /* We must absolutize the file path as the save is done out of process */ if (virFileAbsPath(to, &absolute_to) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute output file path")); goto error; } ret = conn->driver->domainSave(domain, absolute_to); VIR_FREE(absolute_to); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSaveFlags: * @domain: a domain object * @to: path for the output file * @dxml: (optional) XML config for adjusting guest xml used on restore * @flags: bitwise-OR of virDomainSaveRestoreFlags * * This method will suspend a domain and save its memory contents to * a file on disk. After the call, if successful, the domain is not * listed as running anymore (this ends the life of a transient domain). * Use virDomainRestore() to restore a domain after saving. * * If the hypervisor supports it, @dxml can be used to alter * host-specific portions of the domain XML that will be used when * restoring an image. For example, it is possible to alter the * backing filename that is associated with a disk device, in order to * prepare for file renaming done as part of backing up the disk * device while the domain is stopped. * * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will * attempt to bypass the file system cache while creating the file, or * fail if it cannot do so for the given system; this can allow less * pressure on file system cache, but also risks slowing saves to NFS. * * Normally, the saved state file will remember whether the domain was * running or paused, and restore defaults to the same state. * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in * @flags will override what state gets saved into the file. These * two flags are mutually exclusive. * * A save file can be inspected or modified slightly with * virDomainSaveImageGetXMLDesc() and virDomainSaveImageDefineXML(). * * Some hypervisors may prevent this operation if there is a current * block copy operation; in that case, use virDomainBlockJobAbort() * to stop the block copy first. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSaveFlags(virDomainPtr domain, const char *to, const char *dxml, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "to=%s, dxml=%s, flags=%x", to, NULLSTR(dxml), flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(to, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING, VIR_DOMAIN_SAVE_PAUSED, error); if (conn->driver->domainSaveFlags) { int ret; char *absolute_to; /* We must absolutize the file path as the save is done out of process */ if (virFileAbsPath(to, &absolute_to) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute output file path")); goto error; } ret = conn->driver->domainSaveFlags(domain, absolute_to, dxml, flags); VIR_FREE(absolute_to); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainRestore: * @conn: pointer to the hypervisor connection * @from: path to the input file * * This method will restore a domain saved to disk by virDomainSave(). * * See virDomainRestoreFlags() for more control. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainRestore(virConnectPtr conn, const char *from) { VIR_DEBUG("conn=%p, from=%s", conn, NULLSTR(from)); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(from, error); if (conn->driver->domainRestore) { int ret; char *absolute_from; /* We must absolutize the file path as the restore is done out of process */ if (virFileAbsPath(from, &absolute_from) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute input file path")); goto error; } ret = conn->driver->domainRestore(conn, absolute_from); VIR_FREE(absolute_from); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainRestoreFlags: * @conn: pointer to the hypervisor connection * @from: path to the input file * @dxml: (optional) XML config for adjusting guest xml used on restore * @flags: bitwise-OR of virDomainSaveRestoreFlags * * This method will restore a domain saved to disk by virDomainSave(). * * If the hypervisor supports it, @dxml can be used to alter * host-specific portions of the domain XML that will be used when * restoring an image. For example, it is possible to alter the * backing filename that is associated with a disk device, in order to * prepare for file renaming done as part of backing up the disk * device while the domain is stopped. * * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will * attempt to bypass the file system cache while restoring the file, or * fail if it cannot do so for the given system; this can allow less * pressure on file system cache, but also risks slowing restores from NFS. * * Normally, the saved state file will remember whether the domain was * running or paused, and restore defaults to the same state. * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in * @flags will override the default read from the file. These two * flags are mutually exclusive. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainRestoreFlags(virConnectPtr conn, const char *from, const char *dxml, unsigned int flags) { VIR_DEBUG("conn=%p, from=%s, dxml=%s, flags=%x", conn, NULLSTR(from), NULLSTR(dxml), flags); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(from, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING, VIR_DOMAIN_SAVE_PAUSED, error); if (conn->driver->domainRestoreFlags) { int ret; char *absolute_from; /* We must absolutize the file path as the restore is done out of process */ if (virFileAbsPath(from, &absolute_from) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute input file path")); goto error; } ret = conn->driver->domainRestoreFlags(conn, absolute_from, dxml, flags); VIR_FREE(absolute_from); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainSaveImageGetXMLDesc: * @conn: pointer to the hypervisor connection * @file: path to saved state file * @flags: bitwise-OR of subset of virDomainXMLFlags * * This method will extract the XML describing the domain at the time * a saved state file was created. @file must be a file created * previously by virDomainSave() or virDomainSaveFlags(). * * No security-sensitive data will be included unless @flags contains * VIR_DOMAIN_XML_SECURE; this flag is rejected on read-only * connections. For this API, @flags should not contain either * VIR_DOMAIN_XML_INACTIVE or VIR_DOMAIN_XML_UPDATE_CPU. * * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of * error. The caller must free() the returned value. */ char * virDomainSaveImageGetXMLDesc(virConnectPtr conn, const char *file, unsigned int flags) { VIR_DEBUG("conn=%p, file=%s, flags=%x", conn, NULLSTR(file), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(file, error); if ((conn->flags & VIR_CONNECT_RO) && (flags & VIR_DOMAIN_XML_SECURE)) { virReportError(VIR_ERR_OPERATION_DENIED, "%s", _("virDomainSaveImageGetXMLDesc with secure flag")); goto error; } if (conn->driver->domainSaveImageGetXMLDesc) { char *ret; char *absolute_file; /* We must absolutize the file path as the read is done out of process */ if (virFileAbsPath(file, &absolute_file) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute input file path")); goto error; } ret = conn->driver->domainSaveImageGetXMLDesc(conn, absolute_file, flags); VIR_FREE(absolute_file); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainSaveImageDefineXML: * @conn: pointer to the hypervisor connection * @file: path to saved state file * @dxml: XML config for adjusting guest xml used on restore * @flags: bitwise-OR of virDomainSaveRestoreFlags * * This updates the definition of a domain stored in a saved state * file. @file must be a file created previously by virDomainSave() * or virDomainSaveFlags(). * * @dxml can be used to alter host-specific portions of the domain XML * that will be used when restoring an image. For example, it is * possible to alter the backing filename that is associated with a * disk device, to match renaming done as part of backing up the disk * device while the domain is stopped. * * Normally, the saved state file will remember whether the domain was * running or paused, and restore defaults to the same state. * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in * @flags will override the default saved into the file; omitting both * leaves the file's default unchanged. These two flags are mutually * exclusive. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSaveImageDefineXML(virConnectPtr conn, const char *file, const char *dxml, unsigned int flags) { VIR_DEBUG("conn=%p, file=%s, dxml=%s, flags=%x", conn, NULLSTR(file), NULLSTR(dxml), flags); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(file, error); virCheckNonNullArgGoto(dxml, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING, VIR_DOMAIN_SAVE_PAUSED, error); if (conn->driver->domainSaveImageDefineXML) { int ret; char *absolute_file; /* We must absolutize the file path as the read is done out of process */ if (virFileAbsPath(file, &absolute_file) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute input file path")); goto error; } ret = conn->driver->domainSaveImageDefineXML(conn, absolute_file, dxml, flags); VIR_FREE(absolute_file); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainCoreDump: * @domain: a domain object * @to: path for the core file * @flags: bitwise-OR of virDomainCoreDumpFlags * * This method will dump the core of a domain on a given file for analysis. * Note that for remote Xen Daemon the file path will be interpreted in * the remote host. Hypervisors may require the user to manually ensure * proper permissions on the file named by @to. * * If @flags includes VIR_DUMP_CRASH, then leave the guest shut off with * a crashed state after the dump completes. If @flags includes * VIR_DUMP_LIVE, then make the core dump while continuing to allow * the guest to run; otherwise, the guest is suspended during the dump. * VIR_DUMP_RESET flag forces reset of the guest after dump. * The above three flags are mutually exclusive. * * Additionally, if @flags includes VIR_DUMP_BYPASS_CACHE, then libvirt * will attempt to bypass the file system cache while creating the file, * or fail if it cannot do so for the given system; this can allow less * pressure on file system cache, but also risks slowing saves to NFS. * * For more control over the output format, see virDomainCoreDumpWithFormat(). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainCoreDump(virDomainPtr domain, const char *to, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "to=%s, flags=%x", to, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(to, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_LIVE, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_RESET, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_LIVE, VIR_DUMP_RESET, error); if (conn->driver->domainCoreDump) { int ret; char *absolute_to; /* We must absolutize the file path as the save is done out of process */ if (virFileAbsPath(to, &absolute_to) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute core file path")); goto error; } ret = conn->driver->domainCoreDump(domain, absolute_to, flags); VIR_FREE(absolute_to); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainCoreDumpWithFormat: * @domain: a domain object * @to: path for the core file * @dumpformat: format of domain memory's dump (one of virDomainCoreDumpFormat enum) * @flags: bitwise-OR of virDomainCoreDumpFlags * * This method will dump the core of a domain on a given file for analysis. * Note that for remote Xen Daemon the file path will be interpreted in * the remote host. Hypervisors may require the user to manually ensure * proper permissions on the file named by @to. * * @dumpformat controls which format the dump will have; use of * VIR_DOMAIN_CORE_DUMP_FORMAT_RAW mirrors what virDomainCoreDump() will * perform. Not all hypervisors are able to support all formats. * * If @flags includes VIR_DUMP_CRASH, then leave the guest shut off with * a crashed state after the dump completes. If @flags includes * VIR_DUMP_LIVE, then make the core dump while continuing to allow * the guest to run; otherwise, the guest is suspended during the dump. * VIR_DUMP_RESET flag forces reset of the guest after dump. * The above three flags are mutually exclusive. * * Additionally, if @flags includes VIR_DUMP_BYPASS_CACHE, then libvirt * will attempt to bypass the file system cache while creating the file, * or fail if it cannot do so for the given system; this can allow less * pressure on file system cache, but also risks slowing saves to NFS. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainCoreDumpWithFormat(virDomainPtr domain, const char *to, unsigned int dumpformat, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "to=%s, dumpformat=%u, flags=%x", to, dumpformat, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(to, error); if (dumpformat >= VIR_DOMAIN_CORE_DUMP_FORMAT_LAST) { virReportInvalidArg(flags, _("dumpformat '%d' is not supported"), dumpformat); goto error; } VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_LIVE, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_RESET, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_LIVE, VIR_DUMP_RESET, error); if (conn->driver->domainCoreDumpWithFormat) { int ret; char *absolute_to; /* We must absolutize the file path as the save is done out of process */ if (virFileAbsPath(to, &absolute_to) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute core file path")); goto error; } ret = conn->driver->domainCoreDumpWithFormat(domain, absolute_to, dumpformat, flags); VIR_FREE(absolute_to); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainScreenshot: * @domain: a domain object * @stream: stream to use as output * @screen: monitor ID to take screenshot from * @flags: extra flags; not used yet, so callers should always pass 0 * * Take a screenshot of current domain console as a stream. The image format * is hypervisor specific. Moreover, some hypervisors supports multiple * displays per domain. These can be distinguished by @screen argument. * * This call sets up a stream; subsequent use of stream API is necessary * to transfer actual data, determine how much data is successfully * transferred, and detect any errors. * * The screen ID is the sequential number of screen. In case of multiple * graphics cards, heads are enumerated before devices, e.g. having * two graphics cards, both with four heads, screen ID 5 addresses * the second head on the second card. * * Returns a string representing the mime-type of the image format, or * NULL upon error. The caller must free() the returned value. */ char * virDomainScreenshot(virDomainPtr domain, virStreamPtr stream, unsigned int screen, unsigned int flags) { VIR_DOMAIN_DEBUG(domain, "stream=%p, flags=%x", stream, flags); virResetLastError(); virCheckDomainReturn(domain, NULL); virCheckStreamGoto(stream, error); virCheckReadOnlyGoto(domain->conn->flags, error); if (domain->conn != stream->conn) { virReportInvalidArg(stream, _("stream must match connection of domain '%s'"), domain->name); goto error; } if (domain->conn->driver->domainScreenshot) { char *ret; ret = domain->conn->driver->domainScreenshot(domain, stream, screen, flags); if (ret == NULL) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virDomainShutdown: * @domain: a domain object * * Shutdown a domain, the domain object is still usable thereafter, but * the domain OS is being stopped. Note that the guest OS may ignore the * request. Additionally, the hypervisor may check and support the domain * 'on_poweroff' XML setting resulting in a domain that reboots instead of * shutting down. For guests that react to a shutdown request, the differences * from virDomainDestroy() are that the guests disk storage will be in a * stable state rather than having the (virtual) power cord pulled, and * this command returns as soon as the shutdown request is issued rather * than blocking until the guest is no longer running. * * If the domain is transient and has any snapshot metadata (see * virDomainSnapshotNum()), then that metadata will automatically * be deleted when the domain quits. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainShutdown(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainShutdown) { int ret; ret = conn->driver->domainShutdown(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainShutdownFlags: * @domain: a domain object * @flags: bitwise-OR of virDomainShutdownFlagValues * * Shutdown a domain, the domain object is still usable thereafter but * the domain OS is being stopped. Note that the guest OS may ignore the * request. Additionally, the hypervisor may check and support the domain * 'on_poweroff' XML setting resulting in a domain that reboots instead of * shutting down. For guests that react to a shutdown request, the differences * from virDomainDestroy() are that the guest's disk storage will be in a * stable state rather than having the (virtual) power cord pulled, and * this command returns as soon as the shutdown request is issued rather * than blocking until the guest is no longer running. * * If the domain is transient and has any snapshot metadata (see * virDomainSnapshotNum()), then that metadata will automatically * be deleted when the domain quits. * * If @flags is set to zero, then the hypervisor will choose the * method of shutdown it considers best. To have greater control * pass one or more of the virDomainShutdownFlagValues. The order * in which the hypervisor tries each shutdown method is undefined, * and a hypervisor is not required to support all methods. * * To use guest agent (VIR_DOMAIN_SHUTDOWN_GUEST_AGENT) the domain XML * must have <channel> configured. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainShutdownFlags(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainShutdownFlags) { int ret; ret = conn->driver->domainShutdownFlags(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainReboot: * @domain: a domain object * @flags: bitwise-OR of virDomainRebootFlagValues * * Reboot a domain, the domain object is still usable thereafter, but * the domain OS is being stopped for a restart. * Note that the guest OS may ignore the request. * Additionally, the hypervisor may check and support the domain * 'on_reboot' XML setting resulting in a domain that shuts down instead * of rebooting. * * If @flags is set to zero, then the hypervisor will choose the * method of shutdown it considers best. To have greater control * pass one or more of the virDomainRebootFlagValues. The order * in which the hypervisor tries each shutdown method is undefined, * and a hypervisor is not required to support all methods. * * To use guest agent (VIR_DOMAIN_REBOOT_GUEST_AGENT) the domain XML * must have <channel> configured. * * Due to implementation limitations in some drivers (the qemu driver, * for instance) it is not advised to migrate or save a guest that is * rebooting as a result of this API. Migrating such a guest can lead * to a plain shutdown on the destination. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainReboot(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainReboot) { int ret; ret = conn->driver->domainReboot(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainReset: * @domain: a domain object * @flags: extra flags; not used yet, so callers should always pass 0 * * Reset a domain immediately without any guest OS shutdown. * Reset emulates the power reset button on a machine, where all * hardware sees the RST line set and reinitializes internal state. * * Note that there is a risk of data loss caused by reset without any * guest OS shutdown. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainReset(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainReset) { int ret; ret = conn->driver->domainReset(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetName: * @domain: a domain object * * Get the public name for that domain * * Returns a pointer to the name or NULL, the string need not be deallocated * its lifetime will be the same as the domain object. */ const char * virDomainGetName(virDomainPtr domain) { VIR_DEBUG("domain=%p", domain); virResetLastError(); virCheckDomainReturn(domain, NULL); return domain->name; } /** * virDomainGetUUID: * @domain: a domain object * @uuid: pointer to a VIR_UUID_BUFLEN bytes array * * Get the UUID for a domain * * Returns -1 in case of error, 0 in case of success */ int virDomainGetUUID(virDomainPtr domain, unsigned char *uuid) { VIR_DOMAIN_DEBUG(domain, "uuid=%p", uuid); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(uuid, error); memcpy(uuid, &domain->uuid[0], VIR_UUID_BUFLEN); return 0; error: virDispatchError(domain->conn); return -1; } /** * virDomainGetUUIDString: * @domain: a domain object * @buf: pointer to a VIR_UUID_STRING_BUFLEN bytes array * * Get the UUID for a domain as string. For more information about * UUID see RFC4122. * * Returns -1 in case of error, 0 in case of success */ int virDomainGetUUIDString(virDomainPtr domain, char *buf) { VIR_DOMAIN_DEBUG(domain, "buf=%p", buf); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(buf, error); virUUIDFormat(domain->uuid, buf); return 0; error: virDispatchError(domain->conn); return -1; } /** * virDomainGetID: * @domain: a domain object * * Get the hypervisor ID number for the domain * * Returns the domain ID number or (unsigned int) -1 in case of error */ unsigned int virDomainGetID(virDomainPtr domain) { VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, (unsigned int)-1); return domain->id; } /** * virDomainGetOSType: * @domain: a domain object * * Get the type of domain operation system. * * Returns the new string or NULL in case of error, the string must be * freed by the caller. */ char * virDomainGetOSType(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; if (conn->driver->domainGetOSType) { char *ret; ret = conn->driver->domainGetOSType(domain); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virDomainGetMaxMemory: * @domain: a domain object or NULL * * Retrieve the maximum amount of physical memory allocated to a * domain. If domain is NULL, then this get the amount of memory reserved * to Domain0 i.e. the domain where the application runs. * * Returns the memory size in kibibytes (blocks of 1024 bytes), or 0 in * case of error. */ unsigned long virDomainGetMaxMemory(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, 0); conn = domain->conn; if (conn->driver->domainGetMaxMemory) { unsigned long long ret; ret = conn->driver->domainGetMaxMemory(domain); if (ret == 0) goto error; if ((unsigned long) ret != ret) { virReportError(VIR_ERR_OVERFLOW, _("result too large: %llu"), ret); goto error; } return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return 0; } /** * virDomainSetMaxMemory: * @domain: a domain object or NULL * @memory: the memory size in kibibytes (blocks of 1024 bytes) * * Dynamically change the maximum amount of physical memory allocated to a * domain. If domain is NULL, then this change the amount of memory reserved * to Domain0 i.e. the domain where the application runs. * This function may require privileged access to the hypervisor. * * This command is hypervisor-specific for whether active, persistent, * or both configurations are changed; for more control, use * virDomainSetMemoryFlags(). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSetMaxMemory(virDomainPtr domain, unsigned long memory) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "memory=%lu", memory); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonZeroArgGoto(memory, error); if (virMemoryMaxValue(true) / 1024 <= memory) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %lu"), memory); goto error; } if (conn->driver->domainSetMaxMemory) { int ret; ret = conn->driver->domainSetMaxMemory(domain, memory); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetMemory: * @domain: a domain object or NULL * @memory: the memory size in kibibytes (blocks of 1024 bytes) * * Dynamically change the target amount of physical memory allocated to a * domain. If domain is NULL, then this change the amount of memory reserved * to Domain0 i.e. the domain where the application runs. * This function may require privileged access to the hypervisor. * * This command is hypervisor-specific for whether active, persistent, * or both configurations are changed; for more control, use * virDomainSetMemoryFlags(). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSetMemory(virDomainPtr domain, unsigned long memory) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "memory=%lu", memory); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonZeroArgGoto(memory, error); if (virMemoryMaxValue(true) / 1024 <= memory) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %lu"), memory); goto error; } if (conn->driver->domainSetMemory) { int ret; ret = conn->driver->domainSetMemory(domain, memory); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetMemoryFlags: * @domain: a domain object or NULL * @memory: the memory size in kibibytes (blocks of 1024 bytes) * @flags: bitwise-OR of virDomainMemoryModFlags * * Dynamically change the target amount of physical memory allocated to a * domain. If domain is NULL, then this change the amount of memory reserved * to Domain0 i.e. the domain where the application runs. * This function may require privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects * a running domain and will fail if domain is not active. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified * (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain * modifies persistent setup, while an active domain is hypervisor-dependent * on whether just live or both live and persistent state is changed. * If VIR_DOMAIN_MEM_MAXIMUM is set, the change affects domain's maximum memory * size rather than current memory size. * Not all hypervisors can support all flag combinations. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSetMemoryFlags(virDomainPtr domain, unsigned long memory, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "memory=%lu, flags=%x", memory, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonZeroArgGoto(memory, error); if (virMemoryMaxValue(true) / 1024 <= memory) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %lu"), memory); goto error; } if (conn->driver->domainSetMemoryFlags) { int ret; ret = conn->driver->domainSetMemoryFlags(domain, memory, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetMemoryStatsPeriod: * @domain: a domain object or NULL * @period: the period in seconds for stats collection * @flags: bitwise-OR of virDomainMemoryModFlags * * Dynamically change the domain memory balloon driver statistics collection * period. Use 0 to disable and a positive value to enable. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects * a running domain and will fail if domain is not active. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified * (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain * modifies persistent setup, while an active domain is hypervisor-dependent * on whether just live or both live and persistent state is changed. * * Not all hypervisors can support all flag combinations. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSetMemoryStatsPeriod(virDomainPtr domain, int period, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "period=%d, flags=%x", period, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); /* This must be positive to set the balloon collection period */ virCheckNonNegativeArgGoto(period, error); if (conn->driver->domainSetMemoryStatsPeriod) { int ret; ret = conn->driver->domainSetMemoryStatsPeriod(domain, period, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetMemoryParameters: * @domain: pointer to domain object * @params: pointer to memory parameter objects * @nparams: number of memory parameter (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainModificationImpact * * Change all or a subset of the memory tunables. * This function may require privileged access to the hypervisor. * * Possible values for all *_limit memory tunables are in range from 0 to * VIR_DOMAIN_MEMORY_PARAM_UNLIMITED. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckPositiveArgGoto(nparams, error); if (virTypedParameterValidateSet(conn, params, nparams) < 0) goto error; if (conn->driver->domainSetMemoryParameters) { int ret; ret = conn->driver->domainSetMemoryParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetMemoryParameters: * @domain: pointer to domain object * @params: pointer to memory parameter object * (return value, allocated by the caller) * @nparams: pointer to number of memory parameters; input and output * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all memory parameters. On input, @nparams gives the size of the * @params array; on output, @nparams gives how many slots were filled * with parameter information, which might be less but will not exceed * the input value. * * As a special case, calling with @params as NULL and @nparams as 0 on * input will cause @nparams on output to contain the number of parameters * supported by the hypervisor. The caller should then allocate @params * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API * again. * * Here is a sample code snippet: * * if (virDomainGetMemoryParameters(dom, NULL, &nparams, 0) == 0 && * nparams != 0) { * if ((params = malloc(sizeof(*params) * nparams)) == NULL) * goto error; * memset(params, 0, sizeof(*params) * nparams); * if (virDomainGetMemoryParameters(dom, params, &nparams, 0)) * goto error; * } * * This function may require privileged access to the hypervisor. This function * expects the caller to allocate the @params. * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, (nparams) ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) virCheckNonNullArgGoto(params, error); if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); conn = domain->conn; if (conn->driver->domainGetMemoryParameters) { int ret; ret = conn->driver->domainGetMemoryParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetNumaParameters: * @domain: pointer to domain object * @params: pointer to numa parameter objects * @nparams: number of numa parameters (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainModificationImpact * * Change all or a subset of the numa tunables. * This function may require privileged access to the hypervisor. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetNumaParameters(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckPositiveArgGoto(nparams, error); if (virTypedParameterValidateSet(domain->conn, params, nparams) < 0) goto error; conn = domain->conn; if (conn->driver->domainSetNumaParameters) { int ret; ret = conn->driver->domainSetNumaParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetNumaParameters: * @domain: pointer to domain object * @params: pointer to numa parameter object * (return value, allocated by the caller) * @nparams: pointer to number of numa parameters * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all numa parameters. On input, @nparams gives the size of the * @params array; on output, @nparams gives how many slots were filled * with parameter information, which might be less but will not exceed * the input value. * * As a special case, calling with @params as NULL and @nparams as 0 on * input will cause @nparams on output to contain the number of parameters * supported by the hypervisor. The caller should then allocate @params * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API * again. * * See virDomainGetMemoryParameters() for an equivalent usage example. * * This function may require privileged access to the hypervisor. This function * expects the caller to allocate the @params. * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetNumaParameters(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, (nparams) ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) virCheckNonNullArgGoto(params, error); if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; conn = domain->conn; if (conn->driver->domainGetNumaParameters) { int ret; ret = conn->driver->domainGetNumaParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetBlkioParameters: * @domain: pointer to domain object * @params: pointer to blkio parameter objects * @nparams: number of blkio parameters (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainModificationImpact * * Change all or a subset of the blkio tunables. * This function may require privileged access to the hypervisor. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetBlkioParameters(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckNonNegativeArgGoto(nparams, error); if (virTypedParameterValidateSet(conn, params, nparams) < 0) goto error; if (conn->driver->domainSetBlkioParameters) { int ret; ret = conn->driver->domainSetBlkioParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetBlkioParameters: * @domain: pointer to domain object * @params: pointer to blkio parameter object * (return value, allocated by the caller) * @nparams: pointer to number of blkio parameters; input and output * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all blkio parameters. On input, @nparams gives the size of the * @params array; on output, @nparams gives how many slots were filled * with parameter information, which might be less but will not exceed * the input value. * * As a special case, calling with @params as NULL and @nparams as 0 on * input will cause @nparams on output to contain the number of parameters * supported by the hypervisor. The caller should then allocate @params * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API * again. * * See virDomainGetMemoryParameters() for an equivalent usage example. * * This function may require privileged access to the hypervisor. This function * expects the caller to allocate the @params. * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetBlkioParameters(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, (nparams) ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) virCheckNonNullArgGoto(params, error); if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); conn = domain->conn; if (conn->driver->domainGetBlkioParameters) { int ret; ret = conn->driver->domainGetBlkioParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetInfo: * @domain: a domain object * @info: pointer to a virDomainInfo structure allocated by the user * * Extract information about a domain. Note that if the connection * used to get the domain is limited only a partial set of the information * can be extracted. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "info=%p", info); virResetLastError(); if (info) memset(info, 0, sizeof(*info)); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(info, error); conn = domain->conn; if (conn->driver->domainGetInfo) { int ret; ret = conn->driver->domainGetInfo(domain, info); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetState: * @domain: a domain object * @state: returned state of the domain (one of virDomainState) * @reason: returned reason which led to @state (one of virDomain*Reason * corresponding to the current state); it is allowed to be NULL * @flags: extra flags; not used yet, so callers should always pass 0 * * Extract domain state. Each state can be accompanied with a reason (if known) * which led to the state. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetState(virDomainPtr domain, int *state, int *reason, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "state=%p, reason=%p, flags=%x", state, reason, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(state, error); conn = domain->conn; if (conn->driver->domainGetState) { int ret; ret = conn->driver->domainGetState(domain, state, reason, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetControlInfo: * @domain: a domain object * @info: pointer to a virDomainControlInfo structure allocated by the user * @flags: extra flags; not used yet, so callers should always pass 0 * * Extract details about current state of control interface to a domain. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetControlInfo(virDomainPtr domain, virDomainControlInfoPtr info, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "info=%p, flags=%x", info, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(info, error); conn = domain->conn; if (conn->driver->domainGetControlInfo) { int ret; ret = conn->driver->domainGetControlInfo(domain, info, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetXMLDesc: * @domain: a domain object * @flags: bitwise-OR of virDomainXMLFlags * * Provide an XML description of the domain. The description may be reused * later to relaunch the domain with virDomainCreateXML(). * * No security-sensitive data will be included unless @flags contains * VIR_DOMAIN_XML_SECURE; this flag is rejected on read-only * connections. If @flags includes VIR_DOMAIN_XML_INACTIVE, then the * XML represents the configuration that will be used on the next boot * of a persistent domain; otherwise, the configuration represents the * currently running domain. If @flags contains * VIR_DOMAIN_XML_UPDATE_CPU, then the portion of the domain XML * describing CPU capabilities is modified to match actual * capabilities of the host. * * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of error. * the caller must free() the returned value. */ char * virDomainGetXMLDesc(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; if ((conn->flags & VIR_CONNECT_RO) && (flags & (VIR_DOMAIN_XML_SECURE | VIR_DOMAIN_XML_MIGRATABLE))) { virReportError(VIR_ERR_OPERATION_DENIED, "%s", _("virDomainGetXMLDesc with secure flag")); goto error; } if (conn->driver->domainGetXMLDesc) { char *ret; ret = conn->driver->domainGetXMLDesc(domain, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virConnectDomainXMLFromNative: * @conn: a connection object * @nativeFormat: configuration format importing from * @nativeConfig: the configuration data to import * @flags: extra flags; not used yet, so callers should always pass 0 * * Reads native configuration data describing a domain, and * generates libvirt domain XML. The format of the native * data is hypervisor dependent. * * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of error. * the caller must free() the returned value. */ char * virConnectDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat, const char *nativeConfig, unsigned int flags) { VIR_DEBUG("conn=%p, format=%s, config=%s, flags=%x", conn, NULLSTR(nativeFormat), NULLSTR(nativeConfig), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(nativeFormat, error); virCheckNonNullArgGoto(nativeConfig, error); if (conn->driver->connectDomainXMLFromNative) { char *ret; ret = conn->driver->connectDomainXMLFromNative(conn, nativeFormat, nativeConfig, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virConnectDomainXMLToNative: * @conn: a connection object * @nativeFormat: configuration format exporting to * @domainXml: the domain configuration to export * @flags: extra flags; not used yet, so callers should always pass 0 * * Reads a domain XML configuration document, and generates * a native configuration file describing the domain. * The format of the native data is hypervisor dependent. * * Returns a 0 terminated UTF-8 encoded native config datafile, or NULL in case of error. * the caller must free() the returned value. */ char * virConnectDomainXMLToNative(virConnectPtr conn, const char *nativeFormat, const char *domainXml, unsigned int flags) { VIR_DEBUG("conn=%p, format=%s, xml=%s, flags=%x", conn, NULLSTR(nativeFormat), NULLSTR(domainXml), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(nativeFormat, error); virCheckNonNullArgGoto(domainXml, error); if (conn->driver->connectDomainXMLToNative) { char *ret; ret = conn->driver->connectDomainXMLToNative(conn, nativeFormat, domainXml, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /* * Sequence v1: * * Dst: Prepare * - Get ready to accept incoming VM * - Generate optional cookie to pass to src * * Src: Perform * - Start migration and wait for send completion * - Kill off VM if successful, resume if failed * * Dst: Finish * - Wait for recv completion and check status * - Kill off VM if unsuccessful * */ static virDomainPtr virDomainMigrateVersion1(virDomainPtr domain, virConnectPtr dconn, unsigned long flags, const char *dname, const char *uri, unsigned long bandwidth) { virDomainPtr ddomain = NULL; char *uri_out = NULL; char *cookie = NULL; int cookielen = 0, ret; virDomainInfo info; unsigned int destflags; VIR_DOMAIN_DEBUG(domain, "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu", dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth); ret = virDomainGetInfo(domain, &info); if (ret == 0 && info.state == VIR_DOMAIN_PAUSED) flags |= VIR_MIGRATE_PAUSED; destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR | VIR_MIGRATE_AUTO_CONVERGE); /* Prepare the migration. * * The destination host may return a cookie, or leave cookie as * NULL. * * The destination host MUST set uri_out if uri_in is NULL. * * If uri_in is non-NULL, then the destination host may modify * the URI by setting uri_out. If it does not wish to modify * the URI, it should leave uri_out as NULL. */ if (dconn->driver->domainMigratePrepare (dconn, &cookie, &cookielen, uri, &uri_out, destflags, dname, bandwidth) == -1) goto done; if (uri == NULL && uri_out == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("domainMigratePrepare did not set uri")); goto done; } if (uri_out) uri = uri_out; /* Did domainMigratePrepare change URI? */ /* Perform the migration. The driver isn't supposed to return * until the migration is complete. */ if (domain->conn->driver->domainMigratePerform (domain, cookie, cookielen, uri, flags, dname, bandwidth) == -1) goto done; /* Get the destination domain and return it or error. * 'domain' no longer actually exists at this point * (or so we hope), but we still use the object in memory * in order to get the name. */ dname = dname ? dname : domain->name; if (dconn->driver->domainMigrateFinish) ddomain = dconn->driver->domainMigrateFinish (dconn, dname, cookie, cookielen, uri, destflags); else ddomain = virDomainLookupByName(dconn, dname); done: VIR_FREE(uri_out); VIR_FREE(cookie); return ddomain; } /* * Sequence v2: * * Src: DumpXML * - Generate XML to pass to dst * * Dst: Prepare * - Get ready to accept incoming VM * - Generate optional cookie to pass to src * * Src: Perform * - Start migration and wait for send completion * - Kill off VM if successful, resume if failed * * Dst: Finish * - Wait for recv completion and check status * - Kill off VM if unsuccessful * */ static virDomainPtr virDomainMigrateVersion2(virDomainPtr domain, virConnectPtr dconn, unsigned long flags, const char *dname, const char *uri, unsigned long bandwidth) { virDomainPtr ddomain = NULL; char *uri_out = NULL; char *cookie = NULL; char *dom_xml = NULL; int cookielen = 0, ret; virDomainInfo info; virErrorPtr orig_err = NULL; unsigned int getxml_flags = 0; int cancelled; unsigned long destflags; VIR_DOMAIN_DEBUG(domain, "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu", dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth); /* Prepare the migration. * * The destination host may return a cookie, or leave cookie as * NULL. * * The destination host MUST set uri_out if uri_in is NULL. * * If uri_in is non-NULL, then the destination host may modify * the URI by setting uri_out. If it does not wish to modify * the URI, it should leave uri_out as NULL. */ /* In version 2 of the protocol, the prepare step is slightly * different. We fetch the domain XML of the source domain * and pass it to Prepare2. */ if (!domain->conn->driver->domainGetXMLDesc) { virReportUnsupportedError(); return NULL; } if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_XML_MIGRATABLE)) { getxml_flags |= VIR_DOMAIN_XML_MIGRATABLE; } else { getxml_flags |= VIR_DOMAIN_XML_SECURE | VIR_DOMAIN_XML_UPDATE_CPU; } dom_xml = domain->conn->driver->domainGetXMLDesc(domain, getxml_flags); if (!dom_xml) return NULL; ret = virDomainGetInfo(domain, &info); if (ret == 0 && info.state == VIR_DOMAIN_PAUSED) flags |= VIR_MIGRATE_PAUSED; destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR | VIR_MIGRATE_AUTO_CONVERGE); VIR_DEBUG("Prepare2 %p flags=%lx", dconn, destflags); ret = dconn->driver->domainMigratePrepare2 (dconn, &cookie, &cookielen, uri, &uri_out, destflags, dname, bandwidth, dom_xml); VIR_FREE(dom_xml); if (ret == -1) goto done; if (uri == NULL && uri_out == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("domainMigratePrepare2 did not set uri")); cancelled = 1; /* Make sure Finish doesn't overwrite the error */ orig_err = virSaveLastError(); goto finish; } if (uri_out) uri = uri_out; /* Did domainMigratePrepare2 change URI? */ /* Perform the migration. The driver isn't supposed to return * until the migration is complete. */ VIR_DEBUG("Perform %p", domain->conn); ret = domain->conn->driver->domainMigratePerform (domain, cookie, cookielen, uri, flags, dname, bandwidth); /* Perform failed. Make sure Finish doesn't overwrite the error */ if (ret < 0) orig_err = virSaveLastError(); /* If Perform returns < 0, then we need to cancel the VM * startup on the destination */ cancelled = ret < 0 ? 1 : 0; finish: /* In version 2 of the migration protocol, we pass the * status code from the sender to the destination host, * so it can do any cleanup if the migration failed. */ dname = dname ? dname : domain->name; VIR_DEBUG("Finish2 %p ret=%d", dconn, ret); ddomain = dconn->driver->domainMigrateFinish2 (dconn, dname, cookie, cookielen, uri, destflags, cancelled); if (cancelled && ddomain) VIR_ERROR(_("finish step ignored that migration was cancelled")); done: if (orig_err) { virSetError(orig_err); virFreeError(orig_err); } VIR_FREE(uri_out); VIR_FREE(cookie); return ddomain; } /* * Sequence v3: * * Src: Begin * - Generate XML to pass to dst * - Generate optional cookie to pass to dst * * Dst: Prepare * - Get ready to accept incoming VM * - Generate optional cookie to pass to src * * Src: Perform * - Start migration and wait for send completion * - Generate optional cookie to pass to dst * * Dst: Finish * - Wait for recv completion and check status * - Kill off VM if failed, resume if success * - Generate optional cookie to pass to src * * Src: Confirm * - Kill off VM if success, resume if failed * * If useParams is true, params and nparams contain migration parameters and * we know it's safe to call the API which supports extensible parameters. * Otherwise, we have to use xmlin, dname, uri, and bandwidth and pass them * to the old-style APIs. */ static virDomainPtr virDomainMigrateVersion3Full(virDomainPtr domain, virConnectPtr dconn, const char *xmlin, const char *dname, const char *uri, unsigned long long bandwidth, virTypedParameterPtr params, int nparams, bool useParams, unsigned int flags) { virDomainPtr ddomain = NULL; char *uri_out = NULL; char *cookiein = NULL; char *cookieout = NULL; char *dom_xml = NULL; int cookieinlen = 0; int cookieoutlen = 0; int ret; virDomainInfo info; virErrorPtr orig_err = NULL; int cancelled = 1; unsigned long protection = 0; bool notify_source = true; unsigned int destflags; int state; virTypedParameterPtr tmp; VIR_DOMAIN_DEBUG(domain, "dconn=%p, xmlin=%s, dname=%s, uri=%s, bandwidth=%llu, " "params=%p, nparams=%d, useParams=%d, flags=%x", dconn, NULLSTR(xmlin), NULLSTR(dname), NULLSTR(uri), bandwidth, params, nparams, useParams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); if ((!useParams && (!domain->conn->driver->domainMigrateBegin3 || !domain->conn->driver->domainMigratePerform3 || !domain->conn->driver->domainMigrateConfirm3 || !dconn->driver->domainMigratePrepare3 || !dconn->driver->domainMigrateFinish3)) || (useParams && (!domain->conn->driver->domainMigrateBegin3Params || !domain->conn->driver->domainMigratePerform3Params || !domain->conn->driver->domainMigrateConfirm3Params || !dconn->driver->domainMigratePrepare3Params || !dconn->driver->domainMigrateFinish3Params))) { virReportUnsupportedError(); return NULL; } if (virTypedParamsCopy(&tmp, params, nparams) < 0) return NULL; params = tmp; if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION)) protection = VIR_MIGRATE_CHANGE_PROTECTION; VIR_DEBUG("Begin3 %p", domain->conn); if (useParams) { dom_xml = domain->conn->driver->domainMigrateBegin3Params (domain, params, nparams, &cookieout, &cookieoutlen, flags | protection); } else { dom_xml = domain->conn->driver->domainMigrateBegin3 (domain, xmlin, &cookieout, &cookieoutlen, flags | protection, dname, bandwidth); } if (!dom_xml) goto done; if (useParams) { /* If source is new enough to support extensible migration parameters, * it's certainly new enough to support virDomainGetState. */ ret = virDomainGetState(domain, &state, NULL, 0); } else { ret = virDomainGetInfo(domain, &info); state = info.state; } if (ret == 0 && state == VIR_DOMAIN_PAUSED) flags |= VIR_MIGRATE_PAUSED; destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR | VIR_MIGRATE_AUTO_CONVERGE); VIR_DEBUG("Prepare3 %p flags=%x", dconn, destflags); cookiein = cookieout; cookieinlen = cookieoutlen; cookieout = NULL; cookieoutlen = 0; if (useParams) { if (virTypedParamsReplaceString(&params, &nparams, VIR_MIGRATE_PARAM_DEST_XML, dom_xml) < 0) goto done; ret = dconn->driver->domainMigratePrepare3Params (dconn, params, nparams, cookiein, cookieinlen, &cookieout, &cookieoutlen, &uri_out, destflags); } else { ret = dconn->driver->domainMigratePrepare3 (dconn, cookiein, cookieinlen, &cookieout, &cookieoutlen, uri, &uri_out, destflags, dname, bandwidth, dom_xml); } if (ret == -1) { if (protection) { /* Begin already started a migration job so we need to cancel it by * calling Confirm while making sure it doesn't overwrite the error */ orig_err = virSaveLastError(); goto confirm; } else { goto done; } } /* Did domainMigratePrepare3 change URI? */ if (uri_out) { uri = uri_out; if (useParams && virTypedParamsReplaceString(&params, &nparams, VIR_MIGRATE_PARAM_URI, uri_out) < 0) { cancelled = 1; orig_err = virSaveLastError(); goto finish; } } else if (!uri && virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_URI, &uri) <= 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("domainMigratePrepare3 did not set uri")); cancelled = 1; orig_err = virSaveLastError(); goto finish; } if (flags & VIR_MIGRATE_OFFLINE) { VIR_DEBUG("Offline migration, skipping Perform phase"); VIR_FREE(cookieout); cookieoutlen = 0; cancelled = 0; goto finish; } /* Perform the migration. The driver isn't supposed to return * until the migration is complete. The src VM should remain * running, but in paused state until the destination can * confirm migration completion. */ VIR_DEBUG("Perform3 %p uri=%s", domain->conn, uri); VIR_FREE(cookiein); cookiein = cookieout; cookieinlen = cookieoutlen; cookieout = NULL; cookieoutlen = 0; /* dconnuri not relevant in non-P2P modes, so left NULL here */ if (useParams) { ret = domain->conn->driver->domainMigratePerform3Params (domain, NULL, params, nparams, cookiein, cookieinlen, &cookieout, &cookieoutlen, flags | protection); } else { ret = domain->conn->driver->domainMigratePerform3 (domain, NULL, cookiein, cookieinlen, &cookieout, &cookieoutlen, NULL, uri, flags | protection, dname, bandwidth); } /* Perform failed. Make sure Finish doesn't overwrite the error */ if (ret < 0) { orig_err = virSaveLastError(); /* Perform failed so we don't need to call confirm to let source know * about the failure. */ notify_source = false; } /* If Perform returns < 0, then we need to cancel the VM * startup on the destination */ cancelled = ret < 0 ? 1 : 0; finish: /* * The status code from the source is passed to the destination. * The dest can cleanup if the source indicated it failed to * send all migration data. Returns NULL for ddomain if * the dest was unable to complete migration. */ VIR_DEBUG("Finish3 %p ret=%d", dconn, ret); VIR_FREE(cookiein); cookiein = cookieout; cookieinlen = cookieoutlen; cookieout = NULL; cookieoutlen = 0; if (useParams) { if (virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_NAME, NULL) <= 0 && virTypedParamsReplaceString(&params, &nparams, VIR_MIGRATE_PARAM_DEST_NAME, domain->name) < 0) { ddomain = NULL; } else { ddomain = dconn->driver->domainMigrateFinish3Params (dconn, params, nparams, cookiein, cookieinlen, &cookieout, &cookieoutlen, destflags, cancelled); } } else { dname = dname ? dname : domain->name; ddomain = dconn->driver->domainMigrateFinish3 (dconn, dname, cookiein, cookieinlen, &cookieout, &cookieoutlen, NULL, uri, destflags, cancelled); } if (cancelled) { if (ddomain) { VIR_ERROR(_("finish step ignored that migration was cancelled")); } else { /* If Finish reported a useful error, use it instead of the * original "migration unexpectedly failed" error. * * This is ugly but we can't do better with the APIs we have. We * only replace the error if Finish was called with cancelled == 1 * and reported a real error (old libvirt would report an error * from RPC instead of MIGRATE_FINISH_OK), which only happens when * the domain died on destination. To further reduce a possibility * of false positives we also check that Perform returned * VIR_ERR_OPERATION_FAILED. */ if (orig_err && orig_err->domain == VIR_FROM_QEMU && orig_err->code == VIR_ERR_OPERATION_FAILED) { virErrorPtr err = virGetLastError(); if (err && err->domain == VIR_FROM_QEMU && err->code != VIR_ERR_MIGRATE_FINISH_OK) { virFreeError(orig_err); orig_err = NULL; } } } } /* If ddomain is NULL, then we were unable to start * the guest on the target, and must restart on the * source. There is a small chance that the ddomain * is NULL due to an RPC failure, in which case * ddomain could in fact be running on the dest. * The lock manager plugins should take care of * safety in this scenario. */ cancelled = ddomain == NULL ? 1 : 0; /* If finish3 set an error, and we don't have an earlier * one we need to preserve it in case confirm3 overwrites */ if (!orig_err) orig_err = virSaveLastError(); confirm: /* * If cancelled, then src VM will be restarted, else it will be killed. * Don't do this if migration failed on source and thus it was already * cancelled there. */ if (notify_source) { VIR_DEBUG("Confirm3 %p ret=%d domain=%p", domain->conn, ret, domain); VIR_FREE(cookiein); cookiein = cookieout; cookieinlen = cookieoutlen; cookieout = NULL; cookieoutlen = 0; if (useParams) { ret = domain->conn->driver->domainMigrateConfirm3Params (domain, params, nparams, cookiein, cookieinlen, flags | protection, cancelled); } else { ret = domain->conn->driver->domainMigrateConfirm3 (domain, cookiein, cookieinlen, flags | protection, cancelled); } /* If Confirm3 returns -1, there's nothing more we can * do, but fortunately worst case is that there is a * domain left in 'paused' state on source. */ if (ret < 0) { VIR_WARN("Guest %s probably left in 'paused' state on source", domain->name); } } done: if (orig_err) { virSetError(orig_err); virFreeError(orig_err); } VIR_FREE(dom_xml); VIR_FREE(uri_out); VIR_FREE(cookiein); VIR_FREE(cookieout); virTypedParamsFree(params, nparams); return ddomain; } static virDomainPtr virDomainMigrateVersion3(virDomainPtr domain, virConnectPtr dconn, const char *xmlin, unsigned long flags, const char *dname, const char *uri, unsigned long bandwidth) { return virDomainMigrateVersion3Full(domain, dconn, xmlin, dname, uri, bandwidth, NULL, 0, false, flags); } static virDomainPtr virDomainMigrateVersion3Params(virDomainPtr domain, virConnectPtr dconn, virTypedParameterPtr params, int nparams, unsigned int flags) { return virDomainMigrateVersion3Full(domain, dconn, NULL, NULL, NULL, 0, params, nparams, true, flags); } static int virDomainMigrateCheckNotLocal(const char *dconnuri) { virURIPtr tempuri = NULL; int ret = -1; if (!(tempuri = virURIParse(dconnuri))) goto cleanup; if (!tempuri->server || STRPREFIX(tempuri->server, "localhost")) { virReportInvalidArg(dconnuri, "%s", _("Attempt to migrate guest to the same host")); goto cleanup; } ret = 0; cleanup: virURIFree(tempuri); return ret; } static int virDomainMigrateUnmanagedProto2(virDomainPtr domain, const char *dconnuri, virTypedParameterPtr params, int nparams, unsigned int flags) { /* uri parameter is added for direct case */ const char *compatParams[] = { VIR_MIGRATE_PARAM_DEST_NAME, VIR_MIGRATE_PARAM_BANDWIDTH, VIR_MIGRATE_PARAM_URI }; const char *uri = NULL; const char *miguri = NULL; const char *dname = NULL; unsigned long long bandwidth = 0; if (!virTypedParamsCheck(params, nparams, compatParams, ARRAY_CARDINALITY(compatParams))) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Some parameters are not supported by migration " "protocol 2")); return -1; } if (virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_URI, &miguri) < 0 || virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_NAME, &dname) < 0 || virTypedParamsGetULLong(params, nparams, VIR_MIGRATE_PARAM_BANDWIDTH, &bandwidth) < 0) { return -1; } if (flags & VIR_MIGRATE_PEER2PEER) { if (miguri) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unable to override peer2peer migration URI")); return -1; } uri = dconnuri; } else { uri = miguri; } return domain->conn->driver->domainMigratePerform (domain, NULL, 0, uri, flags, dname, bandwidth); } static int virDomainMigrateUnmanagedProto3(virDomainPtr domain, const char *dconnuri, virTypedParameterPtr params, int nparams, unsigned int flags) { const char *compatParams[] = { VIR_MIGRATE_PARAM_URI, VIR_MIGRATE_PARAM_DEST_NAME, VIR_MIGRATE_PARAM_DEST_XML, VIR_MIGRATE_PARAM_BANDWIDTH }; const char *miguri = NULL; const char *dname = NULL; const char *xmlin = NULL; unsigned long long bandwidth = 0; if (!virTypedParamsCheck(params, nparams, compatParams, ARRAY_CARDINALITY(compatParams))) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Some parameters are not supported by migration " "protocol 3")); return -1; } if (virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_URI, &miguri) < 0 || virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_NAME, &dname) < 0 || virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_XML, &xmlin) < 0 || virTypedParamsGetULLong(params, nparams, VIR_MIGRATE_PARAM_BANDWIDTH, &bandwidth) < 0) { return -1; } return domain->conn->driver->domainMigratePerform3 (domain, xmlin, NULL, 0, NULL, NULL, dconnuri, miguri, flags, dname, bandwidth); } /* * In normal migration, the libvirt client co-ordinates communication * between the 2 libvirtd instances on source & dest hosts. * * This function encapsulates 2 alternatives to the above case. * * 1. peer-2-peer migration, the libvirt client only talks to the source * libvirtd instance. The source libvirtd then opens its own * connection to the destination and co-ordinates migration itself. * * 2. direct migration, where there is no requirement for a libvirtd instance * on the dest host. Eg, XenD can talk direct to XenD, so libvirtd on dest * does not need to be involved at all, or even running. */ static int virDomainMigrateUnmanagedParams(virDomainPtr domain, const char *dconnuri, virTypedParameterPtr params, int nparams, unsigned int flags) { VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, params=%p, nparams=%d, flags=%x", NULLSTR(dconnuri), params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); if ((flags & VIR_MIGRATE_PEER2PEER) && virDomainMigrateCheckNotLocal(dconnuri) < 0) return -1; if ((flags & VIR_MIGRATE_PEER2PEER) && VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_PARAMS)) { VIR_DEBUG("Using migration protocol 3 with extensible parameters"); if (!domain->conn->driver->domainMigratePerform3Params) { virReportUnsupportedError(); return -1; } return domain->conn->driver->domainMigratePerform3Params (domain, dconnuri, params, nparams, NULL, 0, NULL, NULL, flags); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V3)) { VIR_DEBUG("Using migration protocol 3"); if (!domain->conn->driver->domainMigratePerform3) { virReportUnsupportedError(); return -1; } return virDomainMigrateUnmanagedProto3(domain, dconnuri, params, nparams, flags); } else { VIR_DEBUG("Using migration protocol 2"); if (!domain->conn->driver->domainMigratePerform) { virReportUnsupportedError(); return -1; } return virDomainMigrateUnmanagedProto2(domain, dconnuri, params, nparams, flags); } } static int virDomainMigrateUnmanaged(virDomainPtr domain, const char *xmlin, unsigned int flags, const char *dname, const char *dconnuri, const char *miguri, unsigned long long bandwidth) { int ret = -1; virTypedParameterPtr params = NULL; int nparams = 0; int maxparams = 0; if (miguri && virTypedParamsAddString(&params, &nparams, &maxparams, VIR_MIGRATE_PARAM_URI, miguri) < 0) goto cleanup; if (dname && virTypedParamsAddString(&params, &nparams, &maxparams, VIR_MIGRATE_PARAM_DEST_NAME, dname) < 0) goto cleanup; if (xmlin && virTypedParamsAddString(&params, &nparams, &maxparams, VIR_MIGRATE_PARAM_DEST_XML, xmlin) < 0) goto cleanup; if (virTypedParamsAddULLong(&params, &nparams, &maxparams, VIR_MIGRATE_PARAM_BANDWIDTH, bandwidth) < 0) goto cleanup; ret = virDomainMigrateUnmanagedParams(domain, dconnuri, params, nparams, flags); cleanup: virTypedParamsFree(params, nparams); return ret; } /** * virDomainMigrate: * @domain: a domain object * @dconn: destination host (a connection object) * @flags: bitwise-OR of virDomainMigrateFlags * @dname: (optional) rename domain to this at destination * @uri: (optional) dest hostname/URI as seen from the source host * @bandwidth: (optional) specify migration bandwidth limit in MiB/s * * Migrate the domain object from its current host to the destination * host given by dconn (a connection to the destination host). * * Flags may be one of more of the following: * VIR_MIGRATE_LIVE Do not pause the VM during migration * VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts * VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel * VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain * on the destination host. * VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the * domain on the source host. * VIR_MIGRATE_PAUSED Leave the domain suspended on the remote side. * VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full * disk copy * VIR_MIGRATE_NON_SHARED_INC Migration with non-shared storage with * incremental disk copy * VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration * changes during the migration process (set * automatically when supported). * VIR_MIGRATE_UNSAFE Force migration even if it is considered unsafe. * VIR_MIGRATE_OFFLINE Migrate offline * * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set. * Applications using the VIR_MIGRATE_PEER2PEER flag will probably * prefer to invoke virDomainMigrateToURI, avoiding the need to * open connection to the destination host themselves. * * If a hypervisor supports renaming domains during migration, * then you may set the dname parameter to the new name (otherwise * it keeps the same name). If this is not supported by the * hypervisor, dname must be NULL or else you will get an error. * * If the VIR_MIGRATE_PEER2PEER flag is set, the uri parameter * must be a valid libvirt connection URI, by which the source * libvirt driver can connect to the destination libvirt. If * omitted, the dconn connection object will be queried for its * current URI. * * If the VIR_MIGRATE_PEER2PEER flag is NOT set, the URI parameter * takes a hypervisor specific format. The hypervisor capabilities * XML includes details of the support URI schemes. If omitted * the dconn will be asked for a default URI. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * * In either case it is typically only necessary to specify a * URI if the destination host has multiple interfaces and a * specific interface is required to transmit migration data. * * The maximum bandwidth (in MiB/s) that will be used to do migration * can be specified with the bandwidth parameter. If set to 0, * libvirt will choose a suitable default. Some hypervisors do * not support this feature and will return an error if bandwidth * is not 0. * * To see which features are supported by the current hypervisor, * see virConnectGetCapabilities, /capabilities/host/migration_features. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * virDomainFree should be used to free the resources after the * returned domain object is no longer needed. * * Returns the new domain object if the migration was successful, * or NULL in case of error. Note that the new domain object * exists in the scope of the destination connection (dconn). */ virDomainPtr virDomainMigrate(virDomainPtr domain, virConnectPtr dconn, unsigned long flags, const char *dname, const char *uri, unsigned long bandwidth) { virDomainPtr ddomain = NULL; VIR_DOMAIN_DEBUG(domain, "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu", dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, NULL); virCheckReadOnlyGoto(domain->conn->flags, error); /* Now checkout the destination */ virCheckConnectGoto(dconn, error); virCheckReadOnlyGoto(dconn->flags, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_NON_SHARED_DISK, VIR_MIGRATE_NON_SHARED_INC, error); if (flags & VIR_MIGRATE_OFFLINE) { if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the source host")); goto error; } if (!VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the destination host")); goto error; } } if (flags & VIR_MIGRATE_PEER2PEER) { if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_P2P)) { char *dstURI = NULL; if (uri == NULL) { dstURI = virConnectGetURI(dconn); if (!dstURI) return NULL; } VIR_DEBUG("Using peer2peer migration"); if (virDomainMigrateUnmanaged(domain, NULL, flags, dname, uri ? uri : dstURI, NULL, bandwidth) < 0) { VIR_FREE(dstURI); goto error; } VIR_FREE(dstURI); ddomain = virDomainLookupByName(dconn, dname ? dname : domain->name); } else { /* This driver does not support peer to peer migration */ virReportUnsupportedError(); goto error; } } else { /* Change protection requires support only on source side, and * is only needed in v3 migration, which automatically re-adds * the flag for just the source side. We mask it out for * non-peer2peer to allow migration from newer source to an * older destination that rejects the flag. */ if (flags & VIR_MIGRATE_CHANGE_PROTECTION && !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("cannot enforce change protection")); goto error; } flags &= ~VIR_MIGRATE_CHANGE_PROTECTION; if (flags & VIR_MIGRATE_TUNNELLED) { virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("cannot perform tunnelled migration without using peer2peer flag")); goto error; } /* Check that migration is supported by both drivers. */ if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V3) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V3)) { VIR_DEBUG("Using migration protocol 3"); ddomain = virDomainMigrateVersion3(domain, dconn, NULL, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V2) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V2)) { VIR_DEBUG("Using migration protocol 2"); ddomain = virDomainMigrateVersion2(domain, dconn, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V1) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V1)) { VIR_DEBUG("Using migration protocol 1"); ddomain = virDomainMigrateVersion1(domain, dconn, flags, dname, uri, bandwidth); } else { /* This driver does not support any migration method */ virReportUnsupportedError(); goto error; } } if (ddomain == NULL) goto error; return ddomain; error: virDispatchError(domain->conn); return NULL; } /** * virDomainMigrate2: * @domain: a domain object * @dconn: destination host (a connection object) * @flags: bitwise-OR of virDomainMigrateFlags * @dxml: (optional) XML config for launching guest on target * @dname: (optional) rename domain to this at destination * @uri: (optional) dest hostname/URI as seen from the source host * @bandwidth: (optional) specify migration bandwidth limit in MiB/s * * Migrate the domain object from its current host to the destination * host given by dconn (a connection to the destination host). * * Flags may be one of more of the following: * VIR_MIGRATE_LIVE Do not pause the VM during migration * VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts * VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel * VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain * on the destination host. * VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the * domain on the source host. * VIR_MIGRATE_PAUSED Leave the domain suspended on the remote side. * VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full * disk copy * VIR_MIGRATE_NON_SHARED_INC Migration with non-shared storage with * incremental disk copy * VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration * changes during the migration process (set * automatically when supported). * VIR_MIGRATE_UNSAFE Force migration even if it is considered unsafe. * VIR_MIGRATE_OFFLINE Migrate offline * * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set. * Applications using the VIR_MIGRATE_PEER2PEER flag will probably * prefer to invoke virDomainMigrateToURI, avoiding the need to * open connection to the destination host themselves. * * If a hypervisor supports renaming domains during migration, * then you may set the dname parameter to the new name (otherwise * it keeps the same name). If this is not supported by the * hypervisor, dname must be NULL or else you will get an error. * * If the VIR_MIGRATE_PEER2PEER flag is set, the uri parameter * must be a valid libvirt connection URI, by which the source * libvirt driver can connect to the destination libvirt. If * omitted, the dconn connection object will be queried for its * current URI. * * If the VIR_MIGRATE_PEER2PEER flag is NOT set, the URI parameter * takes a hypervisor specific format. The hypervisor capabilities * XML includes details of the support URI schemes. If omitted * the dconn will be asked for a default URI. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * * In either case it is typically only necessary to specify a * URI if the destination host has multiple interfaces and a * specific interface is required to transmit migration data. * * The maximum bandwidth (in MiB/s) that will be used to do migration * can be specified with the bandwidth parameter. If set to 0, * libvirt will choose a suitable default. Some hypervisors do * not support this feature and will return an error if bandwidth * is not 0. * * To see which features are supported by the current hypervisor, * see virConnectGetCapabilities, /capabilities/host/migration_features. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * If the hypervisor supports it, @dxml can be used to alter * host-specific portions of the domain XML that will be used on * the destination. For example, it is possible to alter the * backing filename that is associated with a disk device, in order * to account for naming differences between source and destination * in accessing the underlying storage. The migration will fail * if @dxml would cause any guest-visible changes. Pass NULL * if no changes are needed to the XML between source and destination. * @dxml cannot be used to rename the domain during migration (use * @dname for that purpose). Domain name in @dxml must match the * original domain name. * * virDomainFree should be used to free the resources after the * returned domain object is no longer needed. * * Returns the new domain object if the migration was successful, * or NULL in case of error. Note that the new domain object * exists in the scope of the destination connection (dconn). */ virDomainPtr virDomainMigrate2(virDomainPtr domain, virConnectPtr dconn, const char *dxml, unsigned long flags, const char *dname, const char *uri, unsigned long bandwidth) { virDomainPtr ddomain = NULL; VIR_DOMAIN_DEBUG(domain, "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu", dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, NULL); virCheckReadOnlyGoto(domain->conn->flags, error); /* Now checkout the destination */ virCheckConnectGoto(dconn, error); virCheckReadOnlyGoto(dconn->flags, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_NON_SHARED_DISK, VIR_MIGRATE_NON_SHARED_INC, error); if (flags & VIR_MIGRATE_OFFLINE) { if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the source host")); goto error; } if (!VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the destination host")); goto error; } } if (flags & VIR_MIGRATE_PEER2PEER) { if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_P2P)) { char *dstURI = virConnectGetURI(dconn); if (!dstURI) return NULL; VIR_DEBUG("Using peer2peer migration"); if (virDomainMigrateUnmanaged(domain, dxml, flags, dname, dstURI, uri, bandwidth) < 0) { VIR_FREE(dstURI); goto error; } VIR_FREE(dstURI); ddomain = virDomainLookupByName(dconn, dname ? dname : domain->name); } else { /* This driver does not support peer to peer migration */ virReportUnsupportedError(); goto error; } } else { /* Change protection requires support only on source side, and * is only needed in v3 migration, which automatically re-adds * the flag for just the source side. We mask it out for * non-peer2peer to allow migration from newer source to an * older destination that rejects the flag. */ if (flags & VIR_MIGRATE_CHANGE_PROTECTION && !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("cannot enforce change protection")); goto error; } flags &= ~VIR_MIGRATE_CHANGE_PROTECTION; if (flags & VIR_MIGRATE_TUNNELLED) { virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("cannot perform tunnelled migration without using peer2peer flag")); goto error; } /* Check that migration is supported by both drivers. */ if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V3) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V3)) { VIR_DEBUG("Using migration protocol 3"); ddomain = virDomainMigrateVersion3(domain, dconn, dxml, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V2) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V2)) { VIR_DEBUG("Using migration protocol 2"); if (dxml) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Unable to change target guest XML during migration")); goto error; } ddomain = virDomainMigrateVersion2(domain, dconn, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V1) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V1)) { VIR_DEBUG("Using migration protocol 1"); if (dxml) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Unable to change target guest XML during migration")); goto error; } ddomain = virDomainMigrateVersion1(domain, dconn, flags, dname, uri, bandwidth); } else { /* This driver does not support any migration method */ virReportUnsupportedError(); goto error; } } if (ddomain == NULL) goto error; return ddomain; error: virDispatchError(domain->conn); return NULL; } /** * virDomainMigrate3: * @domain: a domain object * @dconn: destination host (a connection object) * @params: (optional) migration parameters * @nparams: (optional) number of migration parameters in @params * @flags: bitwise-OR of virDomainMigrateFlags * * Migrate the domain object from its current host to the destination host * given by dconn (a connection to the destination host). * * See virDomainMigrateFlags documentation for description of individual flags. * * VIR_MIGRATE_TUNNELLED and VIR_MIGRATE_PEER2PEER are not supported by this * API, use virDomainMigrateToURI3 instead. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * virDomainFree should be used to free the resources after the * returned domain object is no longer needed. * * Returns the new domain object if the migration was successful, * or NULL in case of error. Note that the new domain object * exists in the scope of the destination connection (dconn). */ virDomainPtr virDomainMigrate3(virDomainPtr domain, virConnectPtr dconn, virTypedParameterPtr params, unsigned int nparams, unsigned int flags) { virDomainPtr ddomain = NULL; const char *compatParams[] = { VIR_MIGRATE_PARAM_URI, VIR_MIGRATE_PARAM_DEST_NAME, VIR_MIGRATE_PARAM_DEST_XML, VIR_MIGRATE_PARAM_BANDWIDTH }; const char *uri = NULL; const char *dname = NULL; const char *dxml = NULL; unsigned long long bandwidth = 0; VIR_DOMAIN_DEBUG(domain, "dconn=%p, params=%p, nparms=%u flags=%x", dconn, params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, NULL); virCheckReadOnlyGoto(domain->conn->flags, error); /* Now checkout the destination */ virCheckReadOnlyGoto(dconn->flags, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_NON_SHARED_DISK, VIR_MIGRATE_NON_SHARED_INC, error); if (flags & VIR_MIGRATE_PEER2PEER) { virReportInvalidArg(flags, "%s", _("use virDomainMigrateToURI3 for peer-to-peer " "migration")); goto error; } if (flags & VIR_MIGRATE_TUNNELLED) { virReportInvalidArg(flags, "%s", _("cannot perform tunnelled migration " "without using peer2peer flag")); goto error; } if (flags & VIR_MIGRATE_OFFLINE) { if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the source host")); goto error; } if (!VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the destination host")); goto error; } } /* Change protection requires support only on source side, and * is only needed in v3 migration, which automatically re-adds * the flag for just the source side. We mask it out to allow * migration from newer source to an older destination that * rejects the flag. */ if (flags & VIR_MIGRATE_CHANGE_PROTECTION && !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("cannot enforce change protection")); goto error; } flags &= ~VIR_MIGRATE_CHANGE_PROTECTION; /* Prefer extensible API but fall back to older migration APIs if params * only contains parameters which were supported by the older API. */ if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_PARAMS) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_PARAMS)) { VIR_DEBUG("Using migration protocol 3 with extensible parameters"); ddomain = virDomainMigrateVersion3Params(domain, dconn, params, nparams, flags); goto done; } if (!virTypedParamsCheck(params, nparams, compatParams, ARRAY_CARDINALITY(compatParams))) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Migration APIs with extensible parameters are not " "supported but extended parameters were passed")); goto error; } if (virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_URI, &uri) < 0 || virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_NAME, &dname) < 0 || virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_XML, &dxml) < 0 || virTypedParamsGetULLong(params, nparams, VIR_MIGRATE_PARAM_BANDWIDTH, &bandwidth) < 0) { goto error; } if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V3) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V3)) { VIR_DEBUG("Using migration protocol 3"); ddomain = virDomainMigrateVersion3(domain, dconn, dxml, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V2) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V2)) { VIR_DEBUG("Using migration protocol 2"); if (dxml) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Unable to change target guest XML during " "migration")); goto error; } ddomain = virDomainMigrateVersion2(domain, dconn, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V1) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V1)) { VIR_DEBUG("Using migration protocol 1"); if (dxml) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Unable to change target guest XML during " "migration")); goto error; } ddomain = virDomainMigrateVersion1(domain, dconn, flags, dname, uri, bandwidth); } else { /* This driver does not support any migration method */ virReportUnsupportedError(); goto error; } done: if (ddomain == NULL) goto error; return ddomain; error: virDispatchError(domain->conn); return NULL; } static int virDomainMigrateUnmanagedCheckCompat(virDomainPtr domain, unsigned int flags) { VIR_EXCLUSIVE_FLAGS_RET(VIR_MIGRATE_NON_SHARED_DISK, VIR_MIGRATE_NON_SHARED_INC, -1); if (flags & VIR_MIGRATE_OFFLINE && !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the source host")); return -1; } if (flags & VIR_MIGRATE_PEER2PEER) { if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_P2P)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("p2p migration is not supported by " "the source host")); return -1; } } else { if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_DIRECT)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("direct migration is not supported by " "the source host")); return -1; } } return 0; } /** * virDomainMigrateToURI: * @domain: a domain object * @duri: mandatory URI for the destination host * @flags: bitwise-OR of virDomainMigrateFlags * @dname: (optional) rename domain to this at destination * @bandwidth: (optional) specify migration bandwidth limit in MiB/s * * Migrate the domain object from its current host to the destination * host given by duri. * * Flags may be one of more of the following: * VIR_MIGRATE_LIVE Do not pause the VM during migration * VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts * VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel * VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain * on the destination host. * VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the * domain on the source host. * VIR_MIGRATE_PAUSED Leave the domain suspended on the remote side. * VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full * disk copy * VIR_MIGRATE_NON_SHARED_INC Migration with non-shared storage with * incremental disk copy * VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration * changes during the migration process (set * automatically when supported). * VIR_MIGRATE_UNSAFE Force migration even if it is considered unsafe. * VIR_MIGRATE_OFFLINE Migrate offline * * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag. * If the VIR_MIGRATE_PEER2PEER flag is NOT set, the duri parameter * takes a hypervisor specific format. The uri_transports element of the * hypervisor capabilities XML includes details of the supported URI * schemes. Not all hypervisors will support this mode of migration, so * if the VIR_MIGRATE_PEER2PEER flag is not set, then it may be necessary * to use the alternative virDomainMigrate API providing and explicit * virConnectPtr for the destination host. * * If the VIR_MIGRATE_PEER2PEER flag IS set, the duri parameter * must be a valid libvirt connection URI, by which the source * libvirt driver can connect to the destination libvirt. * * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * * If a hypervisor supports renaming domains during migration, * the dname parameter specifies the new name for the domain. * Setting dname to NULL keeps the domain name the same. If domain * renaming is not supported by the hypervisor, dname must be NULL or * else an error will be returned. * * The maximum bandwidth (in MiB/s) that will be used to do migration * can be specified with the bandwidth parameter. If set to 0, * libvirt will choose a suitable default. Some hypervisors do * not support this feature and will return an error if bandwidth * is not 0. * * To see which features are supported by the current hypervisor, * see virConnectGetCapabilities, /capabilities/host/migration_features. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * Returns 0 if the migration succeeded, -1 upon error. */ int virDomainMigrateToURI(virDomainPtr domain, const char *duri, unsigned long flags, const char *dname, unsigned long bandwidth) { const char *dconnuri = NULL; const char *miguri = NULL; VIR_DOMAIN_DEBUG(domain, "duri=%p, flags=%lx, dname=%s, bandwidth=%lu", NULLSTR(duri), flags, NULLSTR(dname), bandwidth); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); virCheckNonNullArgGoto(duri, error); if (virDomainMigrateUnmanagedCheckCompat(domain, flags) < 0) goto error; if (flags & VIR_MIGRATE_PEER2PEER) dconnuri = duri; else miguri = duri; if (virDomainMigrateUnmanaged(domain, NULL, flags, dname, dconnuri, miguri, bandwidth) < 0) goto error; return 0; error: virDispatchError(domain->conn); return -1; } /** * virDomainMigrateToURI2: * @domain: a domain object * @dconnuri: (optional) URI for target libvirtd if @flags includes VIR_MIGRATE_PEER2PEER * @miguri: (optional) URI for invoking the migration, not if @flags includs VIR_MIGRATE_TUNNELLED * @dxml: (optional) XML config for launching guest on target * @flags: bitwise-OR of virDomainMigrateFlags * @dname: (optional) rename domain to this at destination * @bandwidth: (optional) specify migration bandwidth limit in MiB/s * * Migrate the domain object from its current host to the destination * host given by duri. * * Flags may be one of more of the following: * VIR_MIGRATE_LIVE Do not pause the VM during migration * VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts * VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel * VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain * on the destination host. * VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the * domain on the source host. * VIR_MIGRATE_PAUSED Leave the domain suspended on the remote side. * VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full * disk copy * VIR_MIGRATE_NON_SHARED_INC Migration with non-shared storage with * incremental disk copy * VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration * changes during the migration process (set * automatically when supported). * VIR_MIGRATE_UNSAFE Force migration even if it is considered unsafe. * VIR_MIGRATE_OFFLINE Migrate offline * * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag. * * If the VIR_MIGRATE_PEER2PEER flag is set, the @dconnuri parameter * must be a valid libvirt connection URI, by which the source * libvirt driver can connect to the destination libvirt. If the * VIR_MIGRATE_PEER2PEER flag is NOT set, then @dconnuri must be * NULL. * * If the VIR_MIGRATE_TUNNELLED flag is NOT set, then the @miguri * parameter allows specification of a URI to use to initiate the * VM migration. It takes a hypervisor specific format. The uri_transports * element of the hypervisor capabilities XML includes details of the * supported URI schemes. * * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * As of 1.2.11 disks of some types ('file' and 'volume') are * precreated automatically, if there's a pool defined on the * destination for the disk path. * * If a hypervisor supports changing the configuration of the guest * during migration, the @dxml parameter specifies the new config * for the guest. The configuration must include an identical set * of virtual devices, to ensure a stable guest ABI across migration. * Only parameters related to host side configuration can be * changed in the XML. Hypervisors will validate this and refuse to * allow migration if the provided XML would cause a change in the * guest ABI, * * If a hypervisor supports renaming domains during migration, * the dname parameter specifies the new name for the domain. * Setting dname to NULL keeps the domain name the same. If domain * renaming is not supported by the hypervisor, dname must be NULL or * else an error will be returned. * * The maximum bandwidth (in MiB/s) that will be used to do migration * can be specified with the bandwidth parameter. If set to 0, * libvirt will choose a suitable default. Some hypervisors do * not support this feature and will return an error if bandwidth * is not 0. * * To see which features are supported by the current hypervisor, * see virConnectGetCapabilities, /capabilities/host/migration_features. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * Returns 0 if the migration succeeded, -1 upon error. */ int virDomainMigrateToURI2(virDomainPtr domain, const char *dconnuri, const char *miguri, const char *dxml, unsigned long flags, const char *dname, unsigned long bandwidth) { VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, miguri=%s, dxml=%s, " "flags=%lx, dname=%s, bandwidth=%lu", NULLSTR(dconnuri), NULLSTR(miguri), NULLSTR(dxml), flags, NULLSTR(dname), bandwidth); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); if (virDomainMigrateUnmanagedCheckCompat(domain, flags) < 0) goto error; if (flags & VIR_MIGRATE_PEER2PEER) virCheckNonNullArgGoto(dconnuri, error); else dconnuri = NULL; if (virDomainMigrateUnmanaged(domain, dxml, flags, dname, dconnuri, miguri, bandwidth) < 0) goto error; return 0; error: virDispatchError(domain->conn); return -1; } /** * virDomainMigrateToURI3: * @domain: a domain object * @dconnuri: (optional) URI for target libvirtd if @flags includes VIR_MIGRATE_PEER2PEER * @params: (optional) migration parameters * @nparams: (optional) number of migration parameters in @params * @flags: bitwise-OR of virDomainMigrateFlags * * Migrate the domain object from its current host to the destination host * given by URI. * * See virDomainMigrateFlags documentation for description of individual flags. * * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag. * * If the VIR_MIGRATE_PEER2PEER flag is set, the @dconnuri parameter must be a * valid libvirt connection URI, by which the source libvirt daemon can connect * to the destination libvirt. * * If the VIR_MIGRATE_PEER2PEER flag is NOT set, then @dconnuri must be NULL * and VIR_MIGRATE_PARAM_URI migration parameter must be filled in with * hypervisor specific URI used to initiate the migration. This is called * "direct" migration. * * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * Returns 0 if the migration succeeded, -1 upon error. */ int virDomainMigrateToURI3(virDomainPtr domain, const char *dconnuri, virTypedParameterPtr params, unsigned int nparams, unsigned int flags) { VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, params=%p, nparms=%u flags=%x", NULLSTR(dconnuri), params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); if (virDomainMigrateUnmanagedCheckCompat(domain, flags) < 0) goto error; if (flags & VIR_MIGRATE_PEER2PEER) virCheckNonNullArgGoto(dconnuri, error); else dconnuri = NULL; if (virDomainMigrateUnmanagedParams(domain, dconnuri, params, nparams, flags) < 0) goto error; return 0; error: virDispatchError(domain->conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepare(virConnectPtr dconn, char **cookie, int *cookielen, const char *uri_in, char **uri_out, unsigned long flags, const char *dname, unsigned long bandwidth) { VIR_DEBUG("dconn=%p, cookie=%p, cookielen=%p, uri_in=%s, uri_out=%p, " "flags=%lx, dname=%s, bandwidth=%lu", dconn, cookie, cookielen, NULLSTR(uri_in), uri_out, flags, NULLSTR(dname), bandwidth); virResetLastError(); virCheckConnectReturn(dconn, -1); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigratePrepare) { int ret; ret = dconn->driver->domainMigratePrepare(dconn, cookie, cookielen, uri_in, uri_out, flags, dname, bandwidth); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePerform(virDomainPtr domain, const char *cookie, int cookielen, const char *uri, unsigned long flags, const char *dname, unsigned long bandwidth) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cookie=%p, cookielen=%d, uri=%s, flags=%lx, " "dname=%s, bandwidth=%lu", cookie, cookielen, uri, flags, NULLSTR(dname), bandwidth); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigratePerform) { int ret; ret = conn->driver->domainMigratePerform(domain, cookie, cookielen, uri, flags, dname, bandwidth); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ virDomainPtr virDomainMigrateFinish(virConnectPtr dconn, const char *dname, const char *cookie, int cookielen, const char *uri, unsigned long flags) { VIR_DEBUG("dconn=%p, dname=%s, cookie=%p, cookielen=%d, uri=%s, " "flags=%lx", dconn, NULLSTR(dname), cookie, cookielen, NULLSTR(uri), flags); virResetLastError(); virCheckConnectReturn(dconn, NULL); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigrateFinish) { virDomainPtr ret; ret = dconn->driver->domainMigrateFinish(dconn, dname, cookie, cookielen, uri, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepare2(virConnectPtr dconn, char **cookie, int *cookielen, const char *uri_in, char **uri_out, unsigned long flags, const char *dname, unsigned long bandwidth, const char *dom_xml) { VIR_DEBUG("dconn=%p, cookie=%p, cookielen=%p, uri_in=%s, uri_out=%p," "flags=%lx, dname=%s, bandwidth=%lu, dom_xml=%s", dconn, cookie, cookielen, NULLSTR(uri_in), uri_out, flags, NULLSTR(dname), bandwidth, NULLSTR(dom_xml)); virResetLastError(); virCheckConnectReturn(dconn, -1); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigratePrepare2) { int ret; ret = dconn->driver->domainMigratePrepare2(dconn, cookie, cookielen, uri_in, uri_out, flags, dname, bandwidth, dom_xml); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ virDomainPtr virDomainMigrateFinish2(virConnectPtr dconn, const char *dname, const char *cookie, int cookielen, const char *uri, unsigned long flags, int retcode) { VIR_DEBUG("dconn=%p, dname=%s, cookie=%p, cookielen=%d, uri=%s, " "flags=%lx, retcode=%d", dconn, NULLSTR(dname), cookie, cookielen, NULLSTR(uri), flags, retcode); virResetLastError(); virCheckConnectReturn(dconn, NULL); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigrateFinish2) { virDomainPtr ret; ret = dconn->driver->domainMigrateFinish2(dconn, dname, cookie, cookielen, uri, flags, retcode); if (!ret && !retcode) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepareTunnel(virConnectPtr conn, virStreamPtr st, unsigned long flags, const char *dname, unsigned long bandwidth, const char *dom_xml) { VIR_DEBUG("conn=%p, stream=%p, flags=%lx, dname=%s, " "bandwidth=%lu, dom_xml=%s", conn, st, flags, NULLSTR(dname), bandwidth, NULLSTR(dom_xml)); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); if (conn != st->conn) { virReportInvalidArg(conn, "%s", _("conn must match stream connection")); goto error; } if (conn->driver->domainMigratePrepareTunnel) { int rv = conn->driver->domainMigratePrepareTunnel(conn, st, flags, dname, bandwidth, dom_xml); if (rv < 0) goto error; return rv; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ char * virDomainMigrateBegin3(virDomainPtr domain, const char *xmlin, char **cookieout, int *cookieoutlen, unsigned long flags, const char *dname, unsigned long bandwidth) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xmlin=%s cookieout=%p, cookieoutlen=%p, " "flags=%lx, dname=%s, bandwidth=%lu", NULLSTR(xmlin), cookieout, cookieoutlen, flags, NULLSTR(dname), bandwidth); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateBegin3) { char *xml; xml = conn->driver->domainMigrateBegin3(domain, xmlin, cookieout, cookieoutlen, flags, dname, bandwidth); VIR_DEBUG("xml %s", NULLSTR(xml)); if (!xml) goto error; return xml; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepare3(virConnectPtr dconn, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, const char *uri_in, char **uri_out, unsigned long flags, const char *dname, unsigned long bandwidth, const char *dom_xml) { VIR_DEBUG("dconn=%p, cookiein=%p, cookieinlen=%d, cookieout=%p, " "cookieoutlen=%p, uri_in=%s, uri_out=%p, flags=%lx, dname=%s, " "bandwidth=%lu, dom_xml=%s", dconn, cookiein, cookieinlen, cookieout, cookieoutlen, NULLSTR(uri_in), uri_out, flags, NULLSTR(dname), bandwidth, NULLSTR(dom_xml)); virResetLastError(); virCheckConnectReturn(dconn, -1); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigratePrepare3) { int ret; ret = dconn->driver->domainMigratePrepare3(dconn, cookiein, cookieinlen, cookieout, cookieoutlen, uri_in, uri_out, flags, dname, bandwidth, dom_xml); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepareTunnel3(virConnectPtr conn, virStreamPtr st, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned long flags, const char *dname, unsigned long bandwidth, const char *dom_xml) { VIR_DEBUG("conn=%p, stream=%p, cookiein=%p, cookieinlen=%d, cookieout=%p, " "cookieoutlen=%p, flags=%lx, dname=%s, bandwidth=%lu, " "dom_xml=%s", conn, st, cookiein, cookieinlen, cookieout, cookieoutlen, flags, NULLSTR(dname), bandwidth, NULLSTR(dom_xml)); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); if (conn != st->conn) { virReportInvalidArg(conn, "%s", _("conn must match stream connection")); goto error; } if (conn->driver->domainMigratePrepareTunnel3) { int rv = conn->driver->domainMigratePrepareTunnel3(conn, st, cookiein, cookieinlen, cookieout, cookieoutlen, flags, dname, bandwidth, dom_xml); if (rv < 0) goto error; return rv; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePerform3(virDomainPtr domain, const char *xmlin, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, const char *dconnuri, const char *uri, unsigned long flags, const char *dname, unsigned long bandwidth) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xmlin=%s cookiein=%p, cookieinlen=%d, " "cookieout=%p, cookieoutlen=%p, dconnuri=%s, " "uri=%s, flags=%lx, dname=%s, bandwidth=%lu", NULLSTR(xmlin), cookiein, cookieinlen, cookieout, cookieoutlen, NULLSTR(dconnuri), NULLSTR(uri), flags, NULLSTR(dname), bandwidth); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigratePerform3) { int ret; ret = conn->driver->domainMigratePerform3(domain, xmlin, cookiein, cookieinlen, cookieout, cookieoutlen, dconnuri, uri, flags, dname, bandwidth); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ virDomainPtr virDomainMigrateFinish3(virConnectPtr dconn, const char *dname, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, const char *dconnuri, const char *uri, unsigned long flags, int cancelled) { VIR_DEBUG("dconn=%p, dname=%s, cookiein=%p, cookieinlen=%d, cookieout=%p," "cookieoutlen=%p, dconnuri=%s, uri=%s, flags=%lx, retcode=%d", dconn, NULLSTR(dname), cookiein, cookieinlen, cookieout, cookieoutlen, NULLSTR(dconnuri), NULLSTR(uri), flags, cancelled); virResetLastError(); virCheckConnectReturn(dconn, NULL); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigrateFinish3) { virDomainPtr ret; ret = dconn->driver->domainMigrateFinish3(dconn, dname, cookiein, cookieinlen, cookieout, cookieoutlen, dconnuri, uri, flags, cancelled); if (!ret && !cancelled) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigrateConfirm3(virDomainPtr domain, const char *cookiein, int cookieinlen, unsigned long flags, int cancelled) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cookiein=%p, cookieinlen=%d, flags=%lx, cancelled=%d", cookiein, cookieinlen, flags, cancelled); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateConfirm3) { int ret; ret = conn->driver->domainMigrateConfirm3(domain, cookiein, cookieinlen, flags, cancelled); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ char * virDomainMigrateBegin3Params(virDomainPtr domain, virTypedParameterPtr params, int nparams, char **cookieout, int *cookieoutlen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, " "cookieout=%p, cookieoutlen=%p, flags=%x", params, nparams, cookieout, cookieoutlen, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateBegin3Params) { char *xml; xml = conn->driver->domainMigrateBegin3Params(domain, params, nparams, cookieout, cookieoutlen, flags); VIR_DEBUG("xml %s", NULLSTR(xml)); if (!xml) goto error; return xml; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepare3Params(virConnectPtr dconn, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, char **uri_out, unsigned int flags) { VIR_DEBUG("dconn=%p, params=%p, nparams=%d, cookiein=%p, cookieinlen=%d, " "cookieout=%p, cookieoutlen=%p, uri_out=%p, flags=%x", dconn, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, uri_out, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckConnectReturn(dconn, -1); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigratePrepare3Params) { int ret; ret = dconn->driver->domainMigratePrepare3Params(dconn, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, uri_out, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepareTunnel3Params(virConnectPtr conn, virStreamPtr st, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned int flags) { VIR_DEBUG("conn=%p, stream=%p, params=%p, nparams=%d, cookiein=%p, " "cookieinlen=%d, cookieout=%p, cookieoutlen=%p, flags=%x", conn, st, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); if (conn != st->conn) { virReportInvalidArg(conn, "%s", _("conn must match stream connection")); goto error; } if (conn->driver->domainMigratePrepareTunnel3Params) { int rv; rv = conn->driver->domainMigratePrepareTunnel3Params( conn, st, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags); if (rv < 0) goto error; return rv; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePerform3Params(virDomainPtr domain, const char *dconnuri, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, params=%p, nparams=%d, cookiein=%p, " "cookieinlen=%d, cookieout=%p, cookieoutlen=%p, flags=%x", NULLSTR(dconnuri), params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigratePerform3Params) { int ret; ret = conn->driver->domainMigratePerform3Params( domain, dconnuri, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ virDomainPtr virDomainMigrateFinish3Params(virConnectPtr dconn, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned int flags, int cancelled) { VIR_DEBUG("dconn=%p, params=%p, nparams=%d, cookiein=%p, cookieinlen=%d, " "cookieout=%p, cookieoutlen=%p, flags=%x, cancelled=%d", dconn, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags, cancelled); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckConnectReturn(dconn, NULL); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigrateFinish3Params) { virDomainPtr ret; ret = dconn->driver->domainMigrateFinish3Params( dconn, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags, cancelled); if (!ret && !cancelled) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigrateConfirm3Params(virDomainPtr domain, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, unsigned int flags, int cancelled) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, cookiein=%p, " "cookieinlen=%d, flags=%x, cancelled=%d", params, nparams, cookiein, cookieinlen, flags, cancelled); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateConfirm3Params) { int ret; ret = conn->driver->domainMigrateConfirm3Params( domain, params, nparams, cookiein, cookieinlen, flags, cancelled); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetSchedulerType: * @domain: pointer to domain object * @nparams: pointer to number of scheduler parameters, can be NULL * (return value) * * Get the scheduler type and the number of scheduler parameters. * * Returns NULL in case of error. The caller must free the returned string. */ char * virDomainGetSchedulerType(virDomainPtr domain, int *nparams) { virConnectPtr conn; char *schedtype; VIR_DOMAIN_DEBUG(domain, "nparams=%p", nparams); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; if (conn->driver->domainGetSchedulerType) { schedtype = conn->driver->domainGetSchedulerType(domain, nparams); if (!schedtype) goto error; return schedtype; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virDomainGetSchedulerParameters: * @domain: pointer to domain object * @params: pointer to scheduler parameter objects * (return value) * @nparams: pointer to number of scheduler parameter objects * (this value should generally be as large as the returned value * nparams of virDomainGetSchedulerType()); input and output * * Get all scheduler parameters. On input, @nparams gives the size of the * @params array; on output, @nparams gives how many slots were filled * with parameter information, which might be less but will not exceed * the input value. @nparams cannot be 0. * * It is hypervisor specific whether this returns the live or * persistent state; for more control, use * virDomainGetSchedulerParametersFlags(). * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetSchedulerParameters(virDomainPtr domain, virTypedParameterPtr params, int *nparams) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%p", params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(params, error); virCheckNonNullArgGoto(nparams, error); virCheckPositiveArgGoto(*nparams, error); conn = domain->conn; if (conn->driver->domainGetSchedulerParameters) { int ret; ret = conn->driver->domainGetSchedulerParameters(domain, params, nparams); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetSchedulerParametersFlags: * @domain: pointer to domain object * @params: pointer to scheduler parameter object * (return value) * @nparams: pointer to number of scheduler parameter * (this value should be same than the returned value * nparams of virDomainGetSchedulerType()); input and output * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all scheduler parameters. On input, @nparams gives the size of the * @params array; on output, @nparams gives how many slots were filled * with parameter information, which might be less but will not exceed * the input value. @nparams cannot be 0. * * The value of @flags can be exactly VIR_DOMAIN_AFFECT_CURRENT, * VIR_DOMAIN_AFFECT_LIVE, or VIR_DOMAIN_AFFECT_CONFIG. * * Here is a sample code snippet: * * char *ret = virDomainGetSchedulerType(dom, &nparams); * if (ret && nparams != 0) { * if ((params = malloc(sizeof(*params) * nparams)) == NULL) * goto error; * memset(params, 0, sizeof(*params) * nparams); * if (virDomainGetSchedulerParametersFlags(dom, params, &nparams, 0)) * goto error; * } * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetSchedulerParametersFlags(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%p, flags=%x", params, nparams, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(params, error); virCheckNonNullArgGoto(nparams, error); virCheckPositiveArgGoto(*nparams, error); if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); conn = domain->conn; if (conn->driver->domainGetSchedulerParametersFlags) { int ret; ret = conn->driver->domainGetSchedulerParametersFlags(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetSchedulerParameters: * @domain: pointer to domain object * @params: pointer to scheduler parameter objects * @nparams: number of scheduler parameter objects * (this value can be the same or less than the returned value * nparams of virDomainGetSchedulerType) * * Change all or a subset or the scheduler parameters. It is * hypervisor-specific whether this sets live, persistent, or both * settings; for more control, use * virDomainSetSchedulerParametersFlags. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetSchedulerParameters(virDomainPtr domain, virTypedParameterPtr params, int nparams) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d", params, nparams); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckNonNegativeArgGoto(nparams, error); if (virTypedParameterValidateSet(conn, params, nparams) < 0) goto error; if (conn->driver->domainSetSchedulerParameters) { int ret; ret = conn->driver->domainSetSchedulerParameters(domain, params, nparams); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetSchedulerParametersFlags: * @domain: pointer to domain object * @params: pointer to scheduler parameter objects * @nparams: number of scheduler parameter objects * (this value can be the same or less than the returned value * nparams of virDomainGetSchedulerType) * @flags: bitwise-OR of virDomainModificationImpact * * Change a subset or all scheduler parameters. The value of @flags * should be either VIR_DOMAIN_AFFECT_CURRENT, or a bitwise-or of * values from VIR_DOMAIN_AFFECT_LIVE and * VIR_DOMAIN_AFFECT_CURRENT, although hypervisors vary in which * flags are supported. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetSchedulerParametersFlags(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckNonNegativeArgGoto(nparams, error); if (virTypedParameterValidateSet(conn, params, nparams) < 0) goto error; if (conn->driver->domainSetSchedulerParametersFlags) { int ret; ret = conn->driver->domainSetSchedulerParametersFlags(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainBlockStats: * @dom: pointer to the domain object * @disk: path to the block device, or device shorthand * @stats: block device stats (returned) * @size: size of stats structure * * This function returns block device (disk) stats for block * devices attached to the domain. * * The @disk parameter is either the device target shorthand (the * <target dev='...'/> sub-element, such as "vda"), or (since 0.9.8) * an unambiguous source name of the block device (the <source * file='...'/> sub-element, such as "/path/to/image"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. Some drivers might also * accept the empty string for the @disk parameter, and then yield * summary stats for the entire domain. * * Domains may have more than one block device. To get stats for * each you should make multiple calls to this function. * * Individual fields within the stats structure may be returned * as -1, which indicates that the hypervisor does not support * that particular statistic. * * Returns: 0 in case of success or -1 in case of failure. */ int virDomainBlockStats(virDomainPtr dom, const char *disk, virDomainBlockStatsPtr stats, size_t size) { virConnectPtr conn; virDomainBlockStatsStruct stats2 = { -1, -1, -1, -1, -1 }; VIR_DOMAIN_DEBUG(dom, "disk=%s, stats=%p, size=%zi", disk, stats, size); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(disk, error); virCheckNonNullArgGoto(stats, error); if (size > sizeof(stats2)) { virReportInvalidArg(size, _("size must not exceed %zu"), sizeof(stats2)); goto error; } conn = dom->conn; if (conn->driver->domainBlockStats) { if (conn->driver->domainBlockStats(dom, disk, &stats2) == -1) goto error; memcpy(stats, &stats2, size); return 0; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockStatsFlags: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @params: pointer to block stats parameter object * (return value, allocated by the caller) * @nparams: pointer to number of block stats; input and output * @flags: bitwise-OR of virTypedParameterFlags * * This function is to get block stats parameters for block * devices attached to the domain. * * The @disk parameter is either the device target shorthand (the * <target dev='...'/> sub-element, such as "vda"), or (since 0.9.8) * an unambiguous source name of the block device (the <source * file='...'/> sub-element, such as "/path/to/image"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. Some drivers might also * accept the empty string for the @disk parameter, and then yield * summary stats for the entire domain. * * Domains may have more than one block device. To get stats for * each you should make multiple calls to this function. * * On input, @nparams gives the size of the @params array; on output, * @nparams gives how many slots were filled with parameter * information, which might be less but will not exceed the input * value. * * As a special case, calling with @params as NULL and @nparams as 0 on * input will cause @nparams on output to contain the number of parameters * supported by the hypervisor. (Note that block devices of different types * might support different parameters, so it might be necessary to compute * @nparams for each block device). The caller should then allocate @params * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API * again. See virDomainGetMemoryParameters() for more details. * * Returns -1 in case of error, 0 in case of success. */ int virDomainBlockStatsFlags(virDomainPtr dom, const char *disk, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=%x", disk, params, nparams ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(disk, error); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) virCheckNonNullArgGoto(params, error); if (VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; conn = dom->conn; if (conn->driver->domainBlockStatsFlags) { int ret; ret = conn->driver->domainBlockStatsFlags(dom, disk, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainInterfaceStats: * @dom: pointer to the domain object * @path: path to the interface * @stats: network interface stats (returned) * @size: size of stats structure * * This function returns network interface stats for interfaces * attached to the domain. * * The path parameter is the name of the network interface. * * Domains may have more than one network interface. To get stats for * each you should make multiple calls to this function. * * Individual fields within the stats structure may be returned * as -1, which indicates that the hypervisor does not support * that particular statistic. * * Returns: 0 in case of success or -1 in case of failure. */ int virDomainInterfaceStats(virDomainPtr dom, const char *path, virDomainInterfaceStatsPtr stats, size_t size) { virConnectPtr conn; virDomainInterfaceStatsStruct stats2 = { -1, -1, -1, -1, -1, -1, -1, -1 }; VIR_DOMAIN_DEBUG(dom, "path=%s, stats=%p, size=%zi", path, stats, size); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(path, error); virCheckNonNullArgGoto(stats, error); if (size > sizeof(stats2)) { virReportInvalidArg(size, _("size must not exceed %zu"), sizeof(stats2)); goto error; } conn = dom->conn; if (conn->driver->domainInterfaceStats) { if (conn->driver->domainInterfaceStats(dom, path, &stats2) == -1) goto error; memcpy(stats, &stats2, size); return 0; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainSetInterfaceParameters: * @domain: pointer to domain object * @device: the interface name or mac address * @params: pointer to interface parameter objects * @nparams: number of interface parameter (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainModificationImpact * * Change a subset or all parameters of interface; currently this * includes bandwidth parameters. The value of @flags should be * either VIR_DOMAIN_AFFECT_CURRENT, or a bitwise-or of values * VIR_DOMAIN_AFFECT_LIVE and VIR_DOMAIN_AFFECT_CONFIG, although * hypervisors vary in which flags are supported. * * This function may require privileged access to the hypervisor. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetInterfaceParameters(virDomainPtr domain, const char *device, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "device=%s, params=%p, nparams=%d, flags=%x", device, params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckPositiveArgGoto(nparams, error); if (virTypedParameterValidateSet(conn, params, nparams) < 0) goto error; if (conn->driver->domainSetInterfaceParameters) { int ret; ret = conn->driver->domainSetInterfaceParameters(domain, device, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetInterfaceParameters: * @domain: pointer to domain object * @device: the interface name or mac address * @params: pointer to interface parameter objects * (return value, allocated by the caller) * @nparams: pointer to number of interface parameter; input and output * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all interface parameters. On input, @nparams gives the size of * the @params array; on output, @nparams gives how many slots were * filled with parameter information, which might be less but will not * exceed the input value. * * As a special case, calling with @params as NULL and @nparams as 0 on * input will cause @nparams on output to contain the number of parameters * supported by the hypervisor. The caller should then allocate @params * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the * API again. See virDomainGetMemoryParameters() for an equivalent usage * example. * * This function may require privileged access to the hypervisor. This function * expects the caller to allocate the @params. * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetInterfaceParameters(virDomainPtr domain, const char *device, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "device=%s, params=%p, nparams=%d, flags=%x", device, params, (nparams) ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) virCheckNonNullArgGoto(params, error); if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; conn = domain->conn; if (conn->driver->domainGetInterfaceParameters) { int ret; ret = conn->driver->domainGetInterfaceParameters(domain, device, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainMemoryStats: * @dom: pointer to the domain object * @stats: nr_stats-sized array of stat structures (returned) * @nr_stats: number of memory statistics requested * @flags: extra flags; not used yet, so callers should always pass 0 * * This function provides memory statistics for the domain. * * Up to 'nr_stats' elements of 'stats' will be populated with memory statistics * from the domain. Only statistics supported by the domain, the driver, and * this version of libvirt will be returned. * * Memory Statistics: * * VIR_DOMAIN_MEMORY_STAT_SWAP_IN: * The total amount of data read from swap space (in kb). * VIR_DOMAIN_MEMORY_STAT_SWAP_OUT: * The total amount of memory written out to swap space (in kb). * VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT: * The number of page faults that required disk IO to service. * VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT: * The number of page faults serviced without disk IO. * VIR_DOMAIN_MEMORY_STAT_UNUSED: * The amount of memory which is not being used for any purpose (in kb). * VIR_DOMAIN_MEMORY_STAT_AVAILABLE: * The total amount of memory available to the domain's OS (in kb). * VIR_DOMAIN_MEMORY_STAT_ACTUAL_BALLOON: * Current balloon value (in kb). * * Returns: The number of stats provided or -1 in case of failure. */ int virDomainMemoryStats(virDomainPtr dom, virDomainMemoryStatPtr stats, unsigned int nr_stats, unsigned int flags) { virConnectPtr conn; unsigned long nr_stats_ret = 0; VIR_DOMAIN_DEBUG(dom, "stats=%p, nr_stats=%u, flags=%x", stats, nr_stats, flags); virResetLastError(); virCheckDomainReturn(dom, -1); if (!stats || nr_stats == 0) return 0; if (nr_stats > VIR_DOMAIN_MEMORY_STAT_NR) nr_stats = VIR_DOMAIN_MEMORY_STAT_NR; conn = dom->conn; if (conn->driver->domainMemoryStats) { nr_stats_ret = conn->driver->domainMemoryStats(dom, stats, nr_stats, flags); if (nr_stats_ret == -1) goto error; return nr_stats_ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockPeek: * @dom: pointer to the domain object * @disk: path to the block device, or device shorthand * @offset: offset within block device * @size: size to read * @buffer: return buffer (must be at least size bytes) * @flags: extra flags; not used yet, so callers should always pass 0 * * This function allows you to read the contents of a domain's * disk device. * * Typical uses for this are to determine if the domain has * written a Master Boot Record (indicating that the domain * has completed installation), or to try to work out the state * of the domain's filesystems. * * (Note that in the local case you might try to open the * block device or file directly, but that won't work in the * remote case, nor if you don't have sufficient permission. * Hence the need for this call). * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * 'offset' and 'size' represent an area which must lie entirely * within the device or file. 'size' may be 0 to test if the * call would succeed. * * 'buffer' is the return buffer and must be at least 'size' bytes. * * NB. The remote driver imposes a 64K byte limit on 'size'. * For your program to be able to work reliably over a remote * connection you should split large requests to <= 65536 bytes. * However, with 0.9.13 this RPC limit has been raised to 1M byte. * Starting with version 1.0.6 the RPC limit has been raised again. * Now large requests up to 16M byte are supported. * * Returns: 0 in case of success or -1 in case of failure. */ int virDomainBlockPeek(virDomainPtr dom, const char *disk, unsigned long long offset /* really 64 bits */, size_t size, void *buffer, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, offset=%lld, size=%zi, buffer=%p, flags=%x", disk, offset, size, buffer, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonEmptyStringArgGoto(disk, error); /* Allow size == 0 as an access test. */ if (size > 0) virCheckNonNullArgGoto(buffer, error); if (conn->driver->domainBlockPeek) { int ret; ret = conn->driver->domainBlockPeek(dom, disk, offset, size, buffer, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockResize: * @dom: pointer to the domain object * @disk: path to the block image, or shorthand * @size: new size of the block image, see below for unit * @flags: bitwise-OR of virDomainBlockResizeFlags * * Resize a block device of domain while the domain is running. If * @flags is 0, then @size is in kibibytes (blocks of 1024 bytes); * since 0.9.11, if @flags includes VIR_DOMAIN_BLOCK_RESIZE_BYTES, * @size is in bytes instead. @size is taken directly as the new * size. Depending on the file format, the hypervisor may round up * to the next alignment boundary. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * Note that this call may fail if the underlying virtualization hypervisor * does not support it; this call requires privileged access to the * hypervisor. * * Returns: 0 in case of success or -1 in case of failure. */ int virDomainBlockResize(virDomainPtr dom, const char *disk, unsigned long long size, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, size=%llu, flags=%x", disk, size, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (conn->driver->domainBlockResize) { int ret; ret = conn->driver->domainBlockResize(dom, disk, size, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainMemoryPeek: * @dom: pointer to the domain object * @start: start of memory to peek * @size: size of memory to peek * @buffer: return buffer (must be at least size bytes) * @flags: bitwise-OR of virDomainMemoryFlags * * This function allows you to read the contents of a domain's * memory. * * The memory which is read is controlled by the 'start', 'size' * and 'flags' parameters. * * If 'flags' is VIR_MEMORY_VIRTUAL then the 'start' and 'size' * parameters are interpreted as virtual memory addresses for * whichever task happens to be running on the domain at the * moment. Although this sounds haphazard it is in fact what * you want in order to read Linux kernel state, because it * ensures that pointers in the kernel image can be interpreted * coherently. * * 'buffer' is the return buffer and must be at least 'size' bytes. * 'size' may be 0 to test if the call would succeed. * * NB. The remote driver imposes a 64K byte limit on 'size'. * For your program to be able to work reliably over a remote * connection you should split large requests to <= 65536 bytes. * However, with 0.9.13 this RPC limit has been raised to 1M byte. * Starting with version 1.0.6 the RPC limit has been raised again. * Now large requests up to 16M byte are supported. * * Returns: 0 in case of success or -1 in case of failure. */ int virDomainMemoryPeek(virDomainPtr dom, unsigned long long start /* really 64 bits */, size_t size, void *buffer, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "start=%lld, size=%zi, buffer=%p, flags=%x", start, size, buffer, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); /* Note on access to physical memory: A VIR_MEMORY_PHYSICAL flag is * a possibility. However it isn't really useful unless the caller * can also access registers, particularly CR3 on x86 in order to * get the Page Table Directory. Since registers are different on * every architecture, that would imply another call to get the * machine registers. * * The QEMU driver handles VIR_MEMORY_VIRTUAL, mapping it * to the qemu 'memsave' command which does the virtual to physical * mapping inside qemu. * * The QEMU driver also handles VIR_MEMORY_PHYSICAL, mapping it * to the qemu 'pmemsave' command. * * At time of writing there is no Xen driver. However the Xen * hypervisor only lets you map physical pages from other domains, * and so the Xen driver would have to do the virtual to physical * mapping by chasing 2, 3 or 4-level page tables from the PTD. * There is example code in libxc (xc_translate_foreign_address) * which does this, although we cannot copy this code directly * because of incompatible licensing. */ VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MEMORY_VIRTUAL, VIR_MEMORY_PHYSICAL, error); /* Allow size == 0 as an access test. */ if (size > 0) virCheckNonNullArgGoto(buffer, error); if (conn->driver->domainMemoryPeek) { int ret; ret = conn->driver->domainMemoryPeek(dom, start, size, buffer, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetBlockInfo: * @domain: a domain object * @disk: path to the block device, or device shorthand * @info: pointer to a virDomainBlockInfo structure allocated by the user * @flags: extra flags; not used yet, so callers should always pass 0 * * Extract information about a domain's block device. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * For QEMU domains, the allocation and physical virDomainBlockInfo * values returned will generally be the same, except when using a * non raw, block backing device, such as qcow2 for an active domain. * When the persistent domain is not active, QEMU will return the * default which is the same value for allocation and physical. * * Active QEMU domains can return an allocation value which is more * representative of the currently used blocks by the device compared * to the physical size of the device. Applications can use/monitor * the allocation value with the understanding that if the domain * becomes inactive during an attempt to get the value, the default * values will be returned. Thus, the application should check * after the call for the domain being inactive if the values are * the same. Optionally, the application could be watching for a * shutdown event and then ignore any values received afterwards. * This can be an issue when a domain is being migrated and the * exact timing of the domain being made inactive and check of * the allocation value results the default being returned. For * a transient domain in the similar situation, this call will return * -1 and an error message indicating the "domain is not running". * * The following is some pseudo code illustrating the call sequence: * * ... * virDomainPtr dom; * virDomainBlockInfo info; * char *device; * ... * // Either get a list of all domains or a specific domain * // via a virDomainLookupBy*() call. * // * // It's also required to fill in the device pointer, but that's * // specific to the implementation. For the purposes of this example * // a qcow2 backed device name string would need to be provided. * ... * // If the following call is made on a persistent domain with a * // qcow2 block backed block device, then it's possible the returned * // allocation equals the physical value. In that case, the domain * // that may have been active prior to calling has become inactive, * // such as is the case during a domain migration. Thus once we * // get data returned, check for active domain when the values are * // the same. * if (virDomainGetBlockInfo(dom, device, &info, 0) < 0) * goto failure; * if (info.allocation == info.physical) { * // If the domain is no longer active, * // then the defaults are being returned. * if (!virDomainIsActive()) * goto ignore_return; * } * // Do something with the allocation and physical values * ... * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetBlockInfo(virDomainPtr domain, const char *disk, virDomainBlockInfoPtr info, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "info=%p, flags=%x", info, flags); virResetLastError(); if (info) memset(info, 0, sizeof(*info)); virCheckDomainReturn(domain, -1); virCheckNonEmptyStringArgGoto(disk, error); virCheckNonNullArgGoto(info, error); conn = domain->conn; if (conn->driver->domainGetBlockInfo) { int ret; ret = conn->driver->domainGetBlockInfo(domain, disk, info, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainDefineXML: * @conn: pointer to the hypervisor connection * @xml: the XML description for the domain, preferably in UTF-8 * * Define a domain, but does not start it. * This definition is persistent, until explicitly undefined with * virDomainUndefine(). A previous definition for this domain would be * overridden if it already exists. * * Some hypervisors may prevent this operation if there is a current * block copy operation on a transient domain with the same id as the * domain being defined; in that case, use virDomainBlockJobAbort() to * stop the block copy first. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns NULL in case of error, a pointer to the domain otherwise */ virDomainPtr virDomainDefineXML(virConnectPtr conn, const char *xml) { VIR_DEBUG("conn=%p, xml=%s", conn, NULLSTR(xml)); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(xml, error); if (conn->driver->domainDefineXML) { virDomainPtr ret; ret = conn->driver->domainDefineXML(conn, xml); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainDefineXMLFlags: * @conn: pointer to the hypervisor connection * @xml: the XML description for the domain, preferably in UTF-8 * @flags: bitwise OR of the virDomainDefineFlags constants * * Defines a domain, but does not start it. * This definition is persistent, until explicitly undefined with * virDomainUndefine(). A previous definition for this domain would be * overridden if it already exists. * * Some hypervisors may prevent this operation if there is a current * block copy operation on a transient domain with the same id as the * domain being defined; in that case, use virDomainBlockJobAbort() to * stop the block copy first. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns NULL in case of error, a pointer to the domain otherwise */ virDomainPtr virDomainDefineXMLFlags(virConnectPtr conn, const char *xml, unsigned int flags) { VIR_DEBUG("conn=%p, xml=%s flags=%x", conn, NULLSTR(xml), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(xml, error); if (conn->driver->domainDefineXMLFlags) { virDomainPtr ret; ret = conn->driver->domainDefineXMLFlags(conn, xml, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainUndefine: * @domain: pointer to a defined domain * * Undefine a domain. If the domain is running, it's converted to * transient domain, without stopping it. If the domain is inactive, * the domain configuration is removed. * * If the domain has a managed save image (see * virDomainHasManagedSaveImage()), or if it is inactive and has any * snapshot metadata (see virDomainSnapshotNum()), then the undefine will * fail. See virDomainUndefineFlags() for more control. * * Returns 0 in case of success, -1 in case of error */ int virDomainUndefine(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainUndefine) { int ret; ret = conn->driver->domainUndefine(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainUndefineFlags: * @domain: pointer to a defined domain * @flags: bitwise-OR of supported virDomainUndefineFlagsValues * * Undefine a domain. If the domain is running, it's converted to * transient domain, without stopping it. If the domain is inactive, * the domain configuration is removed. * * If the domain has a managed save image (see virDomainHasManagedSaveImage()), * then including VIR_DOMAIN_UNDEFINE_MANAGED_SAVE in @flags will also remove * that file, and omitting the flag will cause the undefine process to fail. * * If the domain is inactive and has any snapshot metadata (see * virDomainSnapshotNum()), then including * VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA in @flags will also remove * that metadata. Omitting the flag will cause the undefine of an * inactive domain to fail. Active snapshots will retain snapshot * metadata until the (now-transient) domain halts, regardless of * whether this flag is present. On hypervisors where snapshots do * not use libvirt metadata, this flag has no effect. * * If the domain has any nvram specified, then including * VIR_DOMAIN_UNDEFINE_NVRAM will also remove that file, and omitting the flag * will cause the undefine process to fail. * * Returns 0 in case of success, -1 in case of error */ int virDomainUndefineFlags(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainUndefineFlags) { int ret; ret = conn->driver->domainUndefineFlags(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virConnectNumOfDefinedDomains: * @conn: pointer to the hypervisor connection * * Provides the number of defined but inactive domains. * * Returns the number of domain found or -1 in case of error */ int virConnectNumOfDefinedDomains(virConnectPtr conn) { VIR_DEBUG("conn=%p", conn); virResetLastError(); virCheckConnectReturn(conn, -1); if (conn->driver->connectNumOfDefinedDomains) { int ret; ret = conn->driver->connectNumOfDefinedDomains(conn); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectListDefinedDomains: * @conn: pointer to the hypervisor connection * @names: pointer to an array to store the names * @maxnames: size of the array * * list the defined but inactive domains, stores the pointers to the names * in @names * * For active domains, see virConnectListDomains(). For more control over * the results, see virConnectListAllDomains(). * * Returns the number of names provided in the array or -1 in case of error. * Note that this command is inherently racy; a domain can be defined between * a call to virConnectNumOfDefinedDomains() and this call; you are only * guaranteed that all currently defined domains were listed if the return * is less than @maxids. The client must call free() on each returned name. */ int virConnectListDefinedDomains(virConnectPtr conn, char **const names, int maxnames) { VIR_DEBUG("conn=%p, names=%p, maxnames=%d", conn, names, maxnames); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNullArgGoto(names, error); virCheckNonNegativeArgGoto(maxnames, error); if (conn->driver->connectListDefinedDomains) { int ret; ret = conn->driver->connectListDefinedDomains(conn, names, maxnames); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectListAllDomains: * @conn: Pointer to the hypervisor connection. * @domains: Pointer to a variable to store the array containing domain objects * or NULL if the list is not required (just returns number of guests). * @flags: bitwise-OR of virConnectListAllDomainsFlags * * Collect a possibly-filtered list of all domains, and return an allocated * array of information for each. This API solves the race inherent in * virConnectListDomains() and virConnectListDefinedDomains(). * * Normally, all domains are returned; however, @flags can be used to * filter the results for a smaller list of targeted domains. The valid * flags are divided into groups, where each group contains bits that * describe mutually exclusive attributes of a domain, and where all bits * within a group describe all possible domains. Some hypervisors might * reject explicit bits from a group where the hypervisor cannot make a * distinction (for example, not all hypervisors can tell whether domains * have snapshots). For a group supported by a given hypervisor, the * behavior when no bits of a group are set is identical to the behavior * when all bits in that group are set. When setting bits from more than * one group, it is possible to select an impossible combination (such * as an inactive transient domain), in that case a hypervisor may return * either 0 or an error. * * The first group of @flags is VIR_CONNECT_LIST_DOMAINS_ACTIVE (online * domains) and VIR_CONNECT_LIST_DOMAINS_INACTIVE (offline domains). * * The next group of @flags is VIR_CONNECT_LIST_DOMAINS_PERSISTENT (defined * domains) and VIR_CONNECT_LIST_DOMAINS_TRANSIENT (running but not defined). * * The next group of @flags covers various domain states: * VIR_CONNECT_LIST_DOMAINS_RUNNING, VIR_CONNECT_LIST_DOMAINS_PAUSED, * VIR_CONNECT_LIST_DOMAINS_SHUTOFF, and a catch-all for all other states * (such as crashed, this catch-all covers the possibility of adding new * states). * * The remaining groups cover boolean attributes commonly asked about * domains; they include VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE and * VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE, for filtering based on whether * a managed save image exists; VIR_CONNECT_LIST_DOMAINS_AUTOSTART and * VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART, for filtering based on autostart; * VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT and * VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT, for filtering based on whether * a domain has snapshots. * * Example of usage: * * virDomainPtr *domains; * size_t i; * int ret; * unsigned int flags = VIR_CONNECT_LIST_DOMAINS_RUNNING | * VIR_CONNECT_LIST_DOMAINS_PERSISTENT; * ret = virConnectListAllDomains(conn, &domains, flags); * if (ret < 0) * error(); * for (i = 0; i < ret; i++) { * do_something_with_domain(domains[i]); * //here or in a separate loop if needed * virDomainFree(domains[i]); * } * free(domains); * * Returns the number of domains found or -1 and sets domains to NULL in case of * error. On success, the array stored into @domains is guaranteed to have an * extra allocated element set to NULL but not included in the return count, to * make iteration easier. The caller is responsible for calling virDomainFree() * on each array element, then calling free() on @domains. */ int virConnectListAllDomains(virConnectPtr conn, virDomainPtr **domains, unsigned int flags) { VIR_DEBUG("conn=%p, domains=%p, flags=%x", conn, domains, flags); virResetLastError(); if (domains) *domains = NULL; virCheckConnectReturn(conn, -1); if (conn->driver->connectListAllDomains) { int ret; ret = conn->driver->connectListAllDomains(conn, domains, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainCreate: * @domain: pointer to a defined domain * * Launch a defined domain. If the call succeeds the domain moves from the * defined to the running domains pools. The domain will be paused only * if restoring from managed state created from a paused domain. For more * control, see virDomainCreateWithFlags(). * * Returns 0 in case of success, -1 in case of error */ int virDomainCreate(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainCreate) { int ret; ret = conn->driver->domainCreate(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainCreateWithFlags: * @domain: pointer to a defined domain * @flags: bitwise-OR of supported virDomainCreateFlags * * Launch a defined domain. If the call succeeds the domain moves from the * defined to the running domains pools. * * If the VIR_DOMAIN_START_PAUSED flag is set, or if the guest domain * has a managed save image that requested paused state (see * virDomainManagedSave()) the guest domain will be started, but its * CPUs will remain paused. The CPUs can later be manually started * using virDomainResume(). In all other cases, the guest domain will * be running. * * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest * domain will be automatically destroyed when the virConnectPtr * object is finally released. This will also happen if the * client application crashes / loses its connection to the * libvirtd daemon. Any domains marked for auto destroy will * block attempts at migration, save-to-file, or snapshots. * * If the VIR_DOMAIN_START_BYPASS_CACHE flag is set, and there is a * managed save file for this domain (created by virDomainManagedSave()), * then libvirt will attempt to bypass the file system cache while restoring * the file, or fail if it cannot do so for the given system; this can allow * less pressure on file system cache, but also risks slowing loads from NFS. * * If the VIR_DOMAIN_START_FORCE_BOOT flag is set, then any managed save * file for this domain is discarded, and the domain boots from scratch. * * Returns 0 in case of success, -1 in case of error */ int virDomainCreateWithFlags(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainCreateWithFlags) { int ret; ret = conn->driver->domainCreateWithFlags(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainCreateWithFiles: * @domain: pointer to a defined domain * @nfiles: number of file descriptors passed * @files: list of file descriptors passed * @flags: bitwise-OR of supported virDomainCreateFlags * * Launch a defined domain. If the call succeeds the domain moves from the * defined to the running domains pools. * * @files provides an array of file descriptors which will be * made available to the 'init' process of the guest. The file * handles exposed to the guest will be renumbered to start * from 3 (ie immediately following stderr). This is only * supported for guests which use container based virtualization * technology. * * If the VIR_DOMAIN_START_PAUSED flag is set, or if the guest domain * has a managed save image that requested paused state (see * virDomainManagedSave()) the guest domain will be started, but its * CPUs will remain paused. The CPUs can later be manually started * using virDomainResume(). In all other cases, the guest domain will * be running. * * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest * domain will be automatically destroyed when the virConnectPtr * object is finally released. This will also happen if the * client application crashes / loses its connection to the * libvirtd daemon. Any domains marked for auto destroy will * block attempts at migration, save-to-file, or snapshots. * * If the VIR_DOMAIN_START_BYPASS_CACHE flag is set, and there is a * managed save file for this domain (created by virDomainManagedSave()), * then libvirt will attempt to bypass the file system cache while restoring * the file, or fail if it cannot do so for the given system; this can allow * less pressure on file system cache, but also risks slowing loads from NFS. * * If the VIR_DOMAIN_START_FORCE_BOOT flag is set, then any managed save * file for this domain is discarded, and the domain boots from scratch. * * Returns 0 in case of success, -1 in case of error */ int virDomainCreateWithFiles(virDomainPtr domain, unsigned int nfiles, int *files, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "nfiles=%u, files=%p, flags=%x", nfiles, files, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainCreateWithFiles) { int ret; ret = conn->driver->domainCreateWithFiles(domain, nfiles, files, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetAutostart: * @domain: a domain object * @autostart: the value returned * * Provides a boolean value indicating whether the domain * configured to be automatically started when the host * machine boots. * * Returns -1 in case of error, 0 in case of success */ int virDomainGetAutostart(virDomainPtr domain, int *autostart) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "autostart=%p", autostart); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(autostart, error); conn = domain->conn; if (conn->driver->domainGetAutostart) { int ret; ret = conn->driver->domainGetAutostart(domain, autostart); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetAutostart: * @domain: a domain object * @autostart: whether the domain should be automatically started 0 or 1 * * Configure the domain to be automatically started * when the host machine boots. * * Returns -1 in case of error, 0 in case of success */ int virDomainSetAutostart(virDomainPtr domain, int autostart) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "autostart=%d", autostart); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainSetAutostart) { int ret; ret = conn->driver->domainSetAutostart(domain, autostart); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainInjectNMI: * @domain: pointer to domain object, or NULL for Domain0 * @flags: extra flags; not used yet, so callers should always pass 0 * * Send NMI to the guest * * Returns 0 in case of success, -1 in case of failure. */ int virDomainInjectNMI(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainInjectNMI) { int ret; ret = conn->driver->domainInjectNMI(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSendKey: * @domain: pointer to domain object, or NULL for Domain0 * @codeset: the code set of keycodes, from virKeycodeSet * @holdtime: the duration (in milliseconds) that the keys will be held * @keycodes: array of keycodes * @nkeycodes: number of keycodes, up to VIR_DOMAIN_SEND_KEY_MAX_KEYS * @flags: extra flags; not used yet, so callers should always pass 0 * * Send key(s) to the guest. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSendKey(virDomainPtr domain, unsigned int codeset, unsigned int holdtime, unsigned int *keycodes, int nkeycodes, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "codeset=%u, holdtime=%u, nkeycodes=%u, flags=%x", codeset, holdtime, nkeycodes, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(keycodes, error); virCheckPositiveArgGoto(nkeycodes, error); if (nkeycodes > VIR_DOMAIN_SEND_KEY_MAX_KEYS) { virReportInvalidArg(nkeycodes, _("nkeycodes must be <= %d"), VIR_DOMAIN_SEND_KEY_MAX_KEYS); goto error; } if (conn->driver->domainSendKey) { int ret; ret = conn->driver->domainSendKey(domain, codeset, holdtime, keycodes, nkeycodes, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSendProcessSignal: * @domain: pointer to domain object * @pid_value: a positive integer process ID, or negative integer process group ID * @signum: a signal from the virDomainProcessSignal enum * @flags: one of the virDomainProcessSignalFlag values * * Send a signal to the designated process in the guest * * The signal numbers must be taken from the virDomainProcessSignal * enum. These will be translated to the corresponding signal * number for the guest OS, by the guest agent delivering the * signal. If there is no mapping from virDomainProcessSignal to * the native OS signals, this API will report an error. * * If @pid_value is an integer greater than zero, it is * treated as a process ID. If @pid_value is an integer * less than zero, it is treated as a process group ID. * All the @pid_value numbers are from the container/guest * namespace. The value zero is not valid. * * Not all hypervisors will support sending signals to * arbitrary processes or process groups. If this API is * implemented the minimum requirement is to be able to * use @pid_value == 1 (i.e. kill init). No other value is * required to be supported. * * If the @signum is VIR_DOMAIN_PROCESS_SIGNAL_NOP then this * API will simply report whether the process is running in * the container/guest. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSendProcessSignal(virDomainPtr domain, long long pid_value, unsigned int signum, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "pid=%lld, signum=%u flags=%x", pid_value, signum, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonZeroArgGoto(pid_value, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainSendProcessSignal) { int ret; ret = conn->driver->domainSendProcessSignal(domain, pid_value, signum, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetVcpus: * @domain: pointer to domain object, or NULL for Domain0 * @nvcpus: the new number of virtual CPUs for this domain * * Dynamically change the number of virtual CPUs used by the domain. * Note that this call may fail if the underlying virtualization hypervisor * does not support it or if growing the number is arbitrarily limited. * This function may require privileged access to the hypervisor. * * Note that if this call is executed before the guest has finished booting, * the guest may fail to process the change. * * This command only changes the runtime configuration of the domain, * so can only be called on an active domain. It is hypervisor-dependent * whether it also affects persistent configuration; for more control, * use virDomainSetVcpusFlags(). * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "nvcpus=%u", nvcpus); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonZeroArgGoto(nvcpus, error); if (conn->driver->domainSetVcpus) { int ret; ret = conn->driver->domainSetVcpus(domain, nvcpus); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetVcpusFlags: * @domain: pointer to domain object, or NULL for Domain0 * @nvcpus: the new number of virtual CPUs for this domain, must be at least 1 * @flags: bitwise-OR of virDomainVcpuFlags * * Dynamically change the number of virtual CPUs used by the domain. * Note that this call may fail if the underlying virtualization hypervisor * does not support it or if growing the number is arbitrarily limited. * This function may require privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE to affect a running * domain (which may fail if domain is not active), or * VIR_DOMAIN_AFFECT_CONFIG to affect the next boot via the XML * description of the domain. Both flags may be set. * If neither flag is specified (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), * then an inactive domain modifies persistent setup, while an active domain * is hypervisor-dependent on whether just live or both live and persistent * state is changed. * * Note that if this call is executed before the guest has finished booting, * the guest may fail to process the change. * * If @flags includes VIR_DOMAIN_VCPU_MAXIMUM, then * VIR_DOMAIN_AFFECT_LIVE must be clear, and only the maximum virtual * CPU limit is altered; generally, this value must be less than or * equal to virConnectGetMaxVcpus(). Otherwise, this call affects the * current virtual CPU limit, which must be less than or equal to the * maximum limit. * * If @flags includes VIR_DOMAIN_VCPU_GUEST, then the state of processors is * modified inside the guest instead of the hypervisor. This flag can only * be used with live guests and is incompatible with VIR_DOMAIN_VCPU_MAXIMUM. * The usage of this flag may require a guest agent configured. * * Not all hypervisors can support all flag combinations. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "nvcpus=%u, flags=%x", nvcpus, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); VIR_REQUIRE_FLAG_GOTO(VIR_DOMAIN_VCPU_MAXIMUM, VIR_DOMAIN_AFFECT_CONFIG, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_VCPU_GUEST, VIR_DOMAIN_AFFECT_CONFIG, error); virCheckNonZeroArgGoto(nvcpus, error); conn = domain->conn; if (conn->driver->domainSetVcpusFlags) { int ret; ret = conn->driver->domainSetVcpusFlags(domain, nvcpus, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetVcpusFlags: * @domain: pointer to domain object, or NULL for Domain0 * @flags: bitwise-OR of virDomainVcpuFlags * * Query the number of virtual CPUs used by the domain. Note that * this call may fail if the underlying virtualization hypervisor does * not support it. This function may require privileged access to the * hypervisor. * * If @flags includes VIR_DOMAIN_AFFECT_LIVE, this will query a * running domain (which will fail if domain is not active); if * it includes VIR_DOMAIN_AFFECT_CONFIG, this will query the XML * description of the domain. It is an error to set both flags. * If neither flag is set (that is, VIR_DOMAIN_AFFECT_CURRENT), * then the configuration queried depends on whether the domain * is currently running. * * If @flags includes VIR_DOMAIN_VCPU_MAXIMUM, then the maximum * virtual CPU limit is queried. Otherwise, this call queries the * current virtual CPU count. * * If @flags includes VIR_DOMAIN_VCPU_GUEST, then the state of the processors * is queried in the guest instead of the hypervisor. This flag is only usable * on live domains. Guest agent may be needed for this flag to be available. * * Returns the number of vCPUs in case of success, -1 in case of failure. */ int virDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; if (flags & VIR_DOMAIN_VCPU_GUEST) virCheckReadOnlyGoto(conn->flags, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); if (conn->driver->domainGetVcpusFlags) { int ret; ret = conn->driver->domainGetVcpusFlags(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainPinVcpu: * @domain: pointer to domain object, or NULL for Domain0 * @vcpu: virtual CPU number * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN) * Each bit set to 1 means that corresponding CPU is usable. * Bytes are stored in little-endian order: CPU0-7, 8-15... * In each byte, lowest CPU number is least significant bit. * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in * underlying virtualization system (Xen...). * If maplen < size, missing bytes are set to zero. * If maplen > size, failure code is returned. * * Dynamically change the real CPUs which can be allocated to a virtual CPU. * This function may require privileged access to the hypervisor. * * This command only changes the runtime configuration of the domain, * so can only be called on an active domain. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainPinVcpu(virDomainPtr domain, unsigned int vcpu, unsigned char *cpumap, int maplen) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "vcpu=%u, cpumap=%p, maplen=%d", vcpu, cpumap, maplen); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(cpumap, error); virCheckPositiveArgGoto(maplen, error); if (conn->driver->domainPinVcpu) { int ret; ret = conn->driver->domainPinVcpu(domain, vcpu, cpumap, maplen); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainPinVcpuFlags: * @domain: pointer to domain object, or NULL for Domain0 * @vcpu: virtual CPU number * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN) * Each bit set to 1 means that corresponding CPU is usable. * Bytes are stored in little-endian order: CPU0-7, 8-15... * In each byte, lowest CPU number is least significant bit. * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in * underlying virtualization system (Xen...). * If maplen < size, missing bytes are set to zero. * If maplen > size, failure code is returned. * @flags: bitwise-OR of virDomainModificationImpact * * Dynamically change the real CPUs which can be allocated to a virtual CPU. * This function may require privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain * and may fail if domain is not alive. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified (that is, * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies * persistent setup, while an active domain is hypervisor-dependent on whether * just live or both live and persistent state is changed. * Not all hypervisors can support all flag combinations. * * See also virDomainGetVcpuPinInfo for querying this information. * * Returns 0 in case of success, -1 in case of failure. * */ int virDomainPinVcpuFlags(virDomainPtr domain, unsigned int vcpu, unsigned char *cpumap, int maplen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "vcpu=%u, cpumap=%p, maplen=%d, flags=%x", vcpu, cpumap, maplen, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(cpumap, error); virCheckPositiveArgGoto(maplen, error); if (conn->driver->domainPinVcpuFlags) { int ret; ret = conn->driver->domainPinVcpuFlags(domain, vcpu, cpumap, maplen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetVcpuPinInfo: * @domain: pointer to domain object, or NULL for Domain0 * @ncpumaps: the number of cpumap (listed first to match virDomainGetVcpus) * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this * domain (in 8-bit bytes) (OUT) * It's assumed there is <ncpumaps> cpumap in cpumaps array. * The memory allocated to cpumaps must be (ncpumaps * maplen) bytes * (ie: calloc(ncpumaps, maplen)). * One cpumap inside cpumaps has the format described in * virDomainPinVcpu() API. * Must not be NULL. * @maplen: the number of bytes in one cpumap, from 1 up to size of CPU map. * Must be positive. * @flags: bitwise-OR of virDomainModificationImpact * Must not be VIR_DOMAIN_AFFECT_LIVE and * VIR_DOMAIN_AFFECT_CONFIG concurrently. * * Query the CPU affinity setting of all virtual CPUs of domain, store it * in cpumaps. * * Returns the number of virtual CPUs in case of success, * -1 in case of failure. */ int virDomainGetVcpuPinInfo(virDomainPtr domain, int ncpumaps, unsigned char *cpumaps, int maplen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "ncpumaps=%d, cpumaps=%p, maplen=%d, flags=%x", ncpumaps, cpumaps, maplen, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(cpumaps, error); virCheckPositiveArgGoto(ncpumaps, error); virCheckPositiveArgGoto(maplen, error); if (INT_MULTIPLY_OVERFLOW(ncpumaps, maplen)) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %d * %d"), ncpumaps, maplen); goto error; } VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); if (conn->driver->domainGetVcpuPinInfo) { int ret; ret = conn->driver->domainGetVcpuPinInfo(domain, ncpumaps, cpumaps, maplen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainPinEmulator: * @domain: pointer to domain object, or NULL for Domain0 * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN) * Each bit set to 1 means that corresponding CPU is usable. * Bytes are stored in little-endian order: CPU0-7, 8-15... * In each byte, lowest CPU number is least significant bit. * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in * underlying virtualization system (Xen...). * If maplen < size, missing bytes are set to zero. * If maplen > size, failure code is returned. * @flags: bitwise-OR of virDomainModificationImpact * * Dynamically change the real CPUs which can be allocated to all emulator * threads. This function may require privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain * and may fail if domain is not alive. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified (that is, * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies * persistent setup, while an active domain is hypervisor-dependent on whether * just live or both live and persistent state is changed. * Not all hypervisors can support all flag combinations. * * See also virDomainGetEmulatorPinInfo for querying this information. * * Returns 0 in case of success, -1 in case of failure. * */ int virDomainPinEmulator(virDomainPtr domain, unsigned char *cpumap, int maplen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cpumap=%p, maplen=%d, flags=%x", cpumap, maplen, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(cpumap, error); virCheckPositiveArgGoto(maplen, error); if (conn->driver->domainPinEmulator) { int ret; ret = conn->driver->domainPinEmulator(domain, cpumap, maplen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetEmulatorPinInfo: * @domain: pointer to domain object, or NULL for Domain0 * @cpumap: pointer to a bit map of real CPUs for all emulator threads of * this domain (in 8-bit bytes) (OUT) * There is only one cpumap for all emulator threads. * Must not be NULL. * @maplen: the number of bytes in one cpumap, from 1 up to size of CPU map. * Must be positive. * @flags: bitwise-OR of virDomainModificationImpact * Must not be VIR_DOMAIN_AFFECT_LIVE and * VIR_DOMAIN_AFFECT_CONFIG concurrently. * * Query the CPU affinity setting of all emulator threads of domain, store * it in cpumap. * * Returns 1 in case of success, * 0 in case of no emulator threads are pined to pcpus, * -1 in case of failure. */ int virDomainGetEmulatorPinInfo(virDomainPtr domain, unsigned char *cpumap, int maplen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cpumap=%p, maplen=%d, flags=%x", cpumap, maplen, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(cpumap, error); virCheckPositiveArgGoto(maplen, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); conn = domain->conn; if (conn->driver->domainGetEmulatorPinInfo) { int ret; ret = conn->driver->domainGetEmulatorPinInfo(domain, cpumap, maplen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetVcpus: * @domain: pointer to domain object, or NULL for Domain0 * @info: pointer to an array of virVcpuInfo structures (OUT) * @maxinfo: number of structures in info array * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this * domain (in 8-bit bytes) (OUT) * If cpumaps is NULL, then no cpumap information is returned by the API. * It's assumed there is <maxinfo> cpumap in cpumaps array. * The memory allocated to cpumaps must be (maxinfo * maplen) bytes * (ie: calloc(maxinfo, maplen)). * One cpumap inside cpumaps has the format described in * virDomainPinVcpu() API. * @maplen: number of bytes in one cpumap, from 1 up to size of CPU map in * underlying virtualization system (Xen...). * Must be zero when cpumaps is NULL and positive when it is non-NULL. * * Extract information about virtual CPUs of domain, store it in info array * and also in cpumaps if this pointer isn't NULL. This call may fail * on an inactive domain. * * See also virDomainGetVcpuPinInfo for querying just cpumaps, including on * an inactive domain. * * Returns the number of info filled in case of success, -1 in case of failure. */ int virDomainGetVcpus(virDomainPtr domain, virVcpuInfoPtr info, int maxinfo, unsigned char *cpumaps, int maplen) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "info=%p, maxinfo=%d, cpumaps=%p, maplen=%d", info, maxinfo, cpumaps, maplen); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(info, error); virCheckPositiveArgGoto(maxinfo, error); /* Ensure that domainGetVcpus (aka remoteDomainGetVcpus) does not try to memcpy anything into a NULL pointer. */ if (cpumaps) virCheckPositiveArgGoto(maplen, error); else virCheckZeroArgGoto(maplen, error); if (cpumaps && INT_MULTIPLY_OVERFLOW(maxinfo, maplen)) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %d * %d"), maxinfo, maplen); goto error; } conn = domain->conn; if (conn->driver->domainGetVcpus) { int ret; ret = conn->driver->domainGetVcpus(domain, info, maxinfo, cpumaps, maplen); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetMaxVcpus: * @domain: pointer to domain object * * Provides the maximum number of virtual CPUs supported for * the guest VM. If the guest is inactive, this is basically * the same as virConnectGetMaxVcpus(). If the guest is running * this will reflect the maximum number of virtual CPUs the * guest was booted with. For more details, see virDomainGetVcpusFlags(). * * Returns the maximum of virtual CPU or -1 in case of error. */ int virDomainGetMaxVcpus(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; if (conn->driver->domainGetMaxVcpus) { int ret; ret = conn->driver->domainGetMaxVcpus(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetIOThreadInfo: * @dom: a domain object * @info: pointer to an array of virDomainIOThreadInfo structures (OUT) * @flags: bitwise-OR of virDomainModificationImpact * Must not be VIR_DOMAIN_AFFECT_LIVE and * VIR_DOMAIN_AFFECT_CONFIG concurrently. * * Fetch IOThreads of an active domain including the cpumap information to * determine on which CPU the IOThread has affinity to run. * * Returns the number of IOThreads or -1 in case of error. * On success, the array of information is stored into @info. The caller is * responsible for calling virDomainIOThreadInfoFree() on each array element, * then calling free() on @info. On error, @info is set to NULL. */ int virDomainGetIOThreadInfo(virDomainPtr dom, virDomainIOThreadInfoPtr **info, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "info=%p flags=%x", info, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(info, error); *info = NULL; VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); if (dom->conn->driver->domainGetIOThreadInfo) { int ret; ret = dom->conn->driver->domainGetIOThreadInfo(dom, info, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainIOThreadInfoFree: * @info: pointer to a virDomainIOThreadInfo object * * Frees the memory used by @info. */ void virDomainIOThreadInfoFree(virDomainIOThreadInfoPtr info) { if (!info) return; VIR_FREE(info->cpumap); VIR_FREE(info); } /** * virDomainPinIOThread: * @domain: a domain object * @iothread_id: the IOThread ID to set the CPU affinity * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN) * Each bit set to 1 means that corresponding CPU is usable. * Bytes are stored in little-endian order: CPU0-7, 8-15... * In each byte, lowest CPU number is least significant bit. * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in * underlying virtualization system (Xen...). * If maplen < size, missing bytes are set to zero. * If maplen > size, failure code is returned. * @flags: bitwise-OR of virDomainModificationImpact * * Dynamically change the real CPUs which can be allocated to an IOThread. * This function may require privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain * and may fail if domain is not alive. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified (that is, * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies * persistent setup, while an active domain is hypervisor-dependent on whether * just live or both live and persistent state is changed. * Not all hypervisors can support all flag combinations. * * See also virDomainGetIOThreadInfo for querying this information. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainPinIOThread(virDomainPtr domain, unsigned int iothread_id, unsigned char *cpumap, int maplen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "iothread_id=%u, cpumap=%p, maplen=%d", iothread_id, cpumap, maplen); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(cpumap, error); virCheckPositiveArgGoto(maplen, error); if (conn->driver->domainPinIOThread) { int ret; ret = conn->driver->domainPinIOThread(domain, iothread_id, cpumap, maplen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainAddIOThread: * @domain: a domain object * @iothread_id: the specific IOThread ID value to add * @flags: bitwise-OR of virDomainModificationImpact * * Dynamically add an IOThread to the domain. It is left up to the * underlying virtual hypervisor to determine the valid range for an * @iothread_id and determining whether the @iothread_id already exists. * * Note that this call can fail if the underlying virtualization hypervisor * does not support it or if growing the number is arbitrarily limited. * This function requires privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain * and may fail if domain is not alive. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified (that is, * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies * persistent setup, while an active domain is hypervisor-dependent on whether * just live or both live and persistent state is changed. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainAddIOThread(virDomainPtr domain, unsigned int iothread_id, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "iothread_id=%u, flags=%x", iothread_id, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); conn = domain->conn; if (conn->driver->domainAddIOThread) { int ret; ret = conn->driver->domainAddIOThread(domain, iothread_id, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainDelIOThread: * @domain: a domain object * @iothread_id: the specific IOThread ID value to delete * @flags: bitwise-OR of virDomainModificationImpact * * Dynamically delete an IOThread from the domain. The @iothread_id to be * deleted must not have a resource associated with it and can be any of * the currently valid IOThread ID's. * * Note that this call can fail if the underlying virtualization hypervisor * does not support it or if reducing the number is arbitrarily limited. * This function requires privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain * and may fail if domain is not alive. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified (that is, * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies * persistent setup, while an active domain is hypervisor-dependent on whether * just live or both live and persistent state is changed. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainDelIOThread(virDomainPtr domain, unsigned int iothread_id, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "iothread_id=%u, flags=%x", iothread_id, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); virCheckNonZeroArgGoto(iothread_id, error); conn = domain->conn; if (conn->driver->domainDelIOThread) { int ret; ret = conn->driver->domainDelIOThread(domain, iothread_id, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetSecurityLabel: * @domain: a domain object * @seclabel: pointer to a virSecurityLabel structure * * Extract security label of an active domain. The 'label' field * in the @seclabel argument will be initialized to the empty * string if the domain is not running under a security model. * * Returns 0 in case of success, -1 in case of failure */ int virDomainGetSecurityLabel(virDomainPtr domain, virSecurityLabelPtr seclabel) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "seclabel=%p", seclabel); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(seclabel, error); if (conn->driver->domainGetSecurityLabel) { int ret; ret = conn->driver->domainGetSecurityLabel(domain, seclabel); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetSecurityLabelList: * @domain: a domain object * @seclabels: will be auto-allocated and filled with domains' security labels. * Caller must free memory on return. * * Extract the security labels of an active domain. The 'label' field * in the @seclabels argument will be initialized to the empty * string if the domain is not running under a security model. * * Returns number of elemnets in @seclabels on success, -1 in case of failure. */ int virDomainGetSecurityLabelList(virDomainPtr domain, virSecurityLabelPtr* seclabels) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "seclabels=%p", seclabels); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(seclabels, error); conn = domain->conn; if (conn->driver->domainGetSecurityLabelList) { int ret; ret = conn->driver->domainGetSecurityLabelList(domain, seclabels); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetMetadata: * @domain: a domain object * @type: type of metadata, from virDomainMetadataType * @metadata: new metadata text * @key: XML namespace key, or NULL * @uri: XML namespace URI, or NULL * @flags: bitwise-OR of virDomainModificationImpact * * Sets the appropriate domain element given by @type to the * value of @metadata. A @type of VIR_DOMAIN_METADATA_DESCRIPTION * is free-form text; VIR_DOMAIN_METADATA_TITLE is free-form, but no * newlines are permitted, and should be short (although the length is * not enforced). For these two options @key and @uri are irrelevant and * must be set to NULL. * * For type VIR_DOMAIN_METADATA_ELEMENT @metadata must be well-formed * XML belonging to namespace defined by @uri with local name @key. * * Passing NULL for @metadata says to remove that element from the * domain XML (passing the empty string leaves the element present). * * The resulting metadata will be present in virDomainGetXMLDesc(), * as well as quick access through virDomainGetMetadata(). * * @flags controls whether the live domain, persistent configuration, * or both will be modified. * * Returns 0 on success, -1 in case of failure. */ int virDomainSetMetadata(virDomainPtr domain, int type, const char *metadata, const char *key, const char *uri, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "type=%d, metadata='%s', key='%s', uri='%s', flags=%x", type, NULLSTR(metadata), NULLSTR(key), NULLSTR(uri), flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); switch (type) { case VIR_DOMAIN_METADATA_TITLE: if (metadata && strchr(metadata, '\n')) { virReportInvalidArg(metadata, "%s", _("metadata title can't contain " "newlines")); goto error; } /* fallthrough */ case VIR_DOMAIN_METADATA_DESCRIPTION: virCheckNullArgGoto(uri, error); virCheckNullArgGoto(key, error); break; case VIR_DOMAIN_METADATA_ELEMENT: virCheckNonNullArgGoto(uri, error); if (metadata) virCheckNonNullArgGoto(key, error); break; default: /* For future expansion */ break; } if (conn->driver->domainSetMetadata) { int ret; ret = conn->driver->domainSetMetadata(domain, type, metadata, key, uri, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetMetadata: * @domain: a domain object * @type: type of metadata, from virDomainMetadataType * @uri: XML namespace identifier * @flags: bitwise-OR of virDomainModificationImpact * * Retrieves the appropriate domain element given by @type. * If VIR_DOMAIN_METADATA_ELEMENT is requested parameter @uri * must be set to the name of the namespace the requested elements * belong to, otherwise must be NULL. * * If an element of the domain XML is not present, the resulting * error will be VIR_ERR_NO_DOMAIN_METADATA. This method forms * a shortcut for seeing information from virDomainSetMetadata() * without having to go through virDomainGetXMLDesc(). * * @flags controls whether the live domain or persistent * configuration will be queried. * * Returns the metadata string on success (caller must free), * or NULL in case of failure. */ char * virDomainGetMetadata(virDomainPtr domain, int type, const char *uri, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "type=%d, uri='%s', flags=%x", type, NULLSTR(uri), flags); virResetLastError(); virCheckDomainReturn(domain, NULL); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); switch (type) { case VIR_DOMAIN_METADATA_TITLE: case VIR_DOMAIN_METADATA_DESCRIPTION: virCheckNullArgGoto(uri, error); break; case VIR_DOMAIN_METADATA_ELEMENT: virCheckNonNullArgGoto(uri, error); break; default: /* For future expansion */ break; } conn = domain->conn; if (conn->driver->domainGetMetadata) { char *ret; if (!(ret = conn->driver->domainGetMetadata(domain, type, uri, flags))) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virDomainAttachDevice: * @domain: pointer to domain object * @xml: pointer to XML description of one device * * Create a virtual device attachment to backend. This function, * having hotplug semantics, is only allowed on an active domain. * * For compatibility, this method can also be used to change the media * in an existing CDROM/Floppy device, however, applications are * recommended to use the virDomainUpdateDeviceFlag method instead. * * Be aware that hotplug changes might not persist across a domain going * into S4 state (also known as hibernation) unless you also modify the * persistent domain definition. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainAttachDevice(virDomainPtr domain, const char *xml) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xml=%s", xml); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(xml, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainAttachDevice) { int ret; ret = conn->driver->domainAttachDevice(domain, xml); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainAttachDeviceFlags: * @domain: pointer to domain object * @xml: pointer to XML description of one device * @flags: bitwise-OR of virDomainDeviceModifyFlags * * Attach a virtual device to a domain, using the flags parameter * to control how the device is attached. VIR_DOMAIN_AFFECT_CURRENT * specifies that the device allocation is made based on current domain * state. VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be * allocated to the active domain instance only and is not added to the * persisted domain configuration. VIR_DOMAIN_AFFECT_CONFIG * specifies that the device shall be allocated to the persisted domain * configuration only. Note that the target hypervisor must return an * error if unable to satisfy flags. E.g. the hypervisor driver will * return failure if LIVE is specified but it only supports modifying the * persisted device allocation. * * For compatibility, this method can also be used to change the media * in an existing CDROM/Floppy device, however, applications are * recommended to use the virDomainUpdateDeviceFlag method instead. * * Be aware that hotplug changes might not persist across a domain going * into S4 state (also known as hibernation) unless you also modify the * persistent domain definition. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainAttachDeviceFlags(virDomainPtr domain, const char *xml, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=%x", xml, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(xml, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainAttachDeviceFlags) { int ret; ret = conn->driver->domainAttachDeviceFlags(domain, xml, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainDetachDevice: * @domain: pointer to domain object * @xml: pointer to XML description of one device * * This is an equivalent of virDomainDetachDeviceFlags() when called with * @flags parameter set to VIR_DOMAIN_AFFECT_LIVE. * * See virDomainDetachDeviceFlags() for more details. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainDetachDevice(virDomainPtr domain, const char *xml) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xml=%s", xml); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(xml, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainDetachDevice) { int ret; ret = conn->driver->domainDetachDevice(domain, xml); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainDetachDeviceFlags: * @domain: pointer to domain object * @xml: pointer to XML description of one device * @flags: bitwise-OR of virDomainDeviceModifyFlags * * Detach a virtual device from a domain, using the flags parameter * to control how the device is detached. VIR_DOMAIN_AFFECT_CURRENT * specifies that the device allocation is removed based on current domain * state. VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be * deallocated from the active domain instance only and is not from the * persisted domain configuration. VIR_DOMAIN_AFFECT_CONFIG * specifies that the device shall be deallocated from the persisted domain * configuration only. Note that the target hypervisor must return an * error if unable to satisfy flags. E.g. the hypervisor driver will * return failure if LIVE is specified but it only supports removing the * persisted device allocation. * * Some hypervisors may prevent this operation if there is a current * block copy operation on the device being detached; in that case, * use virDomainBlockJobAbort() to stop the block copy first. * * Beware that depending on the hypervisor and device type, detaching a device * from a running domain may be asynchronous. That is, calling * virDomainDetachDeviceFlags may just request device removal while the device * is actually removed later (in cooperation with a guest OS). Previously, * this fact was ignored and the device could have been removed from domain * configuration before it was actually removed by the hypervisor causing * various failures on subsequent operations. To check whether the device was * successfully removed, either recheck domain configuration using * virDomainGetXMLDesc() or add a handler for the VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED * event. In case the device is already gone when virDomainDetachDeviceFlags * returns, the event is delivered before this API call ends. To help existing * clients work better in most cases, this API will try to transform an * asynchronous device removal that finishes shortly after the request into * a synchronous removal. In other words, this API may wait a bit for the * removal to complete in case it was not synchronous. * * Be aware that hotplug changes might not persist across a domain going * into S4 state (also known as hibernation) unless you also modify the * persistent domain definition. * * The supplied XML description of the device should be as specific * as its definition in the domain XML. The set of attributes used * to match the device are internal to the drivers. Using a partial definition, * or attempting to detach a device that is not present in the domain XML, * but shares some specific attributes with one that is present, * may lead to unexpected results. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainDetachDeviceFlags(virDomainPtr domain, const char *xml, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=%x", xml, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(xml, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainDetachDeviceFlags) { int ret; ret = conn->driver->domainDetachDeviceFlags(domain, xml, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainUpdateDeviceFlags: * @domain: pointer to domain object * @xml: pointer to XML description of one device * @flags: bitwise-OR of virDomainDeviceModifyFlags * * Change a virtual device on a domain, using the flags parameter * to control how the device is changed. VIR_DOMAIN_AFFECT_CURRENT * specifies that the device change is made based on current domain * state. VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be * changed on the active domain instance only and is not added to the * persisted domain configuration. VIR_DOMAIN_AFFECT_CONFIG * specifies that the device shall be changed on the persisted domain * configuration only. Note that the target hypervisor must return an * error if unable to satisfy flags. E.g. the hypervisor driver will * return failure if LIVE is specified but it only supports modifying the * persisted device allocation. * * This method is used for actions such changing CDROM/Floppy device * media, altering the graphics configuration such as password, * reconfiguring the NIC device backend connectivity, etc. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainUpdateDeviceFlags(virDomainPtr domain, const char *xml, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=%x", xml, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(xml, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainUpdateDeviceFlags) { int ret; ret = conn->driver->domainUpdateDeviceFlags(domain, xml, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virConnectDomainEventRegister: * @conn: pointer to the connection * @cb: callback to the function handling domain events * @opaque: opaque data to pass on to the callback * @freecb: optional function to deallocate opaque when not used anymore * * Adds a callback to receive notifications of domain lifecycle events * occurring on a connection. This function requires that an event loop * has been previously registered with virEventRegisterImpl() or * virEventRegisterDefaultImpl(). * * Use of this method is no longer recommended. Instead applications * should try virConnectDomainEventRegisterAny() which has a more flexible * API contract. * * The virDomainPtr object handle passed into the callback upon delivery * of an event is only valid for the duration of execution of the callback. * If the callback wishes to keep the domain object after the callback returns, * it shall take a reference to it, by calling virDomainRef. * The reference can be released once the object is no longer required * by calling virDomainFree. * * Returns 0 on success, -1 on failure. Older versions of some hypervisors * sometimes returned a positive number on success, but without any reliable * semantics on what that number represents. */ int virConnectDomainEventRegister(virConnectPtr conn, virConnectDomainEventCallback cb, void *opaque, virFreeCallback freecb) { VIR_DEBUG("conn=%p, cb=%p, opaque=%p, freecb=%p", conn, cb, opaque, freecb); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNullArgGoto(cb, error); if (conn->driver && conn->driver->connectDomainEventRegister) { int ret; ret = conn->driver->connectDomainEventRegister(conn, cb, opaque, freecb); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectDomainEventDeregister: * @conn: pointer to the connection * @cb: callback to the function handling domain events * * Removes a callback previously registered with the * virConnectDomainEventRegister() function. * * Use of this method is no longer recommended. Instead applications * should try virConnectDomainEventDeregisterAny() which has a more flexible * API contract * * Returns 0 on success, -1 on failure. Older versions of some hypervisors * sometimes returned a positive number on success, but without any reliable * semantics on what that number represents. */ int virConnectDomainEventDeregister(virConnectPtr conn, virConnectDomainEventCallback cb) { VIR_DEBUG("conn=%p, cb=%p", conn, cb); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNullArgGoto(cb, error); if (conn->driver && conn->driver->connectDomainEventDeregister) { int ret; ret = conn->driver->connectDomainEventDeregister(conn, cb); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainIsActive: * @dom: pointer to the domain object * * Determine if the domain is currently running * * Returns 1 if running, 0 if inactive, -1 on error */ int virDomainIsActive(virDomainPtr dom) { VIR_DEBUG("dom=%p", dom); virResetLastError(); virCheckDomainReturn(dom, -1); if (dom->conn->driver->domainIsActive) { int ret; ret = dom->conn->driver->domainIsActive(dom); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainIsPersistent: * @dom: pointer to the domain object * * Determine if the domain has a persistent configuration * which means it will still exist after shutting down * * Returns 1 if persistent, 0 if transient, -1 on error */ int virDomainIsPersistent(virDomainPtr dom) { VIR_DOMAIN_DEBUG(dom); virResetLastError(); virCheckDomainReturn(dom, -1); if (dom->conn->driver->domainIsPersistent) { int ret; ret = dom->conn->driver->domainIsPersistent(dom); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainRename: * @dom: pointer to the domain object * @new_name: new domain name * @flags: extra flags; not used yet, so callers should always pass 0 * * Rename a domain. New domain name is specified in the second * argument. Depending on each driver implementation it may be * required that domain is in a specific state. * * There might be some attributes and/or elements in domain XML that if no * value provided at XML defining time, libvirt will derive their value from * the domain name. These are not updated by this API. Users are strongly * advised to change these after the rename was successful. * * Returns 0 if successfully renamed, -1 on error */ int virDomainRename(virDomainPtr dom, const char *new_name, unsigned int flags) { VIR_DEBUG("dom=%p, new_name=%s", dom, NULLSTR(new_name)); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(new_name, error); virCheckReadOnlyGoto(dom->conn->flags, error); if (dom->conn->driver->domainRename) { int ret = dom->conn->driver->domainRename(dom, new_name, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainIsUpdated: * @dom: pointer to the domain object * * Determine if the domain has been updated. * * Returns 1 if updated, 0 if not, -1 on error */ int virDomainIsUpdated(virDomainPtr dom) { VIR_DOMAIN_DEBUG(dom); virResetLastError(); virCheckDomainReturn(dom, -1); if (dom->conn->driver->domainIsUpdated) { int ret; ret = dom->conn->driver->domainIsUpdated(dom); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetJobInfo: * @domain: a domain object * @info: pointer to a virDomainJobInfo structure allocated by the user * * Extract information about progress of a background job on a domain. * Will return an error if the domain is not active. * * This function returns a limited amount of information in comparison * to virDomainGetJobStats(). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetJobInfo(virDomainPtr domain, virDomainJobInfoPtr info) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "info=%p", info); virResetLastError(); if (info) memset(info, 0, sizeof(*info)); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(info, error); conn = domain->conn; if (conn->driver->domainGetJobInfo) { int ret; ret = conn->driver->domainGetJobInfo(domain, info); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetJobStats: * @domain: a domain object * @type: where to store the job type (one of virDomainJobType) * @params: where to store job statistics * @nparams: number of items in @params * @flags: bitwise-OR of virDomainGetJobStatsFlags * * Extract information about progress of a background job on a domain. * Will return an error if the domain is not active. The function returns * a superset of progress information provided by virDomainGetJobInfo. * Possible fields returned in @params are defined by VIR_DOMAIN_JOB_* * macros and new fields will likely be introduced in the future so callers * may receive fields that they do not understand in case they talk to a * newer server. * * When @flags contains VIR_DOMAIN_JOB_STATS_COMPLETED, the function will * return statistics about a recently completed job. Specifically, this * flag may be used to query statistics of a completed incoming migration. * Statistics of a completed job are automatically destroyed once read or * when libvirtd is restarted. Note that time information returned for * completed migrations may be completely irrelevant unless both source and * destination hosts have synchronized time (i.e., NTP daemon is running on * both of them). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetJobStats(virDomainPtr domain, int *type, virTypedParameterPtr *params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "type=%p, params=%p, nparams=%p, flags=%x", type, params, nparams, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(type, error); virCheckNonNullArgGoto(params, error); virCheckNonNullArgGoto(nparams, error); conn = domain->conn; if (conn->driver->domainGetJobStats) { int ret; ret = conn->driver->domainGetJobStats(domain, type, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainAbortJob: * @domain: a domain object * * Requests that the current background job be aborted at the * soonest opportunity. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainAbortJob(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainAbortJob) { int ret; ret = conn->driver->domainAbortJob(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainMigrateSetMaxDowntime: * @domain: a domain object * @downtime: maximum tolerable downtime for live migration, in milliseconds * @flags: extra flags; not used yet, so callers should always pass 0 * * Sets maximum tolerable time for which the domain is allowed to be paused * at the end of live migration. It's supposed to be called while the domain is * being live-migrated as a reaction to migration progress. * * Returns 0 in case of success, -1 otherwise. */ int virDomainMigrateSetMaxDowntime(virDomainPtr domain, unsigned long long downtime, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "downtime=%llu, flags=%x", downtime, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateSetMaxDowntime) { if (conn->driver->domainMigrateSetMaxDowntime(domain, downtime, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainMigrateGetCompressionCache: * @domain: a domain object * @cacheSize: return value of current size of the cache (in bytes) * @flags: extra flags; not used yet, so callers should always pass 0 * * Gets current size of the cache (in bytes) used for compressing repeatedly * transferred memory pages during live migration. * * Returns 0 in case of success, -1 otherwise. */ int virDomainMigrateGetCompressionCache(virDomainPtr domain, unsigned long long *cacheSize, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cacheSize=%p, flags=%x", cacheSize, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(cacheSize, error); if (conn->driver->domainMigrateGetCompressionCache) { if (conn->driver->domainMigrateGetCompressionCache(domain, cacheSize, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainMigrateSetCompressionCache: * @domain: a domain object * @cacheSize: size of the cache (in bytes) used for compression * @flags: extra flags; not used yet, so callers should always pass 0 * * Sets size of the cache (in bytes) used for compressing repeatedly * transferred memory pages during live migration. It's supposed to be called * while the domain is being live-migrated as a reaction to migration progress * and increasing number of compression cache misses obtained from * virDomainGetJobStats. * * Returns 0 in case of success, -1 otherwise. */ int virDomainMigrateSetCompressionCache(virDomainPtr domain, unsigned long long cacheSize, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cacheSize=%llu, flags=%x", cacheSize, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateSetCompressionCache) { if (conn->driver->domainMigrateSetCompressionCache(domain, cacheSize, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainMigrateSetMaxSpeed: * @domain: a domain object * @bandwidth: migration bandwidth limit in MiB/s * @flags: extra flags; not used yet, so callers should always pass 0 * * The maximum bandwidth (in MiB/s) that will be used to do migration * can be specified with the bandwidth parameter. Not all hypervisors * will support a bandwidth cap * * Returns 0 in case of success, -1 otherwise. */ int virDomainMigrateSetMaxSpeed(virDomainPtr domain, unsigned long bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "bandwidth=%lu, flags=%x", bandwidth, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateSetMaxSpeed) { if (conn->driver->domainMigrateSetMaxSpeed(domain, bandwidth, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainMigrateGetMaxSpeed: * @domain: a domain object * @bandwidth: return value of current migration bandwidth limit in MiB/s * @flags: extra flags; not used yet, so callers should always pass 0 * * Get the current maximum bandwidth (in MiB/s) that will be used if the * domain is migrated. Not all hypervisors will support a bandwidth limit. * * Returns 0 in case of success, -1 otherwise. */ int virDomainMigrateGetMaxSpeed(virDomainPtr domain, unsigned long *bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "bandwidth = %p, flags=%x", bandwidth, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(bandwidth, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateGetMaxSpeed) { if (conn->driver->domainMigrateGetMaxSpeed(domain, bandwidth, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectDomainEventRegisterAny: * @conn: pointer to the connection * @dom: pointer to the domain * @eventID: the event type to receive * @cb: callback to the function handling domain events * @opaque: opaque data to pass on to the callback * @freecb: optional function to deallocate opaque when not used anymore * * Adds a callback to receive notifications of arbitrary domain events * occurring on a domain. This function requires that an event loop * has been previously registered with virEventRegisterImpl() or * virEventRegisterDefaultImpl(). * * If @dom is NULL, then events will be monitored for any domain. If @dom * is non-NULL, then only the specific domain will be monitored. * * Most types of event have a callback providing a custom set of parameters * for the event. When registering an event, it is thus necessary to use * the VIR_DOMAIN_EVENT_CALLBACK() macro to cast the supplied function pointer * to match the signature of this method. * * The virDomainPtr object handle passed into the callback upon delivery * of an event is only valid for the duration of execution of the callback. * If the callback wishes to keep the domain object after the callback returns, * it shall take a reference to it, by calling virDomainRef(). * The reference can be released once the object is no longer required * by calling virDomainFree(). * * The return value from this method is a positive integer identifier * for the callback. To unregister a callback, this callback ID should * be passed to the virConnectDomainEventDeregisterAny() method. * * Returns a callback identifier on success, -1 on failure. */ int virConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID, virConnectDomainEventGenericCallback cb, void *opaque, virFreeCallback freecb) { VIR_DOMAIN_DEBUG(dom, "conn=%p, eventID=%d, cb=%p, opaque=%p, freecb=%p", conn, eventID, cb, opaque, freecb); virResetLastError(); virCheckConnectReturn(conn, -1); if (dom) { virCheckDomainGoto(dom, error); if (dom->conn != conn) { virReportInvalidArg(dom, _("domain '%s' must match connection"), dom->name); goto error; } } virCheckNonNullArgGoto(cb, error); virCheckNonNegativeArgGoto(eventID, error); if (eventID >= VIR_DOMAIN_EVENT_ID_LAST) { virReportInvalidArg(eventID, _("eventID must be less than %d"), VIR_DOMAIN_EVENT_ID_LAST); goto error; } if (conn->driver && conn->driver->connectDomainEventRegisterAny) { int ret; ret = conn->driver->connectDomainEventRegisterAny(conn, dom, eventID, cb, opaque, freecb); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectDomainEventDeregisterAny: * @conn: pointer to the connection * @callbackID: the callback identifier * * Removes an event callback. The callbackID parameter should be the * value obtained from a previous virConnectDomainEventRegisterAny() method. * * Returns 0 on success, -1 on failure. Older versions of some hypervisors * sometimes returned a positive number on success, but without any reliable * semantics on what that number represents. */ int virConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID) { VIR_DEBUG("conn=%p, callbackID=%d", conn, callbackID); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNegativeArgGoto(callbackID, error); if (conn->driver && conn->driver->connectDomainEventDeregisterAny) { int ret; ret = conn->driver->connectDomainEventDeregisterAny(conn, callbackID); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainManagedSave: * @dom: pointer to the domain * @flags: bitwise-OR of virDomainSaveRestoreFlags * * This method will suspend a domain and save its memory contents to * a file on disk. After the call, if successful, the domain is not * listed as running anymore. * The difference from virDomainSave() is that libvirt is keeping track of * the saved state itself, and will reuse it once the domain is being * restarted (automatically or via an explicit libvirt call). * As a result any running domain is sure to not have a managed saved image. * This also implies that managed save only works on persistent domains, * since the domain must still exist in order to use virDomainCreate() to * restart it. * * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will * attempt to bypass the file system cache while creating the file, or * fail if it cannot do so for the given system; this can allow less * pressure on file system cache, but also risks slowing saves to NFS. * * Normally, the managed saved state will remember whether the domain * was running or paused, and start will resume to the same state. * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in * @flags will override the default saved into the file. These two * flags are mutually exclusive. * * Returns 0 in case of success or -1 in case of failure */ int virDomainManagedSave(virDomainPtr dom, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING, VIR_DOMAIN_SAVE_PAUSED, error); if (conn->driver->domainManagedSave) { int ret; ret = conn->driver->domainManagedSave(dom, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainHasManagedSaveImage: * @dom: pointer to the domain * @flags: extra flags; not used yet, so callers should always pass 0 * * Check if a domain has a managed save image as created by * virDomainManagedSave(). Note that any running domain should not have * such an image, as it should have been removed on restart. * * Returns 0 if no image is present, 1 if an image is present, and * -1 in case of error */ int virDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; if (conn->driver->domainHasManagedSaveImage) { int ret; ret = conn->driver->domainHasManagedSaveImage(dom, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainManagedSaveRemove: * @dom: pointer to the domain * @flags: extra flags; not used yet, so callers should always pass 0 * * Remove any managed save image for this domain. * * Returns 0 in case of success, and -1 in case of error */ int virDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainManagedSaveRemove) { int ret; ret = conn->driver->domainManagedSaveRemove(dom, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainOpenConsole: * @dom: a domain object * @dev_name: the console, serial or parallel port device alias, or NULL * @st: a stream to associate with the console * @flags: bitwise-OR of virDomainConsoleFlags * * This opens the backend associated with a console, serial or * parallel port device on a guest, if the backend is supported. * If the @dev_name is omitted, then the first console or serial * device is opened. The console is associated with the passed * in @st stream, which should have been opened in non-blocking * mode for bi-directional I/O. * * By default, when @flags is 0, the open will fail if libvirt * detects that the console is already in use by another client; * passing VIR_DOMAIN_CONSOLE_FORCE will cause libvirt to forcefully * remove the other client prior to opening this console. * * If flag VIR_DOMAIN_CONSOLE_SAFE the console is opened only in the * case where the hypervisor driver supports safe (mutually exclusive) * console handling. * * Older servers did not support either flag, and also did not forbid * simultaneous clients on a console, with potentially confusing results. * When passing @flags of 0 in order to support a wider range of server * versions, it is up to the client to ensure mutual exclusion. * * Returns 0 if the console was opened, -1 on error */ int virDomainOpenConsole(virDomainPtr dom, const char *dev_name, virStreamPtr st, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "dev_name=%s, st=%p, flags=%x", NULLSTR(dev_name), st, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckStreamGoto(st, error); virCheckReadOnlyGoto(conn->flags, error); if (conn != st->conn) { virReportInvalidArg(st, _("stream must match connection of domain '%s'"), dom->name); goto error; } if (conn->driver->domainOpenConsole) { int ret; ret = conn->driver->domainOpenConsole(dom, dev_name, st, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainOpenChannel: * @dom: a domain object * @name: the channel name, or NULL * @st: a stream to associate with the channel * @flags: bitwise-OR of virDomainChannelFlags * * This opens the host interface associated with a channel device on a * guest, if the host interface is supported. If @name is given, it * can match either the device alias (e.g. "channel0"), or the virtio * target name (e.g. "org.qemu.guest_agent.0"). If @name is omitted, * then the first channel is opened. The channel is associated with * the passed in @st stream, which should have been opened in * non-blocking mode for bi-directional I/O. * * By default, when @flags is 0, the open will fail if libvirt detects * that the channel is already in use by another client; passing * VIR_DOMAIN_CHANNEL_FORCE will cause libvirt to forcefully remove the * other client prior to opening this channel. * * Returns 0 if the channel was opened, -1 on error */ int virDomainOpenChannel(virDomainPtr dom, const char *name, virStreamPtr st, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "name=%s, st=%p, flags=%x", NULLSTR(name), st, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckStreamGoto(st, error); virCheckReadOnlyGoto(conn->flags, error); if (conn != st->conn) { virReportInvalidArg(st, _("stream must match connection of domain '%s'"), dom->name); goto error; } if (conn->driver->domainOpenChannel) { int ret; ret = conn->driver->domainOpenChannel(dom, name, st, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainBlockJobAbort: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @flags: bitwise-OR of virDomainBlockJobAbortFlags * * Cancel the active block job on the given disk. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * If the current block job for @disk is VIR_DOMAIN_BLOCK_JOB_TYPE_PULL, then * by default, this function performs a synchronous operation and the caller * may assume that the operation has completed when 0 is returned. However, * BlockJob operations may take a long time to cancel, and during this time * further domain interactions may be unresponsive. To avoid this problem, * pass VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC in the @flags argument to enable * asynchronous behavior, returning as soon as possible. When the job has * been canceled, a BlockJob event will be emitted, with status * VIR_DOMAIN_BLOCK_JOB_CANCELED (even if the ABORT_ASYNC flag was not * used); it is also possible to poll virDomainBlockJobInfo() to see if * the job cancellation is still pending. This type of job can be restarted * to pick up from where it left off. * * If the current block job for @disk is VIR_DOMAIN_BLOCK_JOB_TYPE_COPY, then * the default is to abort the mirroring and revert to the source disk; * likewise, if the current job is VIR_DOMAIN_BLOCK_JOB_TYPE_ACTIVE_COMMIT, * the default is to abort without changing the active layer of @disk. * Adding @flags of VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT causes this call to * fail with VIR_ERR_BLOCK_COPY_ACTIVE if the copy or commit is not yet * ready; otherwise it will swap the disk over to the new active image * to end the mirroring or active commit. An event will be issued when the * job is ended, and it is possible to use VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC * to control whether this command waits for the completion of the job. * Restarting a copy or active commit job requires starting over from the * beginning of the first phase. * * Returns -1 in case of failure, 0 when successful. */ int virDomainBlockJobAbort(virDomainPtr dom, const char *disk, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, flags=%x", disk, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (conn->driver->domainBlockJobAbort) { int ret; ret = conn->driver->domainBlockJobAbort(dom, disk, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetBlockJobInfo: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @info: pointer to a virDomainBlockJobInfo structure * @flags: bitwise-OR of virDomainBlockJobInfoFlags * * Request block job information for the given disk. If an operation is active * @info will be updated with the current progress. The units used for the * bandwidth field of @info depends on @flags. If @flags includes * VIR_DOMAIN_BLOCK_JOB_INFO_BANDWIDTH_BYTES, bandwidth is in bytes/second * (although this mode can risk failure due to overflow, depending on both * client and server word size); otherwise, the value is rounded up to MiB/s. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * Returns -1 in case of failure, 0 when nothing found, 1 when info was found. */ int virDomainGetBlockJobInfo(virDomainPtr dom, const char *disk, virDomainBlockJobInfoPtr info, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, info=%p, flags=%x", disk, info, flags); virResetLastError(); if (info) memset(info, 0, sizeof(*info)); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckNonNullArgGoto(disk, error); virCheckNonNullArgGoto(info, error); if (conn->driver->domainGetBlockJobInfo) { int ret; ret = conn->driver->domainGetBlockJobInfo(dom, disk, info, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockJobSetSpeed: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @bandwidth: specify bandwidth limit; flags determine the unit * @flags: bitwise-OR of virDomainBlockJobSetSpeedFlags * * Set the maximimum allowable bandwidth that a block job may consume. If * bandwidth is 0, the limit will revert to the hypervisor default of * unlimited. * * If @flags contains VIR_DOMAIN_BLOCK_JOB_SPEED_BANDWIDTH_BYTES, @bandwidth * is in bytes/second; otherwise, it is in MiB/second. Values larger than * 2^52 bytes/sec may be rejected due to overflow considerations based on * the word size of both client and server, and values larger than 2^31 * bytes/sec may cause overflow problems if later queried by * virDomainGetBlockJobInfo() without scaling. Hypervisors may further * restrict the range of valid bandwidth values. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * Returns -1 in case of failure, 0 when successful. */ int virDomainBlockJobSetSpeed(virDomainPtr dom, const char *disk, unsigned long bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, bandwidth=%lu, flags=%x", disk, bandwidth, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (conn->driver->domainBlockJobSetSpeed) { int ret; ret = conn->driver->domainBlockJobSetSpeed(dom, disk, bandwidth, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockPull: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @bandwidth: (optional) specify bandwidth limit; flags determine the unit * @flags: bitwise-OR of virDomainBlockPullFlags * * Populate a disk image with data from its backing image. Once all data from * its backing image has been pulled, the disk no longer depends on a backing * image. This function pulls data for the entire device in the background. * Progress of the operation can be checked with virDomainGetBlockJobInfo() and * the operation can be aborted with virDomainBlockJobAbort(). When finished, * an asynchronous event is raised to indicate the final status. To move * data in the opposite direction, see virDomainBlockCommit(). * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * The maximum bandwidth that will be used to do the copy can be * specified with the @bandwidth parameter. If set to 0, there is no * limit. If @flags includes VIR_DOMAIN_BLOCK_PULL_BANDWIDTH_BYTES, * @bandwidth is in bytes/second; otherwise, it is in MiB/second. * Values larger than 2^52 bytes/sec may be rejected due to overflow * considerations based on the word size of both client and server, * and values larger than 2^31 bytes/sec may cause overflow problems * if later queried by virDomainGetBlockJobInfo() without scaling. * Hypervisors may further restrict the range of valid bandwidth * values. Some hypervisors do not support this feature and will * return an error if bandwidth is not 0; in this case, it might still * be possible for a later call to virDomainBlockJobSetSpeed() to * succeed. The actual speed can be determined with * virDomainGetBlockJobInfo(). * * This is shorthand for virDomainBlockRebase() with a NULL base. * * Returns 0 if the operation has started, -1 on failure. */ int virDomainBlockPull(virDomainPtr dom, const char *disk, unsigned long bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, bandwidth=%lu, flags=%x", disk, bandwidth, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (conn->driver->domainBlockPull) { int ret; ret = conn->driver->domainBlockPull(dom, disk, bandwidth, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockRebase: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @base: path to backing file to keep, or device shorthand, * or NULL for no backing file * @bandwidth: (optional) specify bandwidth limit; flags determine the unit * @flags: bitwise-OR of virDomainBlockRebaseFlags * * Populate a disk image with data from its backing image chain, and * setting the backing image to @base, or alternatively copy an entire * backing chain to a new file @base. * * When @flags is 0, this starts a pull, where @base must be the absolute * path of one of the backing images further up the chain, or NULL to * convert the disk image so that it has no backing image. Once all * data from its backing image chain has been pulled, the disk no * longer depends on those intermediate backing images. This function * pulls data for the entire device in the background. Progress of * the operation can be checked with virDomainGetBlockJobInfo() with a * job type of VIR_DOMAIN_BLOCK_JOB_TYPE_PULL, and the operation can be * aborted with virDomainBlockJobAbort(). When finished, an asynchronous * event is raised to indicate the final status, and the job no longer * exists. If the job is aborted, a new one can be started later to * resume from the same point. * * If @flags contains VIR_DOMAIN_BLOCK_REBASE_RELATIVE, the name recorded * into the active disk as the location for @base will be kept relative. * The operation will fail if libvirt can't infer the name. * * When @flags includes VIR_DOMAIN_BLOCK_REBASE_COPY, this starts a copy, * where @base must be the name of a new file to copy the chain to. By * default, the copy will pull the entire source chain into the destination * file, but if @flags also contains VIR_DOMAIN_BLOCK_REBASE_SHALLOW, then * only the top of the source chain will be copied (the source and * destination have a common backing file). By default, @base will be * created with the same file format as the source, but this can be altered * by adding VIR_DOMAIN_BLOCK_REBASE_COPY_RAW to force the copy to be raw * (does not make sense with the shallow flag unless the source is also raw), * or by using VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT to reuse an existing file * which was pre-created with the correct format and metadata and sufficient * size to hold the copy. In case the VIR_DOMAIN_BLOCK_REBASE_SHALLOW flag * is used the pre-created file has to exhibit the same guest visible contents * as the backing file of the original image. This allows a management app to * pre-create files with relative backing file names, rather than the default * of absolute backing file names; as a security precaution, you should * generally only use reuse_ext with the shallow flag and a non-raw * destination file. By default, the copy destination will be treated as * type='file', but using VIR_DOMAIN_BLOCK_REBASE_COPY_DEV treats the * destination as type='block' (affecting how virDomainGetBlockInfo() will * report allocation after pivoting). * * A copy job has two parts; in the first phase, the @bandwidth parameter * affects how fast the source is pulled into the destination, and the job * can only be canceled by reverting to the source file; progress in this * phase can be tracked via the virDomainBlockJobInfo() command, with a * job type of VIR_DOMAIN_BLOCK_JOB_TYPE_COPY. The job transitions to the * second phase when the job info states cur == end, and remains alive to * mirror all further changes to both source and destination. The user * must call virDomainBlockJobAbort() to end the mirroring while choosing * whether to revert to source or pivot to the destination. An event is * issued when the job ends, and depending on the hypervisor, an event may * also be issued when the job transitions from pulling to mirroring. If * the job is aborted, a new job will have to start over from the beginning * of the first phase. * * Some hypervisors will restrict certain actions, such as virDomainSave() * or virDomainDetachDevice(), while a copy job is active; they may * also restrict a copy job to transient domains. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or the device target shorthand (the * <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * The @base parameter can be either a path to a file within the backing * chain, or the device target shorthand (the <target dev='...'/> * sub-element, such as "vda") followed by an index to the backing chain * enclosed in square brackets. Backing chain indexes can be found by * inspecting //disk//backingStore/@index in the domain XML. Thus, for * example, "vda[3]" refers to the backing store with index equal to "3" * in the chain of disk "vda". * * The maximum bandwidth that will be used to do the copy can be * specified with the @bandwidth parameter. If set to 0, there is no * limit. If @flags includes VIR_DOMAIN_BLOCK_REBASE_BANDWIDTH_BYTES, * @bandwidth is in bytes/second; otherwise, it is in MiB/second. * Values larger than 2^52 bytes/sec may be rejected due to overflow * considerations based on the word size of both client and server, * and values larger than 2^31 bytes/sec may cause overflow problems * if later queried by virDomainGetBlockJobInfo() without scaling. * Hypervisors may further restrict the range of valid bandwidth * values. Some hypervisors do not support this feature and will * return an error if bandwidth is not 0; in this case, it might still * be possible for a later call to virDomainBlockJobSetSpeed() to * succeed. The actual speed can be determined with * virDomainGetBlockJobInfo(). * * When @base is NULL and @flags is 0, this is identical to * virDomainBlockPull(). When @flags contains VIR_DOMAIN_BLOCK_REBASE_COPY, * this command is shorthand for virDomainBlockCopy() where the destination * XML encodes @base as a <disk type='file'>, @bandwidth is properly scaled * and passed as a typed parameter, the shallow and reuse external flags * are preserved, and remaining flags control whether the XML encodes a * destination format of raw instead of leaving the destination identical * to the source format or probed from the reused file. * * Returns 0 if the operation has started, -1 on failure. */ int virDomainBlockRebase(virDomainPtr dom, const char *disk, const char *base, unsigned long bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, base=%s, bandwidth=%lu, flags=%x", disk, NULLSTR(base), bandwidth, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (flags & VIR_DOMAIN_BLOCK_REBASE_COPY) { virCheckNonNullArgGoto(base, error); } else if (flags & (VIR_DOMAIN_BLOCK_REBASE_SHALLOW | VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT | VIR_DOMAIN_BLOCK_REBASE_COPY_RAW | VIR_DOMAIN_BLOCK_REBASE_COPY_DEV)) { virReportInvalidArg(flags, "%s", _("use of flags requires a copy job")); goto error; } if (conn->driver->domainBlockRebase) { int ret; ret = conn->driver->domainBlockRebase(dom, disk, base, bandwidth, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockCopy: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @destxml: XML description of the copy destination * @params: Pointer to block copy parameter objects, or NULL * @nparams: Number of block copy parameters (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainBlockCopyFlags * * Copy the guest-visible contents of a disk image to a new file described * by @destxml. The destination XML has a top-level element of <disk>, and * resembles what is used when hot-plugging a disk via virDomainAttachDevice(), * except that only sub-elements related to describing the new host resource * are necessary (sub-elements related to the guest view, such as <target>, * are ignored). It is strongly recommended to include a <driver type='...'/> * format designation for the destination, to avoid the potential of any * security problem that might be caused by probing a file for its format. * * This command starts a long-running copy. By default, the copy will pull * the entire source chain into the destination file, but if @flags also * contains VIR_DOMAIN_BLOCK_COPY_SHALLOW, then only the top of the source * chain will be copied (the source and destination have a common backing * file). The format of the destination file is controlled by the <driver> * sub-element of the XML. The destination will be created unless the * VIR_DOMAIN_BLOCK_COPY_REUSE_EXT flag is present stating that the file * was pre-created with the correct format and metadata and sufficient * size to hold the copy. In case the VIR_DOMAIN_BLOCK_COPY_SHALLOW flag * is used the pre-created file has to exhibit the same guest visible contents * as the backing file of the original image. This allows a management app to * pre-create files with relative backing file names, rather than the default * of absolute backing file names. * * A copy job has two parts; in the first phase, the source is copied into * the destination, and the job can only be canceled by reverting to the * source file; progress in this phase can be tracked via the * virDomainBlockJobInfo() command, with a job type of * VIR_DOMAIN_BLOCK_JOB_TYPE_COPY. The job transitions to the second * phase when the job info states cur == end, and remains alive to mirror * all further changes to both source and destination. The user must * call virDomainBlockJobAbort() to end the mirroring while choosing * whether to revert to source or pivot to the destination. An event is * issued when the job ends, and depending on the hypervisor, an event may * also be issued when the job transitions from pulling to mirroring. If * the job is aborted, a new job will have to start over from the beginning * of the first phase. * * Some hypervisors will restrict certain actions, such as virDomainSave() * or virDomainDetachDevice(), while a copy job is active; they may * also restrict a copy job to transient domains. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or the device target shorthand (the * <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * The @params and @nparams arguments can be used to set hypervisor-specific * tuning parameters, such as maximum bandwidth or granularity. For a * parameter that the hypervisor understands, explicitly specifying 0 * behaves the same as omitting the parameter, to use the hypervisor * default; however, omitting a parameter is less likely to fail. * * This command is a superset of the older virDomainBlockRebase() when used * with the VIR_DOMAIN_BLOCK_REBASE_COPY flag, and offers better control * over the destination format, the ability to copy to a destination that * is not a local file, and the possibility of additional tuning parameters. * * Returns 0 if the operation has started, -1 on failure. */ int virDomainBlockCopy(virDomainPtr dom, const char *disk, const char *destxml, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, destxml=%s, params=%p, nparams=%d, flags=%x", disk, destxml, params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); virCheckNonNullArgGoto(destxml, error); virCheckNonNegativeArgGoto(nparams, error); if (nparams) virCheckNonNullArgGoto(params, error); if (conn->driver->domainBlockCopy) { int ret; ret = conn->driver->domainBlockCopy(dom, disk, destxml, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockCommit: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @base: path to backing file to merge into, or device shorthand, * or NULL for default * @top: path to file within backing chain that contains data to be merged, * or device shorthand, or NULL to merge all possible data * @bandwidth: (optional) specify bandwidth limit; flags determine the unit * @flags: bitwise-OR of virDomainBlockCommitFlags * * Commit changes that were made to temporary top-level files within a disk * image backing file chain into a lower-level base file. In other words, * take all the difference between @base and @top, and update @base to contain * that difference; after the commit, any portion of the chain that previously * depended on @top will now depend on @base, and all files after @base up * to and including @top will now be invalidated. A typical use of this * command is to reduce the length of a backing file chain after taking an * external disk snapshot. To move data in the opposite direction, see * virDomainBlockPull(). * * This command starts a long-running commit block job, whose status may * be tracked by virDomainBlockJobInfo() with a job type of * VIR_DOMAIN_BLOCK_JOB_TYPE_COMMIT, and the operation can be aborted with * virDomainBlockJobAbort(). When finished, an asynchronous event is * raised to indicate the final status, and the job no longer exists. If * the job is aborted, it is up to the hypervisor whether starting a new * job will resume from the same point, or start over. * * As a special case, if @top is the active image (or NULL), and @flags * includes VIR_DOMAIN_BLOCK_COMMIT_ACTIVE, the block job will have a type * of VIR_DOMAIN_BLOCK_JOB_TYPE_ACTIVE_COMMIT, and operates in two phases. * In the first phase, the contents are being committed into @base, and the * job can only be canceled. The job transitions to the second phase when * the job info states cur == end, and remains alive to keep all further * changes to @top synchronized into @base; an event with status * VIR_DOMAIN_BLOCK_JOB_READY is also issued to mark the job transition. * Once in the second phase, the user must choose whether to cancel the job * (keeping @top as the active image, but now containing only the changes * since the time the job ended) or to pivot the job (adjusting to @base as * the active image, and invalidating @top). * * Be aware that this command may invalidate files even if it is aborted; * the user is cautioned against relying on the contents of invalidated * intermediate files such as @top (when @top is not the active image) * without manually rebasing those files to use a backing file of a * read-only copy of @base prior to the point where the commit operation * was started (and such a rebase cannot be safely done until the commit * has successfully completed). However, the domain itself will not have * any issues; the active layer remains valid throughout the entire commit * operation. * * Some hypervisors may support a shortcut where if @flags contains * VIR_DOMAIN_BLOCK_COMMIT_DELETE, then this command will unlink all files * that were invalidated, after the commit successfully completes. * * If @flags contains VIR_DOMAIN_BLOCK_COMMIT_RELATIVE, the name recorded * into the overlay of the @top image (if there is such image) as the * path to the new backing file will be kept relative to other images. * The operation will fail if libvirt can't infer the name. * * By default, if @base is NULL, the commit target will be the bottom of * the backing chain; if @flags contains VIR_DOMAIN_BLOCK_COMMIT_SHALLOW, * then the immediate backing file of @top will be used instead. If @top * is NULL, the active image at the top of the chain will be used. Some * hypervisors place restrictions on how much can be committed, and might * fail if @base is not the immediate backing file of @top, or if @top is * the active layer in use by a running domain but @flags did not include * VIR_DOMAIN_BLOCK_COMMIT_ACTIVE, or if @top is not the top-most file; * restrictions may differ for online vs. offline domains. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or the device target shorthand (the * <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * The @base and @top parameters can be either paths to files within the * backing chain, or the device target shorthand (the <target dev='...'/> * sub-element, such as "vda") followed by an index to the backing chain * enclosed in square brackets. Backing chain indexes can be found by * inspecting //disk//backingStore/@index in the domain XML. Thus, for * example, "vda[3]" refers to the backing store with index equal to "3" * in the chain of disk "vda". * * The maximum bandwidth that will be used to do the commit can be * specified with the @bandwidth parameter. If set to 0, there is no * limit. If @flags includes VIR_DOMAIN_BLOCK_COMMIT_BANDWIDTH_BYTES, * @bandwidth is in bytes/second; otherwise, it is in MiB/second. * Values larger than 2^52 bytes/sec may be rejected due to overflow * considerations based on the word size of both client and server, * and values larger than 2^31 bytes/sec may cause overflow problems * if later queried by virDomainGetBlockJobInfo() without scaling. * Hypervisors may further restrict the range of valid bandwidth * values. Some hypervisors do not support this feature and will * return an error if bandwidth is not 0; in this case, it might still * be possible for a later call to virDomainBlockJobSetSpeed() to * succeed. The actual speed can be determined with * virDomainGetBlockJobInfo(). * * Returns 0 if the operation has started, -1 on failure. */ int virDomainBlockCommit(virDomainPtr dom, const char *disk, const char *base, const char *top, unsigned long bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, base=%s, top=%s, bandwidth=%lu, flags=%x", disk, NULLSTR(base), NULLSTR(top), bandwidth, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (conn->driver->domainBlockCommit) { int ret; ret = conn->driver->domainBlockCommit(dom, disk, base, top, bandwidth, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainOpenGraphics: * @dom: pointer to domain object * @idx: index of graphics config to open * @fd: file descriptor to attach graphics to * @flags: bitwise-OR of virDomainOpenGraphicsFlags * * This will attempt to connect the file descriptor @fd, to * the graphics backend of @dom. If @dom has multiple graphics * backends configured, then @idx will determine which one is * opened, starting from @idx 0. * * To disable any authentication, pass the VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH * constant for @flags. * * The caller should use an anonymous socketpair to open * @fd before invocation. * * This method can only be used when connected to a local * libvirt hypervisor, over a UNIX domain socket. Attempts * to use this method over a TCP connection will always fail * * Returns 0 on success, -1 on failure */ int virDomainOpenGraphics(virDomainPtr dom, unsigned int idx, int fd, unsigned int flags) { struct stat sb; VIR_DOMAIN_DEBUG(dom, "idx=%u, fd=%d, flags=%x", idx, fd, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNegativeArgGoto(fd, error); if (fstat(fd, &sb) < 0) { virReportSystemError(errno, _("Unable to access file descriptor %d"), fd); goto error; } if (!S_ISSOCK(sb.st_mode)) { virReportInvalidArg(fd, _("fd %d must be a socket"), fd); goto error; } virCheckReadOnlyGoto(dom->conn->flags, error); if (!VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn, VIR_DRV_FEATURE_FD_PASSING)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("fd passing is not supported by this connection")); goto error; } if (dom->conn->driver->domainOpenGraphics) { int ret; ret = dom->conn->driver->domainOpenGraphics(dom, idx, fd, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainOpenGraphicsFD: * @dom: pointer to domain object * @idx: index of graphics config to open * @flags: bitwise-OR of virDomainOpenGraphicsFlags * * This will create a socket pair connected to the graphics backend of @dom. * One end of the socket will be returned on success, and the other end is * handed to the hypervisor. * If @dom has multiple graphics backends configured, then @idx will determine * which one is opened, starting from @idx 0. * * To disable any authentication, pass the VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH * constant for @flags. * * This method can only be used when connected to a local * libvirt hypervisor, over a UNIX domain socket. Attempts * to use this method over a TCP connection will always fail. * * Returns an fd on success, -1 on failure */ int virDomainOpenGraphicsFD(virDomainPtr dom, unsigned int idx, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "idx=%u, flags=%x", idx, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); if (!VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn, VIR_DRV_FEATURE_FD_PASSING)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("fd passing is not supported by this connection")); goto error; } if (dom->conn->driver->domainOpenGraphicsFD) { int ret; ret = dom->conn->driver->domainOpenGraphicsFD(dom, idx, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainSetBlockIoTune: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @params: Pointer to blkio parameter objects * @nparams: Number of blkio parameters (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainModificationImpact * * Change all or a subset of the per-device block IO tunables. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or the device target shorthand (the <target * dev='...'/> sub-element, such as "xvda"). Valid names can be found * by calling virDomainGetXMLDesc() and inspecting elements * within //domain/devices/disk. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetBlockIoTune(virDomainPtr dom, const char *disk, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=%x", disk, params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); virCheckPositiveArgGoto(nparams, error); virCheckNonNullArgGoto(params, error); if (virTypedParameterValidateSet(dom->conn, params, nparams) < 0) goto error; if (conn->driver->domainSetBlockIoTune) { int ret; ret = conn->driver->domainSetBlockIoTune(dom, disk, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetBlockIoTune: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @params: Pointer to blkio parameter object * (return value, allocated by the caller) * @nparams: Pointer to number of blkio parameters * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all block IO tunable parameters for a given device. On input, * @nparams gives the size of the @params array; on output, @nparams * gives how many slots were filled with parameter information, which * might be less but will not exceed the input value. * * As a special case, calling with @params as NULL and @nparams as 0 * on input will cause @nparams on output to contain the number of * parameters supported by the hypervisor, either for the given @disk * (note that block devices of different types might support different * parameters), or if @disk is NULL, for all possible disks. The * caller should then allocate @params array, * i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API * again. See virDomainGetMemoryParameters() for more details. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or the device target shorthand (the <target * dev='...'/> sub-element, such as "xvda"). Valid names can be found * by calling virDomainGetXMLDesc() and inspecting elements * within //domain/devices/disk. This parameter cannot be NULL * unless @nparams is 0 on input. * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetBlockIoTune(virDomainPtr dom, const char *disk, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=%x", NULLSTR(disk), params, (nparams) ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) { virCheckNonNullArgGoto(params, error); virCheckNonNullArgGoto(disk, error); } if (VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); conn = dom->conn; if (conn->driver->domainGetBlockIoTune) { int ret; ret = conn->driver->domainGetBlockIoTune(dom, disk, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetCPUStats: * @domain: domain to query * @params: array to populate on output * @nparams: number of parameters per cpu * @start_cpu: which cpu to start with, or -1 for summary * @ncpus: how many cpus to query * @flags: bitwise-OR of virTypedParameterFlags * * Get statistics relating to CPU usage attributable to a single * domain (in contrast to the statistics returned by * virNodeGetCPUStats() for all processes on the host). @dom * must be running (an inactive domain has no attributable cpu * usage). On input, @params must contain at least @nparams * @ncpus * entries, allocated by the caller. * * If @start_cpu is -1, then @ncpus must be 1, and the returned * results reflect the statistics attributable to the entire * domain (such as user and system time for the process as a * whole). Otherwise, @start_cpu represents which cpu to start * with, and @ncpus represents how many consecutive processors to * query, with statistics attributable per processor (such as * per-cpu usage). If @ncpus is larger than the number of cpus * available to query, then the trailing part of the array will * be unpopulated. * * The remote driver imposes a limit of 128 @ncpus and 16 @nparams; * the number of parameters per cpu should not exceed 16, but if you * have a host with more than 128 CPUs, your program should split * the request into multiple calls. * * As special cases, if @params is NULL and @nparams is 0 and * @ncpus is 1, and the return value will be how many * statistics are available for the given @start_cpu. This number * may be different for @start_cpu of -1 than for any non-negative * value, but will be the same for all non-negative @start_cpu. * Likewise, if @params is NULL and @nparams is 0 and @ncpus is 0, * the number of cpus available to query is returned. From the * host perspective, this would typically match the cpus member * of virNodeGetInfo(), but might be less due to host cpu hotplug. * * For now, @flags is unused, and the statistics all relate to the * usage from the host perspective. It is possible that a future * version will support a flag that queries the cpu usage from the * guest's perspective, where the maximum cpu to query would be * related to virDomainGetVcpusFlags() rather than virNodeGetInfo(). * An individual guest vcpu cannot be reliably mapped back to a * specific host cpu unless a single-processor vcpu pinning was used, * but when @start_cpu is -1, any difference in usage between a host * and guest perspective would serve as a measure of hypervisor overhead. * * Typical use sequence is below. * * getting total stats: set start_cpu as -1, ncpus 1 * * virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0); // nparams * params = calloc(nparams, sizeof(virTypedParameter)) * virDomainGetCPUStats(dom, params, nparams, -1, 1, 0); // total stats. * * getting per-cpu stats: * * virDomainGetCPUStats(dom, NULL, 0, 0, 0, 0); // ncpus * virDomainGetCPUStats(dom, NULL, 0, 0, 1, 0); // nparams * params = calloc(ncpus * nparams, sizeof(virTypedParameter)); * virDomainGetCPUStats(dom, params, nparams, 0, ncpus, 0); // per-cpu stats * * Returns -1 on failure, or the number of statistics that were * populated per cpu on success (this will be less than the total * number of populated @params, unless @ncpus was 1; and may be * less than @nparams). The populated parameters start at each * stride of @nparams, which means the results may be discontiguous; * any unpopulated parameters will be zeroed on success (this includes * skipped elements if @nparams is too large, and tail elements if * @ncpus is too large). The caller is responsible for freeing any * returned string parameters. */ int virDomainGetCPUStats(virDomainPtr domain, virTypedParameterPtr params, unsigned int nparams, int start_cpu, unsigned int ncpus, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, start_cpu=%d, ncpus=%u, flags=%x", params, nparams, start_cpu, ncpus, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; /* Special cases: * start_cpu must be non-negative, or else -1 * if start_cpu is -1, ncpus must be 1 * params == NULL must match nparams == 0 * ncpus must be non-zero unless params == NULL * nparams * ncpus must not overflow (RPC may restrict it even more) */ if (start_cpu == -1) { if (ncpus != 1) { virReportInvalidArg(start_cpu, "%s", _("ncpus must be 1 when start_cpu is -1")); goto error; } } else { virCheckNonNegativeArgGoto(start_cpu, error); } if (nparams) virCheckNonNullArgGoto(params, error); else virCheckNullArgGoto(params, error); if (ncpus == 0) virCheckNullArgGoto(params, error); if (nparams && ncpus > UINT_MAX / nparams) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %u * %u"), nparams, ncpus); goto error; } if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; if (conn->driver->domainGetCPUStats) { int ret; ret = conn->driver->domainGetCPUStats(domain, params, nparams, start_cpu, ncpus, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetDiskErrors: * @dom: a domain object * @errors: array to populate on output * @maxerrors: size of @errors array * @flags: extra flags; not used yet, so callers should always pass 0 * * The function populates @errors array with all disks that encountered an * I/O error. Disks with no error will not be returned in the @errors array. * Each disk is identified by its target (the dev attribute of target * subelement in domain XML), such as "vda", and accompanied with the error * that was seen on it. The caller is also responsible for calling free() * on each disk name returned. * * In a special case when @errors is NULL and @maxerrors is 0, the function * returns preferred size of @errors that the caller should use to get all * disk errors. * * Since calling virDomainGetDiskErrors(dom, NULL, 0, 0) to get preferred size * of @errors array and getting the errors are two separate operations, new * disks may be hotplugged to the domain and new errors may be encountered * between the two calls. Thus, this function may not return all disk errors * because the supplied array is not large enough. Such errors may, however, * be detected by listening to domain events. * * Returns number of disks with errors filled in the @errors array or -1 on * error. */ int virDomainGetDiskErrors(virDomainPtr dom, virDomainDiskErrorPtr errors, unsigned int maxerrors, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "errors=%p, maxerrors=%u, flags=%x", errors, maxerrors, flags); virResetLastError(); virCheckDomainReturn(dom, -1); if (maxerrors) virCheckNonNullArgGoto(errors, error); else virCheckNullArgGoto(errors, error); if (dom->conn->driver->domainGetDiskErrors) { int ret = dom->conn->driver->domainGetDiskErrors(dom, errors, maxerrors, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetHostname: * @domain: a domain object * @flags: extra flags; not used yet, so callers should always pass 0 * * Get the hostname for that domain. * * Dependent on hypervisor used, this may require a guest agent to be * available. * * Returns the hostname which must be freed by the caller, or * NULL if there was an error. */ char * virDomainGetHostname(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; if (conn->driver->domainGetHostname) { char *ret; ret = conn->driver->domainGetHostname(domain, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virDomainFSTrim: * @dom: a domain object * @mountPoint: which mount point to trim * @minimum: Minimum contiguous free range to discard in bytes * @flags: extra flags, not used yet, so callers should always pass 0 * * Calls FITRIM within the guest (hence guest agent may be * required depending on hypervisor used). Either call it on each * mounted filesystem (@mountPoint is NULL) or just on specified * @mountPoint. @minimum hints that free ranges smaller than this * may be ignored (this is a hint and the guest may not respect * it). By increasing this value, the fstrim operation will * complete more quickly for filesystems with badly fragmented * free space, although not all blocks will be discarded. * If @minimum is not zero, the command may fail. * * Returns 0 on success, -1 otherwise. */ int virDomainFSTrim(virDomainPtr dom, const char *mountPoint, unsigned long long minimum, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "mountPoint=%s, minimum=%llu, flags=%x", mountPoint, minimum, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); if (dom->conn->driver->domainFSTrim) { int ret = dom->conn->driver->domainFSTrim(dom, mountPoint, minimum, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainFSFreeze: * @dom: a domain object * @mountpoints: list of mount points to be frozen * @nmountpoints: the number of mount points specified in @mountpoints * @flags: extra flags; not used yet, so callers should always pass 0 * * Freeze specified filesystems within the guest (hence guest agent * may be required depending on hypervisor used). If @mountpoints is NULL and * @nmountpoints is 0, every mounted filesystem on the guest is frozen. * In some environments (e.g. QEMU guest with guest agent which doesn't * support mountpoints argument), @mountpoints may need to be NULL. * * Returns the number of frozen filesystems on success, -1 otherwise. */ int virDomainFSFreeze(virDomainPtr dom, const char **mountpoints, unsigned int nmountpoints, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "mountpoints=%p, nmountpoints=%d, flags=%x", mountpoints, nmountpoints, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); if (nmountpoints) virCheckNonNullArgGoto(mountpoints, error); else virCheckNullArgGoto(mountpoints, error); if (dom->conn->driver->domainFSFreeze) { int ret = dom->conn->driver->domainFSFreeze( dom, mountpoints, nmountpoints, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainFSThaw: * @dom: a domain object * @mountpoints: list of mount points to be thawed * @nmountpoints: the number of mount points specified in @mountpoints * @flags: extra flags; not used yet, so callers should always pass 0 * * Thaw specified filesystems within the guest. If @mountpoints is NULL and * @nmountpoints is 0, every mounted filesystem on the guest is thawed. * In some drivers (e.g. QEMU driver), @mountpoints may need to be NULL. * * Returns the number of thawed filesystems on success, -1 otherwise. */ int virDomainFSThaw(virDomainPtr dom, const char **mountpoints, unsigned int nmountpoints, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); if (nmountpoints) virCheckNonNullArgGoto(mountpoints, error); else virCheckNullArgGoto(mountpoints, error); if (dom->conn->driver->domainFSThaw) { int ret = dom->conn->driver->domainFSThaw( dom, mountpoints, nmountpoints, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetTime: * @dom: a domain object * @seconds: domain's time in seconds * @nseconds: the nanoscond part of @seconds * @flags: extra flags; not used yet, so callers should always pass 0 * * Extract information about guest time and store it into * @seconds and @nseconds. The @seconds represents the number of * seconds since the UNIX Epoch of 1970-01-01 00:00:00 in UTC. * * Please note that some hypervisors may require guest agent to * be configured and running in order to run this API. * * Returns 0 on success, -1 otherwise. */ int virDomainGetTime(virDomainPtr dom, long long *seconds, unsigned int *nseconds, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "seconds=%p, nseconds=%p, flags=%x", seconds, nseconds, flags); virResetLastError(); virCheckDomainReturn(dom, -1); if (dom->conn->driver->domainGetTime) { int ret = dom->conn->driver->domainGetTime(dom, seconds, nseconds, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainSetTime: * @dom: a domain object * @seconds: time to set * @nseconds: the nanosecond part of @seconds * @flags: bitwise-OR of virDomainSetTimeFlags * * When a domain is suspended or restored from a file the * domain's OS has no idea that there was a big gap in the time. * Depending on how long the gap was, NTP might not be able to * resynchronize the guest. * * This API tries to set guest time to the given value. The time * to set (@seconds and @nseconds) should be in seconds relative * to the Epoch of 1970-01-01 00:00:00 in UTC. * * Please note that some hypervisors may require guest agent to * be configured and running in order to be able to run this API. * * Returns 0 on success, -1 otherwise. */ int virDomainSetTime(virDomainPtr dom, long long seconds, unsigned int nseconds, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "seconds=%lld, nseconds=%u, flags=%x", seconds, nseconds, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); if (dom->conn->driver->domainSetTime) { int ret = dom->conn->driver->domainSetTime(dom, seconds, nseconds, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainSetUserPassword: * @dom: a domain object * @user: the username that will get a new password * @password: the password to set * @flags: bitwise-OR of virDomainSetUserPasswordFlags * * Sets the @user password to the value specified by @password. * If @flags contain VIR_DOMAIN_PASSWORD_ENCRYPTED, the password * is assumed to be encrypted by the method required by the guest OS. * * Please note that some hypervisors may require guest agent to * be configured and running in order to be able to run this API. * * Returns 0 on success, -1 otherwise. */ int virDomainSetUserPassword(virDomainPtr dom, const char *user, const char *password, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "user=%s, password=%s, flags=%x", NULLSTR(user), NULLSTR(password), flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); virCheckNonNullArgGoto(user, error); virCheckNonNullArgGoto(password, error); if (dom->conn->driver->domainSetUserPassword) { int ret = dom->conn->driver->domainSetUserPassword(dom, user, password, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virConnectGetDomainCapabilities: * @conn: pointer to the hypervisor connection * @emulatorbin: path to emulator * @arch: domain architecture * @machine: machine type * @virttype: virtualization type * @flags: extra flags; not used yet, so callers should always pass 0 * * Prior creating a domain (for instance via virDomainCreateXML * or virDomainDefineXML) it may be suitable to know what the * underlying emulator and/or libvirt is capable of. For * instance, if host, libvirt and qemu is capable of VFIO * passthrough and so on. * * Returns NULL in case of error or an XML string * defining the capabilities. */ char * virConnectGetDomainCapabilities(virConnectPtr conn, const char *emulatorbin, const char *arch, const char *machine, const char *virttype, unsigned int flags) { VIR_DEBUG("conn=%p, emulatorbin=%s, arch=%s, " "machine=%s, virttype=%s, flags=%x", conn, NULLSTR(emulatorbin), NULLSTR(arch), NULLSTR(machine), NULLSTR(virttype), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); if (conn->driver->connectGetDomainCapabilities) { char *ret; ret = conn->driver->connectGetDomainCapabilities(conn, emulatorbin, arch, machine, virttype, flags); if (!ret) goto error; VIR_DEBUG("conn=%p, ret=%s", conn, ret); return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virConnectGetAllDomainStats: * @conn: pointer to the hypervisor connection * @stats: stats to return, binary-OR of virDomainStatsTypes * @retStats: Pointer that will be filled with the array of returned stats * @flags: extra flags; binary-OR of virConnectGetAllDomainStatsFlags * * Query statistics for all domains on a given connection. * * Report statistics of various parameters for a running VM according to @stats * field. The statistics are returned as an array of structures for each queried * domain. The structure contains an array of typed parameters containing the * individual statistics. The typed parameter name for each statistic field * consists of a dot-separated string containing name of the requested group * followed by a group specific description of the statistic value. * * The statistic groups are enabled using the @stats parameter which is a * binary-OR of enum virDomainStatsTypes. The following groups are available * (although not necessarily implemented for each hypervisor): * * VIR_DOMAIN_STATS_STATE: Return domain state and reason for entering that * state. The typed parameter keys are in this format: * "state.state" - state of the VM, returned as int from virDomainState enum * "state.reason" - reason for entering given state, returned as int from * virDomain*Reason enum corresponding to given state. * * VIR_DOMAIN_STATS_CPU_TOTAL: Return CPU statistics and usage information. * The typed parameter keys are in this format: * "cpu.time" - total cpu time spent for this domain in nanoseconds * as unsigned long long. * "cpu.user" - user cpu time spent in nanoseconds as unsigned long long. * "cpu.system" - system cpu time spent in nanoseconds as unsigned long long. * * VIR_DOMAIN_STATS_BALLOON: Return memory balloon device information. * The typed parameter keys are in this format: * "balloon.current" - the memory in kiB currently used * as unsigned long long. * "balloon.maximum" - the maximum memory in kiB allowed * as unsigned long long. * * VIR_DOMAIN_STATS_VCPU: Return virtual CPU statistics. * Due to VCPU hotplug, the vcpu.<num>.* array could be sparse. * The actual size of the array corresponds to "vcpu.current". * The array size will never exceed "vcpu.maximum". * The typed parameter keys are in this format: * "vcpu.current" - current number of online virtual CPUs as unsigned int. * "vcpu.maximum" - maximum number of online virtual CPUs as unsigned int. * "vcpu.<num>.state" - state of the virtual CPU <num>, as int * from virVcpuState enum. * "vcpu.<num>.time" - virtual cpu time spent by virtual CPU <num> * as unsigned long long. * * VIR_DOMAIN_STATS_INTERFACE: Return network interface statistics. * The typed parameter keys are in this format: * "net.count" - number of network interfaces on this domain * as unsigned int. * "net.<num>.name" - name of the interface <num> as string. * "net.<num>.rx.bytes" - bytes received as unsigned long long. * "net.<num>.rx.pkts" - packets received as unsigned long long. * "net.<num>.rx.errs" - receive errors as unsigned long long. * "net.<num>.rx.drop" - receive packets dropped as unsigned long long. * "net.<num>.tx.bytes" - bytes transmitted as unsigned long long. * "net.<num>.tx.pkts" - packets transmitted as unsigned long long. * "net.<num>.tx.errs" - transmission errors as unsigned long long. * "net.<num>.tx.drop" - transmit packets dropped as unsigned long long. * * VIR_DOMAIN_STATS_BLOCK: Return block devices statistics. By default, * this information is limited to the active layer of each <disk> of the * domain (where block.count is equal to the number of disks), but adding * VIR_CONNECT_GET_ALL_DOMAINS_STATS_BACKING to @flags will expand the * array to cover backing chains (block.count corresponds to the number * of host resources used together to provide the guest disks). * The typed parameter keys are in this format: * "block.count" - number of block devices in the subsequent list, * as unsigned int. * "block.<num>.name" - name of the block device <num> as string. * matches the target name (vda/sda/hda) of the * block device. If the backing chain is listed, * this name is the same for all host resources tied * to the same guest device. * "block.<num>.backingIndex" - unsigned int giving the <backingStore> index, * only used when backing images are listed. * "block.<num>.path" - string describing the source of block device <num>, * if it is a file or block device (omitted for network * sources and drives with no media inserted). * "block.<num>.rd.reqs" - number of read requests as unsigned long long. * "block.<num>.rd.bytes" - number of read bytes as unsigned long long. * "block.<num>.rd.times" - total time (ns) spent on reads as * unsigned long long. * "block.<num>.wr.reqs" - number of write requests as unsigned long long. * "block.<num>.wr.bytes" - number of written bytes as unsigned long long. * "block.<num>.wr.times" - total time (ns) spent on writes as * unsigned long long. * "block.<num>.fl.reqs" - total flush requests as unsigned long long. * "block.<num>.fl.times" - total time (ns) spent on cache flushing as * unsigned long long. * "block.<num>.errors" - Xen only: the 'oo_req' value as * unsigned long long. * "block.<num>.allocation" - offset of the highest written sector * as unsigned long long. * "block.<num>.capacity" - logical size in bytes of the block device backing * image as unsigned long long. * "block.<num>.physical" - physical size in bytes of the container of the * backing image as unsigned long long. * * Note that entire stats groups or individual stat fields may be missing from * the output in case they are not supported by the given hypervisor, are not * applicable for the current state of the guest domain, or their retrieval * was not successful. * * Using 0 for @stats returns all stats groups supported by the given * hypervisor. * * Specifying VIR_CONNECT_GET_ALL_DOMAINS_STATS_ENFORCE_STATS as @flags makes * the function return error in case some of the stat types in @stats were * not recognized by the daemon. However, even with this flag, a hypervisor * may omit individual fields within a known group if the information is not * available; as an extreme example, a supported group may produce zero * fields for offline domains if the statistics are meaningful only for a * running domain. * * Similarly to virConnectListAllDomains, @flags can contain various flags to * filter the list of domains to provide stats for. * * VIR_CONNECT_GET_ALL_DOMAINS_STATS_ACTIVE selects online domains while * VIR_CONNECT_GET_ALL_DOMAINS_STATS_INACTIVE selects offline ones. * * VIR_CONNECT_GET_ALL_DOMAINS_STATS_PERSISTENT and * VIR_CONNECT_GET_ALL_DOMAINS_STATS_TRANSIENT allow to filter the list * according to their persistence. * * To filter the list of VMs by domain state @flags can contain * VIR_CONNECT_GET_ALL_DOMAINS_STATS_RUNNING, * VIR_CONNECT_GET_ALL_DOMAINS_STATS_PAUSED, * VIR_CONNECT_GET_ALL_DOMAINS_STATS_SHUTOFF and/or * VIR_CONNECT_GET_ALL_DOMAINS_STATS_OTHER for all other states. * * Returns the count of returned statistics structures on success, -1 on error. * The requested data are returned in the @retStats parameter. The returned * array should be freed by the caller. See virDomainStatsRecordListFree. */ int virConnectGetAllDomainStats(virConnectPtr conn, unsigned int stats, virDomainStatsRecordPtr **retStats, unsigned int flags) { int ret = -1; VIR_DEBUG("conn=%p, stats=0x%x, retStats=%p, flags=0x%x", conn, stats, retStats, flags); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNullArgGoto(retStats, cleanup); if (!conn->driver->connectGetAllDomainStats) { virReportUnsupportedError(); goto cleanup; } ret = conn->driver->connectGetAllDomainStats(conn, NULL, 0, stats, retStats, flags); cleanup: if (ret < 0) virDispatchError(conn); return ret; } /** * virDomainListGetStats: * @doms: NULL terminated array of domains * @stats: stats to return, binary-OR of virDomainStatsTypes * @retStats: Pointer that will be filled with the array of returned stats * @flags: extra flags; binary-OR of virConnectGetAllDomainStatsFlags * * Query statistics for domains provided by @doms. Note that all domains in * @doms must share the same connection. * * Report statistics of various parameters for a running VM according to @stats * field. The statistics are returned as an array of structures for each queried * domain. The structure contains an array of typed parameters containing the * individual statistics. The typed parameter name for each statistic field * consists of a dot-separated string containing name of the requested group * followed by a group specific description of the statistic value. * * The statistic groups are enabled using the @stats parameter which is a * binary-OR of enum virDomainStatsTypes. The stats groups are documented * in virConnectGetAllDomainStats. * * Using 0 for @stats returns all stats groups supported by the given * hypervisor. * * Specifying VIR_CONNECT_GET_ALL_DOMAINS_STATS_ENFORCE_STATS as @flags makes * the function return error in case some of the stat types in @stats were * not recognized by the daemon. However, even with this flag, a hypervisor * may omit individual fields within a known group if the information is not * available; as an extreme example, a supported group may produce zero * fields for offline domains if the statistics are meaningful only for a * running domain. * * Note that any of the domain list filtering flags in @flags may be rejected * by this function. * * Returns the count of returned statistics structures on success, -1 on error. * The requested data are returned in the @retStats parameter. The returned * array should be freed by the caller. See virDomainStatsRecordListFree. * Note that the count of returned stats may be less than the domain count * provided via @doms. */ int virDomainListGetStats(virDomainPtr *doms, unsigned int stats, virDomainStatsRecordPtr **retStats, unsigned int flags) { virConnectPtr conn = NULL; virDomainPtr *nextdom = doms; unsigned int ndoms = 0; int ret = -1; VIR_DEBUG("doms=%p, stats=0x%x, retStats=%p, flags=0x%x", doms, stats, retStats, flags); virResetLastError(); virCheckNonNullArgGoto(doms, cleanup); virCheckNonNullArgGoto(retStats, cleanup); if (!*doms) { virReportError(VIR_ERR_INVALID_ARG, _("doms array in %s must contain at least one domain"), __FUNCTION__); goto cleanup; } conn = doms[0]->conn; virCheckConnectReturn(conn, -1); if (!conn->driver->connectGetAllDomainStats) { virReportUnsupportedError(); goto cleanup; } while (*nextdom) { virDomainPtr dom = *nextdom; virCheckDomainGoto(dom, cleanup); if (dom->conn != conn) { virReportError(VIR_ERR_INVALID_ARG, "%s", _("domains in 'doms' array must belong to a " "single connection")); goto cleanup; } ndoms++; nextdom++; } ret = conn->driver->connectGetAllDomainStats(conn, doms, ndoms, stats, retStats, flags); cleanup: if (ret < 0) virDispatchError(conn); return ret; } /** * virDomainStatsRecordListFree: * @stats: NULL terminated array of virDomainStatsRecords to free * * Convenience function to free a list of domain stats returned by * virDomainListGetStats and virConnectGetAllDomainStats. */ void virDomainStatsRecordListFree(virDomainStatsRecordPtr *stats) { virDomainStatsRecordPtr *next; if (!stats) return; for (next = stats; *next; next++) { virTypedParamsFree((*next)->params, (*next)->nparams); virDomainFree((*next)->dom); VIR_FREE(*next); } VIR_FREE(stats); } /** * virDomainGetFSInfo: * @dom: a domain object * @info: a pointer to a variable to store an array of mount points information * @flags: extra flags; not used yet, so callers should always pass 0 * * Get a list of mapping information for each mounted file systems within the * specified guest and the disks. * * Returns the number of returned mount points, or -1 in case of error. * On success, the array of the information is stored into @info. The caller is * responsible for calling virDomainFSInfoFree() on each array element, then * calling free() on @info. On error, @info is set to NULL. */ int virDomainGetFSInfo(virDomainPtr dom, virDomainFSInfoPtr **info, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "info=%p, flags=%x", info, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); virCheckNonNullArgGoto(info, error); *info = NULL; if (dom->conn->driver->domainGetFSInfo) { int ret = dom->conn->driver->domainGetFSInfo(dom, info, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainFSInfoFree: * @info: pointer to a FSInfo object * * Frees all the memory occupied by @info. */ void virDomainFSInfoFree(virDomainFSInfoPtr info) { size_t i; if (!info) return; VIR_FREE(info->mountpoint); VIR_FREE(info->name); VIR_FREE(info->fstype); for (i = 0; i < info->ndevAlias; i++) VIR_FREE(info->devAlias[i]); VIR_FREE(info->devAlias); VIR_FREE(info); } /** * virDomainInterfaceAddresses: * @dom: domain object * @ifaces: pointer to an array of pointers pointing to interface objects * @source: one of the virDomainInterfaceAddressesSource constants * @flags: currently unused, pass zero * * Return a pointer to the allocated array of pointers to interfaces * present in given domain along with their IP and MAC addresses. Note that * single interface can have multiple or even 0 IP addresses. * * This API dynamically allocates the virDomainInterfacePtr struct based on * how many interfaces domain @dom has, usually there's 1:1 correlation. The * count of the interfaces is returned as the return value. * * If @source is VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE, the DHCP lease * file associated with any virtual networks will be examined to obtain * the interface addresses. This only returns data for interfaces which * are connected to virtual networks managed by libvirt. * * If @source is VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT, a configured * guest agent is needed for successful return from this API. Moreover, if * guest agent is used then the interface name is the one seen by guest OS. * To match such interface with the one from @dom XML use MAC address or IP * range. * * @ifaces->name and @ifaces->hwaddr are never NULL. * * The caller *must* free @ifaces when no longer needed. Usual use case * looks like this: * * virDomainInterfacePtr *ifaces = NULL; * int ifaces_count = 0; * size_t i, j; * virDomainPtr dom = ... obtain a domain here ...; * * if ((ifaces_count = virDomainInterfaceAddresses(dom, &ifaces, * VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE)) < 0) * goto cleanup; * * ... do something with returned values, for example: * for (i = 0; i < ifaces_count; i++) { * printf("name: %s", ifaces[i]->name); * if (ifaces[i]->hwaddr) * printf(" hwaddr: %s", ifaces[i]->hwaddr); * * for (j = 0; j < ifaces[i]->naddrs; j++) { * virDomainIPAddressPtr ip_addr = ifaces[i]->addrs + j; * printf("[addr: %s prefix: %d type: %d]", * ip_addr->addr, ip_addr->prefix, ip_addr->type); * } * printf("\n"); * } * * cleanup: * if (ifaces && ifaces_count > 0) * for (i = 0; i < ifaces_count; i++) * virDomainInterfaceFree(ifaces[i]); * free(ifaces); * * Returns the number of interfaces on success, -1 in case of error. */ int virDomainInterfaceAddresses(virDomainPtr dom, virDomainInterfacePtr **ifaces, unsigned int source, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "ifaces=%p, source=%d, flags=%x", ifaces, source, flags); virResetLastError(); if (ifaces) *ifaces = NULL; virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(ifaces, error); if (source == VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT) virCheckReadOnlyGoto(dom->conn->flags, error); if (dom->conn->driver->domainInterfaceAddresses) { int ret; ret = dom->conn->driver->domainInterfaceAddresses(dom, ifaces, source, flags); if (ret < 0) goto error; return ret; } virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__); error: virDispatchError(dom->conn); return -1; } /** * virDomainInterfaceFree: * @iface: an interface object * * Free the interface object. The data structure is * freed and should not be used thereafter. If @iface * is NULL, then this method has no effect. */ void virDomainInterfaceFree(virDomainInterfacePtr iface) { size_t i; if (!iface) return; VIR_FREE(iface->name); VIR_FREE(iface->hwaddr); for (i = 0; i < iface->naddrs; i++) VIR_FREE(iface->addrs[i].addr); VIR_FREE(iface->addrs); VIR_FREE(iface); }
./CrossVul/dataset_final_sorted/CWE-254/c/bad_4886_0
crossvul-cpp_data_good_480_1
/* Copyright (c) 2009-2018 Roger Light <roger@atchoo.org> All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #ifdef WIN32 #else # include <dirent.h> # include <strings.h> #endif #ifndef WIN32 # include <netdb.h> # include <sys/socket.h> #else # include <winsock2.h> # include <ws2tcpip.h> #endif #if !defined(WIN32) && !defined(__CYGWIN__) # include <syslog.h> #endif #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "tls_mosq.h" #include "util_mosq.h" #include "mqtt3_protocol.h" struct config_recurse { int log_dest; int log_dest_set; int log_type; int log_type_set; unsigned long max_inflight_bytes; unsigned long max_queued_bytes; int max_inflight_messages; int max_queued_messages; }; #if defined(WIN32) || defined(__CYGWIN__) #include <windows.h> extern SERVICE_STATUS_HANDLE service_handle; #endif static int conf__parse_bool(char **token, const char *name, bool *value, char *saveptr); static int conf__parse_int(char **token, const char *name, int *value, char *saveptr); static int conf__parse_ssize_t(char **token, const char *name, ssize_t *value, char *saveptr); static int conf__parse_string(char **token, const char *name, char **value, char *saveptr); static int config__read_file(struct mosquitto__config *config, bool reload, const char *file, struct config_recurse *config_tmp, int level, int *lineno); static int config__check(struct mosquitto__config *config); static void config__cleanup_plugins(struct mosquitto__config *config); static char *fgets_extending(char **buf, int *buflen, FILE *stream) { char *rc; char endchar; int offset = 0; char *newbuf; do{ rc = fgets(&((*buf)[offset]), *buflen-offset, stream); if(feof(stream)){ return rc; } endchar = (*buf)[strlen(*buf)-1]; if(endchar == '\n'){ return rc; } /* No EOL char found, so extend buffer */ offset = *buflen-1; *buflen += 1000; newbuf = realloc(*buf, *buflen); if(!newbuf){ return NULL; } *buf = newbuf; }while(1); } static void conf__set_cur_security_options(struct mosquitto__config *config, struct mosquitto__listener *cur_listener, struct mosquitto__security_options **security_options) { if(config->per_listener_settings){ (*security_options) = &cur_listener->security_options; }else{ (*security_options) = &config->security_options; } } static int conf__attempt_resolve(const char *host, const char *text, int log, const char *msg) { struct addrinfo gai_hints; struct addrinfo *gai_res; int rc; memset(&gai_hints, 0, sizeof(struct addrinfo)); gai_hints.ai_family = AF_UNSPEC; gai_hints.ai_socktype = SOCK_STREAM; gai_res = NULL; rc = getaddrinfo(host, NULL, &gai_hints, &gai_res); if(gai_res){ freeaddrinfo(gai_res); } if(rc != 0){ #ifndef WIN32 if(rc == EAI_SYSTEM){ if(errno == ENOENT){ log__printf(NULL, log, "%s: Unable to resolve %s %s.", msg, text, host); }else{ log__printf(NULL, log, "%s: Error resolving %s: %s.", msg, text, strerror(errno)); } }else{ log__printf(NULL, log, "%s: Error resolving %s: %s.", msg, text, gai_strerror(rc)); } #else if(rc == WSAHOST_NOT_FOUND){ log__printf(NULL, log, "%s: Error resolving %s.", msg, text); } #endif return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static void config__init_reload(struct mosquitto_db *db, struct mosquitto__config *config) { int i; /* Set defaults */ for(i=0; i<config->listener_count; i++){ mosquitto__free(config->listeners[i].security_options.acl_file); config->listeners[i].security_options.acl_file = NULL; mosquitto__free(config->listeners[i].security_options.password_file); config->listeners[i].security_options.password_file = NULL; mosquitto__free(config->listeners[i].security_options.psk_file); config->listeners[i].security_options.psk_file = NULL; config->listeners[i].security_options.allow_anonymous = -1; config->listeners[i].security_options.allow_zero_length_clientid = true; config->listeners[i].security_options.auto_id_prefix = NULL; config->listeners[i].security_options.auto_id_prefix_len = 0; } config->allow_duplicate_messages = false; mosquitto__free(config->security_options.acl_file); config->security_options.acl_file = NULL; config->security_options.allow_anonymous = -1; config->security_options.allow_zero_length_clientid = true; config->security_options.auto_id_prefix = NULL; config->security_options.auto_id_prefix_len = 0; mosquitto__free(config->security_options.password_file); config->security_options.password_file = NULL; mosquitto__free(config->security_options.psk_file); config->security_options.psk_file = NULL; config->autosave_interval = 1800; config->autosave_on_changes = false; mosquitto__free(config->clientid_prefixes); config->connection_messages = true; config->clientid_prefixes = NULL; config->per_listener_settings = false; if(config->log_fptr){ fclose(config->log_fptr); config->log_fptr = NULL; } mosquitto__free(config->log_file); config->log_file = NULL; #if defined(WIN32) || defined(__CYGWIN__) if(service_handle){ /* This is running as a Windows service. Default to no logging. Using * stdout/stderr is forbidden because the first clients to connect will * get log information sent to them for some reason. */ config->log_dest = MQTT3_LOG_NONE; }else{ config->log_dest = MQTT3_LOG_STDERR; } #else config->log_facility = LOG_DAEMON; config->log_dest = MQTT3_LOG_STDERR; if(db->verbose){ config->log_type = INT_MAX; }else{ config->log_type = MOSQ_LOG_ERR | MOSQ_LOG_WARNING | MOSQ_LOG_NOTICE | MOSQ_LOG_INFO; } #endif config->log_timestamp = true; config->persistence = false; mosquitto__free(config->persistence_location); config->persistence_location = NULL; mosquitto__free(config->persistence_file); config->persistence_file = NULL; config->persistent_client_expiration = 0; config->queue_qos0_messages = false; config->set_tcp_nodelay = false; config->sys_interval = 10; config->upgrade_outgoing_qos = false; config__cleanup_plugins(config); } static void config__cleanup_plugins(struct mosquitto__config *config) { int i, j; struct mosquitto__auth_plugin_config *plug; if(config->security_options.auth_plugin_configs){ for(i=0; i<config->security_options.auth_plugin_config_count; i++){ plug = &config->security_options.auth_plugin_configs[i]; mosquitto__free(plug->path); plug->path = NULL; if(plug->options){ for(j=0; j<plug->option_count; j++){ mosquitto__free(plug->options[j].key); mosquitto__free(plug->options[j].value); } mosquitto__free(plug->options); plug->options = NULL; plug->option_count = 0; } } mosquitto__free(config->security_options.auth_plugin_configs); config->security_options.auth_plugin_configs = NULL; } } void config__init(struct mosquitto_db *db, struct mosquitto__config *config) { memset(config, 0, sizeof(struct mosquitto__config)); config__init_reload(db, config); config->daemon = false; memset(&config->default_listener, 0, sizeof(struct mosquitto__listener)); config->default_listener.max_connections = -1; config->default_listener.protocol = mp_mqtt; config->default_listener.security_options.allow_anonymous = -1; } void config__cleanup(struct mosquitto__config *config) { int i; int j; mosquitto__free(config->clientid_prefixes); mosquitto__free(config->persistence_location); mosquitto__free(config->persistence_file); mosquitto__free(config->persistence_filepath); mosquitto__free(config->security_options.auto_id_prefix); mosquitto__free(config->security_options.acl_file); mosquitto__free(config->security_options.password_file); mosquitto__free(config->security_options.psk_file); mosquitto__free(config->pid_file); if(config->listeners){ for(i=0; i<config->listener_count; i++){ mosquitto__free(config->listeners[i].host); mosquitto__free(config->listeners[i].mount_point); mosquitto__free(config->listeners[i].socks); mosquitto__free(config->listeners[i].security_options.auto_id_prefix); mosquitto__free(config->listeners[i].security_options.acl_file); mosquitto__free(config->listeners[i].security_options.password_file); mosquitto__free(config->listeners[i].security_options.psk_file); #ifdef WITH_TLS mosquitto__free(config->listeners[i].cafile); mosquitto__free(config->listeners[i].capath); mosquitto__free(config->listeners[i].certfile); mosquitto__free(config->listeners[i].keyfile); mosquitto__free(config->listeners[i].ciphers); mosquitto__free(config->listeners[i].psk_hint); mosquitto__free(config->listeners[i].crlfile); mosquitto__free(config->listeners[i].tls_version); #ifdef WITH_WEBSOCKETS if(!config->listeners[i].ws_context) /* libwebsockets frees its own SSL_CTX */ #endif { SSL_CTX_free(config->listeners[i].ssl_ctx); } #endif #ifdef WITH_WEBSOCKETS mosquitto__free(config->listeners[i].http_dir); #endif } mosquitto__free(config->listeners); } #ifdef WITH_BRIDGE if(config->bridges){ for(i=0; i<config->bridge_count; i++){ mosquitto__free(config->bridges[i].name); if(config->bridges[i].addresses){ for(j=0; j<config->bridges[i].address_count; j++){ mosquitto__free(config->bridges[i].addresses[j].address); } mosquitto__free(config->bridges[i].addresses); } mosquitto__free(config->bridges[i].remote_clientid); mosquitto__free(config->bridges[i].remote_username); mosquitto__free(config->bridges[i].remote_password); mosquitto__free(config->bridges[i].local_clientid); mosquitto__free(config->bridges[i].local_username); mosquitto__free(config->bridges[i].local_password); if(config->bridges[i].topics){ for(j=0; j<config->bridges[i].topic_count; j++){ mosquitto__free(config->bridges[i].topics[j].topic); mosquitto__free(config->bridges[i].topics[j].local_prefix); mosquitto__free(config->bridges[i].topics[j].remote_prefix); mosquitto__free(config->bridges[i].topics[j].local_topic); mosquitto__free(config->bridges[i].topics[j].remote_topic); } mosquitto__free(config->bridges[i].topics); } mosquitto__free(config->bridges[i].notification_topic); #ifdef WITH_TLS mosquitto__free(config->bridges[i].tls_version); mosquitto__free(config->bridges[i].tls_cafile); #ifdef WITH_TLS_PSK mosquitto__free(config->bridges[i].tls_psk_identity); mosquitto__free(config->bridges[i].tls_psk); #endif #endif } mosquitto__free(config->bridges); } #endif config__cleanup_plugins(config); if(config->log_fptr){ fclose(config->log_fptr); config->log_fptr = NULL; } if(config->log_file){ mosquitto__free(config->log_file); config->log_file = NULL; } } static void print_usage(void) { printf("mosquitto version %s\n\n", VERSION); printf("mosquitto is an MQTT v3.1.1 broker.\n\n"); printf("Usage: mosquitto [-c config_file] [-d] [-h] [-p port]\n\n"); printf(" -c : specify the broker config file.\n"); printf(" -d : put the broker into the background after starting.\n"); printf(" -h : display this help.\n"); printf(" -p : start the broker listening on the specified port.\n"); printf(" Not recommended in conjunction with the -c option.\n"); printf(" -v : verbose mode - enable all logging types. This overrides\n"); printf(" any logging options given in the config file.\n"); printf("\nSee http://mosquitto.org/ for more information.\n\n"); } int config__parse_args(struct mosquitto_db *db, struct mosquitto__config *config, int argc, char *argv[]) { int i; int port_tmp; for(i=1; i<argc; i++){ if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--config-file")){ if(i<argc-1){ db->config_file = argv[i+1]; if(config__read(db, config, false)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open configuration file."); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -c argument given, but no config file specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--daemon")){ config->daemon = true; }else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")){ print_usage(); return MOSQ_ERR_INVAL; }else if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){ if(i<argc-1){ port_tmp = atoi(argv[i+1]); if(port_tmp<1 || port_tmp>65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port specified (%d).", port_tmp); return MOSQ_ERR_INVAL; }else{ if(config->default_listener.port){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Default listener port specified multiple times. Only the latest will be used."); } config->default_listener.port = port_tmp; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -p argument given, but no port specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){ db->verbose = true; }else{ fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]); print_usage(); return MOSQ_ERR_INVAL; } } if(config->listener_count == 0 #ifdef WITH_TLS || config->default_listener.cafile || config->default_listener.capath || config->default_listener.certfile || config->default_listener.keyfile || config->default_listener.ciphers || config->default_listener.psk_hint || config->default_listener.require_certificate || config->default_listener.crlfile || config->default_listener.use_identity_as_username || config->default_listener.use_subject_as_username #endif || config->default_listener.use_username_as_clientid || config->default_listener.host || config->default_listener.port || config->default_listener.max_connections != -1 || config->default_listener.mount_point || config->default_listener.protocol != mp_mqtt || config->default_listener.socket_domain || config->default_listener.security_options.password_file || config->default_listener.security_options.psk_file || config->default_listener.security_options.auth_plugin_config_count || config->default_listener.security_options.allow_anonymous != -1 ){ config->listener_count++; config->listeners = mosquitto__realloc(config->listeners, sizeof(struct mosquitto__listener)*config->listener_count); if(!config->listeners){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } memset(&config->listeners[config->listener_count-1], 0, sizeof(struct mosquitto__listener)); if(config->default_listener.port){ config->listeners[config->listener_count-1].port = config->default_listener.port; }else{ config->listeners[config->listener_count-1].port = 1883; } if(config->default_listener.host){ config->listeners[config->listener_count-1].host = config->default_listener.host; }else{ config->listeners[config->listener_count-1].host = NULL; } if(config->default_listener.mount_point){ config->listeners[config->listener_count-1].mount_point = config->default_listener.mount_point; }else{ config->listeners[config->listener_count-1].mount_point = NULL; } config->listeners[config->listener_count-1].max_connections = config->default_listener.max_connections; config->listeners[config->listener_count-1].protocol = config->default_listener.protocol; config->listeners[config->listener_count-1].socket_domain = config->default_listener.socket_domain; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].socks = NULL; config->listeners[config->listener_count-1].sock_count = 0; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].use_username_as_clientid = config->default_listener.use_username_as_clientid; #ifdef WITH_TLS config->listeners[config->listener_count-1].tls_version = config->default_listener.tls_version; config->listeners[config->listener_count-1].cafile = config->default_listener.cafile; config->listeners[config->listener_count-1].capath = config->default_listener.capath; config->listeners[config->listener_count-1].certfile = config->default_listener.certfile; config->listeners[config->listener_count-1].keyfile = config->default_listener.keyfile; config->listeners[config->listener_count-1].ciphers = config->default_listener.ciphers; config->listeners[config->listener_count-1].psk_hint = config->default_listener.psk_hint; config->listeners[config->listener_count-1].require_certificate = config->default_listener.require_certificate; config->listeners[config->listener_count-1].ssl_ctx = NULL; config->listeners[config->listener_count-1].crlfile = config->default_listener.crlfile; config->listeners[config->listener_count-1].use_identity_as_username = config->default_listener.use_identity_as_username; config->listeners[config->listener_count-1].use_subject_as_username = config->default_listener.use_subject_as_username; #endif config->listeners[config->listener_count-1].security_options.acl_file = config->default_listener.security_options.acl_file; config->listeners[config->listener_count-1].security_options.password_file = config->default_listener.security_options.password_file; config->listeners[config->listener_count-1].security_options.psk_file = config->default_listener.security_options.psk_file; config->listeners[config->listener_count-1].security_options.auth_plugin_configs = config->default_listener.security_options.auth_plugin_configs; config->listeners[config->listener_count-1].security_options.auth_plugin_config_count = config->default_listener.security_options.auth_plugin_config_count; config->listeners[config->listener_count-1].security_options.allow_anonymous = config->default_listener.security_options.allow_anonymous; } /* Default to drop to mosquitto user if we are privileged and no user specified. */ if(!config->user){ config->user = "mosquitto"; } if(db->verbose){ config->log_type = INT_MAX; } return config__check(config); } void config__copy(struct mosquitto__config *src, struct mosquitto__config *dest) { mosquitto__free(dest->security_options.acl_file); dest->security_options.acl_file = src->security_options.acl_file; dest->security_options.allow_anonymous = src->security_options.allow_anonymous; dest->security_options.allow_zero_length_clientid = src->security_options.allow_zero_length_clientid; mosquitto__free(dest->security_options.auto_id_prefix); dest->security_options.auto_id_prefix = src->security_options.auto_id_prefix; dest->security_options.auto_id_prefix_len = src->security_options.auto_id_prefix_len; mosquitto__free(dest->security_options.password_file); dest->security_options.password_file = src->security_options.password_file; mosquitto__free(dest->security_options.psk_file); dest->security_options.psk_file = src->security_options.psk_file; dest->allow_duplicate_messages = src->allow_duplicate_messages; dest->autosave_interval = src->autosave_interval; dest->autosave_on_changes = src->autosave_on_changes; mosquitto__free(dest->clientid_prefixes); dest->clientid_prefixes = src->clientid_prefixes; dest->connection_messages = src->connection_messages; dest->log_dest = src->log_dest; dest->log_facility = src->log_facility; dest->log_type = src->log_type; dest->log_timestamp = src->log_timestamp; mosquitto__free(dest->log_file); dest->log_file = src->log_file; dest->message_size_limit = src->message_size_limit; dest->persistence = src->persistence; mosquitto__free(dest->persistence_location); dest->persistence_location = src->persistence_location; mosquitto__free(dest->persistence_file); dest->persistence_file = src->persistence_file; mosquitto__free(dest->persistence_filepath); dest->persistence_filepath = src->persistence_filepath; dest->persistent_client_expiration = src->persistent_client_expiration; dest->queue_qos0_messages = src->queue_qos0_messages; dest->sys_interval = src->sys_interval; dest->upgrade_outgoing_qos = src->upgrade_outgoing_qos; #ifdef WITH_WEBSOCKETS dest->websockets_log_level = src->websockets_log_level; #endif } int config__read(struct mosquitto_db *db, struct mosquitto__config *config, bool reload) { int rc = MOSQ_ERR_SUCCESS; struct config_recurse cr; int lineno = 0; int len; struct mosquitto__config config_reload; int i; if(reload){ memset(&config_reload, 0, sizeof(struct mosquitto__config)); } cr.log_dest = MQTT3_LOG_NONE; cr.log_dest_set = 0; cr.log_type = MOSQ_LOG_NONE; cr.log_type_set = 0; cr.max_inflight_bytes = 0; cr.max_inflight_messages = 20; cr.max_queued_bytes = 0; cr.max_queued_messages = 100; if(!db->config_file) return 0; if(reload){ /* Re-initialise appropriate config vars to default for reload. */ config__init_reload(db, &config_reload); config_reload.listeners = config->listeners; config_reload.listener_count = config->listener_count; rc = config__read_file(&config_reload, reload, db->config_file, &cr, 0, &lineno); }else{ rc = config__read_file(config, reload, db->config_file, &cr, 0, &lineno); } if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error found at %s:%d.", db->config_file, lineno); return rc; } if(reload){ config__copy(&config_reload, config); } /* If auth/access options are set and allow_anonymous not explicitly set, disallow anon. */ if(config->per_listener_settings){ for(i=0; i<config->listener_count; i++){ if(config->listeners[i].security_options.allow_anonymous == -1){ if(config->listeners[i].security_options.password_file || config->listeners[i].security_options.psk_file || config->listeners[i].security_options.auth_plugin_configs){ /* allow_anonymous not set explicitly, some other security options * have been set - so disable allow_anonymous */ config->listeners[i].security_options.allow_anonymous = false; }else{ /* Default option if no security options set */ config->listeners[i].security_options.allow_anonymous = true; } } } }else{ if(config->security_options.allow_anonymous == -1){ if(config->security_options.password_file || config->security_options.psk_file || config->security_options.auth_plugin_configs){ /* allow_anonymous not set explicitly, some other security options * have been set - so disable allow_anonymous */ config->security_options.allow_anonymous = false; }else{ /* Default option if no security options set */ config->security_options.allow_anonymous = true; } } } #ifdef WITH_PERSISTENCE if(config->persistence){ if(!config->persistence_file){ config->persistence_file = mosquitto__strdup("mosquitto.db"); if(!config->persistence_file) return MOSQ_ERR_NOMEM; } mosquitto__free(config->persistence_filepath); if(config->persistence_location && strlen(config->persistence_location)){ len = strlen(config->persistence_location) + strlen(config->persistence_file) + 1; config->persistence_filepath = mosquitto__malloc(len); if(!config->persistence_filepath) return MOSQ_ERR_NOMEM; snprintf(config->persistence_filepath, len, "%s%s", config->persistence_location, config->persistence_file); }else{ config->persistence_filepath = mosquitto__strdup(config->persistence_file); if(!config->persistence_filepath) return MOSQ_ERR_NOMEM; } } #endif /* Default to drop to mosquitto user if no other user specified. This must * remain here even though it is covered in config__parse_args() because this * function may be called on its own. */ if(!config->user){ config->user = "mosquitto"; } db__limits_set(cr.max_inflight_messages, cr.max_inflight_bytes, cr.max_queued_messages, cr.max_queued_bytes); #ifdef WITH_BRIDGE for(i=0; i<config->bridge_count; i++){ if(!config->bridges[i].name || !config->bridges[i].addresses || !config->bridges[i].topic_count){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef WITH_TLS_PSK if(config->bridges[i].tls_psk && !config->bridges[i].tls_psk_identity){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration: missing bridge_identity.\n"); return MOSQ_ERR_INVAL; } if(config->bridges[i].tls_psk_identity && !config->bridges[i].tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration: missing bridge_psk.\n"); return MOSQ_ERR_INVAL; } #endif } #endif if(cr.log_dest_set){ config->log_dest = cr.log_dest; } if(db->verbose){ config->log_type = INT_MAX; }else if(cr.log_type_set){ config->log_type = cr.log_type; } return MOSQ_ERR_SUCCESS; } int config__read_file_core(struct mosquitto__config *config, bool reload, struct config_recurse *cr, int level, int *lineno, FILE *fptr, char **buf, int *buflen) { int rc; char *token; int tmp_int; char *saveptr = NULL; #ifdef WITH_BRIDGE char *tmp_char; struct mosquitto__bridge *cur_bridge = NULL; struct mosquitto__bridge_topic *cur_topic; #endif struct mosquitto__auth_plugin_config *cur_auth_plugin_config = NULL; time_t expiration_mult; char *key; char *conf_file; #ifdef WIN32 HANDLE fh; char dirpath[MAX_PATH]; WIN32_FIND_DATA find_data; #else DIR *dh; struct dirent *de; #endif int len; struct mosquitto__listener *cur_listener = &config->default_listener; int i; int lineno_ext; struct mosquitto__security_options *cur_security_options = NULL; *lineno = 0; while(fgets_extending(buf, buflen, fptr)){ (*lineno)++; if((*buf)[0] != '#' && (*buf)[0] != 10 && (*buf)[0] != 13){ while((*buf)[strlen((*buf))-1] == 10 || (*buf)[strlen((*buf))-1] == 13){ (*buf)[strlen((*buf))-1] = 0; } token = strtok_r((*buf), " ", &saveptr); if(token){ if(!strcmp(token, "acl_file")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(reload){ mosquitto__free(cur_security_options->acl_file); cur_security_options->acl_file = NULL; } if(conf__parse_string(&token, "acl_file", &cur_security_options->acl_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "address") || !strcmp(token, "addresses")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge || cur_bridge->addresses){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } while((token = strtok_r(NULL, " ", &saveptr))){ cur_bridge->address_count++; cur_bridge->addresses = mosquitto__realloc(cur_bridge->addresses, sizeof(struct bridge_address)*cur_bridge->address_count); if(!cur_bridge->addresses){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_bridge->addresses[cur_bridge->address_count-1].address = token; } for(i=0; i<cur_bridge->address_count; i++){ /* cur_bridge->addresses[i].address is now * "address[:port]". If address is an IPv6 address, * then port is required. We must check for the : * backwards. */ tmp_char = strrchr(cur_bridge->addresses[i].address, ':'); if(tmp_char){ /* Remove ':', so cur_bridge->addresses[i].address * now just looks like the address. */ tmp_char[0] = '\0'; /* The remainder of the string */ tmp_int = atoi(&tmp_char[1]); if(tmp_int < 1 || tmp_int > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } cur_bridge->addresses[i].port = tmp_int; }else{ cur_bridge->addresses[i].port = 1883; } /* This looks a bit weird, but isn't. Before this * call, cur_bridge->addresses[i].address points * to the tokenised part of the line, it will be * reused in a future parse of a config line so we * must duplicate it. */ cur_bridge->addresses[i].address = mosquitto__strdup(cur_bridge->addresses[i].address); conf__attempt_resolve(cur_bridge->addresses[i].address, "bridge address", MOSQ_LOG_WARNING, "Warning"); } if(cur_bridge->address_count == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty address value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "allow_anonymous")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(conf__parse_bool(&token, "allow_anonymous", (bool *)&cur_security_options->allow_anonymous, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "allow_duplicate_messages")){ if(conf__parse_bool(&token, "allow_duplicate_messages", &config->allow_duplicate_messages, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "allow_zero_length_clientid")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(conf__parse_bool(&token, "allow_zero_length_clientid", &cur_security_options->allow_zero_length_clientid, saveptr)) return MOSQ_ERR_INVAL; }else if(!strncmp(token, "auth_opt_", 9)){ if(reload) continue; // Auth plugin not currently valid for reloading. if(!cur_auth_plugin_config){ log__printf(NULL, MOSQ_LOG_ERR, "Error: An auth_opt_ option exists in the config file without an auth_plugin."); return MOSQ_ERR_INVAL; } if(strlen(token) < 12){ /* auth_opt_ == 9, + one digit key == 10, + one space == 11, + one value == 12 */ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid auth_opt_ config option."); return MOSQ_ERR_INVAL; } key = mosquitto__strdup(&token[9]); if(!key){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; }else if(STREMPTY(key)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid auth_opt_ config option."); mosquitto__free(key); return MOSQ_ERR_INVAL; } token += 9+strlen(key)+1; while(token[0] == ' ' || token[0] == '\t'){ token++; } if(token[0]){ cur_auth_plugin_config->option_count++; cur_auth_plugin_config->options = mosquitto__realloc(cur_auth_plugin_config->options, cur_auth_plugin_config->option_count*sizeof(struct mosquitto_auth_opt)); if(!cur_auth_plugin_config->options){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); mosquitto__free(key); return MOSQ_ERR_NOMEM; } cur_auth_plugin_config->options[cur_auth_plugin_config->option_count-1].key = key; cur_auth_plugin_config->options[cur_auth_plugin_config->option_count-1].value = mosquitto__strdup(token); if(!cur_auth_plugin_config->options[cur_auth_plugin_config->option_count-1].value){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", key); mosquitto__free(key); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "auth_plugin")){ if(reload) continue; // Auth plugin not currently valid for reloading. conf__set_cur_security_options(config, cur_listener, &cur_security_options); cur_security_options->auth_plugin_configs = mosquitto__realloc(cur_security_options->auth_plugin_configs, (cur_security_options->auth_plugin_config_count+1)*sizeof(struct mosquitto__auth_plugin_config)); if(!cur_security_options->auth_plugin_configs){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_auth_plugin_config = &cur_security_options->auth_plugin_configs[cur_security_options->auth_plugin_config_count]; memset(cur_auth_plugin_config, 0, sizeof(struct mosquitto__auth_plugin_config)); cur_auth_plugin_config->path = NULL; cur_auth_plugin_config->options = NULL; cur_auth_plugin_config->option_count = 0; cur_auth_plugin_config->deny_special_chars = true; cur_security_options->auth_plugin_config_count++; if(conf__parse_string(&token, "auth_plugin", &cur_auth_plugin_config->path, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "auth_plugin_deny_special_chars")){ if(reload) continue; // Auth plugin not currently valid for reloading. if(!cur_auth_plugin_config){ log__printf(NULL, MOSQ_LOG_ERR, "Error: An auth_plugin_deny_special_chars option exists in the config file without an auth_plugin."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "auth_plugin_deny_special_chars", &cur_auth_plugin_config->deny_special_chars, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "auto_id_prefix")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(conf__parse_string(&token, "auto_id_prefix", &cur_security_options->auto_id_prefix, saveptr)) return MOSQ_ERR_INVAL; if(cur_security_options->auto_id_prefix){ cur_security_options->auto_id_prefix_len = strlen(cur_security_options->auto_id_prefix); }else{ cur_security_options->auto_id_prefix_len = 0; } }else if(!strcmp(token, "autosave_interval")){ if(conf__parse_int(&token, "autosave_interval", &config->autosave_interval, saveptr)) return MOSQ_ERR_INVAL; if(config->autosave_interval < 0) config->autosave_interval = 0; }else if(!strcmp(token, "autosave_on_changes")){ if(conf__parse_bool(&token, "autosave_on_changes", &config->autosave_on_changes, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "bind_address")){ if(reload) continue; // Listener not valid for reloading. if(conf__parse_string(&token, "default listener bind_address", &config->default_listener.host, saveptr)) return MOSQ_ERR_INVAL; if(conf__attempt_resolve(config->default_listener.host, "bind_address", MOSQ_LOG_ERR, "Error")){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "bridge_attempt_unsubscribe")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "bridge_attempt_unsubscribe", &cur_bridge->attempt_unsubscribe, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_cafile")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_cafile", &cur_bridge->tls_cafile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_capath")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_capath", &cur_bridge->tls_capath, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_certfile")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_certfile", &cur_bridge->tls_certfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_identity")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS_PSK) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(cur_bridge->tls_cafile || cur_bridge->tls_capath || cur_bridge->tls_certfile || cur_bridge->tls_keyfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and identity encryption in a single bridge."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge_identity", &cur_bridge->tls_psk_identity, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS-PSK support not available."); #endif }else if(!strcmp(token, "bridge_insecure")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "bridge_insecure", &cur_bridge->tls_insecure, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->tls_insecure){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge %s using insecure mode.", cur_bridge->name); } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS-PSK support not available."); #endif }else if(!strcmp(token, "bridge_keyfile")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_keyfile", &cur_bridge->tls_keyfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_protocol_version")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, "", &saveptr); if(token){ if(!strcmp(token, "mqttv31")){ cur_bridge->protocol_version = mosq_p_mqtt31; }else if(!strcmp(token, "mqttv311")){ cur_bridge->protocol_version = mosq_p_mqtt311; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge_protocol_version value (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty bridge_protocol_version value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_psk")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS_PSK) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(cur_bridge->tls_cafile || cur_bridge->tls_capath || cur_bridge->tls_certfile || cur_bridge->tls_keyfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge_psk", &cur_bridge->tls_psk, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS-PSK support not available."); #endif }else if(!strcmp(token, "bridge_tls_version")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge_tls_version", &cur_bridge->tls_version, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "cafile")){ #if defined(WITH_TLS) if(reload) continue; // Listeners not valid for reloading. if(cur_listener->psk_hint){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single listener."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "cafile", &cur_listener->cafile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "capath")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "capath", &cur_listener->capath, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "certfile")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(cur_listener->psk_hint){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single listener."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "certfile", &cur_listener->certfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "ciphers")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "ciphers", &cur_listener->ciphers, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "clientid") || !strcmp(token, "remote_clientid")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge remote clientid", &cur_bridge->remote_clientid, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "cleansession")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "cleansession", &cur_bridge->clean_session, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "clientid_prefixes")){ if(reload){ mosquitto__free(config->clientid_prefixes); config->clientid_prefixes = NULL; } if(conf__parse_string(&token, "clientid_prefixes", &config->clientid_prefixes, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "connection")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME token = strtok_r(NULL, " ", &saveptr); if(token){ /* Check for existing bridge name. */ for(i=0; i<config->bridge_count; i++){ if(!strcmp(config->bridges[i].name, token)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate bridge name \"%s\".", token); return MOSQ_ERR_INVAL; } } config->bridge_count++; config->bridges = mosquitto__realloc(config->bridges, config->bridge_count*sizeof(struct mosquitto__bridge)); if(!config->bridges){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_bridge = &(config->bridges[config->bridge_count-1]); memset(cur_bridge, 0, sizeof(struct mosquitto__bridge)); cur_bridge->name = mosquitto__strdup(token); if(!cur_bridge->name){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_bridge->keepalive = 60; cur_bridge->notifications = true; cur_bridge->notifications_local_only = false; cur_bridge->start_type = bst_automatic; cur_bridge->idle_timeout = 60; cur_bridge->restart_timeout = 30; cur_bridge->threshold = 10; cur_bridge->try_private = true; cur_bridge->attempt_unsubscribe = true; cur_bridge->protocol_version = mosq_p_mqtt311; cur_bridge->primary_retry_sock = INVALID_SOCKET; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty connection value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "connection_messages")){ if(conf__parse_bool(&token, token, &config->connection_messages, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "crlfile")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "crlfile", &cur_listener->crlfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "http_dir")){ #ifdef WITH_WEBSOCKETS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "http_dir", &cur_listener->http_dir, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Websockets support not available."); #endif }else if(!strcmp(token, "idle_timeout")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_int(&token, "idle_timeout", &cur_bridge->idle_timeout, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->idle_timeout < 1){ log__printf(NULL, MOSQ_LOG_NOTICE, "idle_timeout interval too low, using 1 second."); cur_bridge->idle_timeout = 1; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "include_dir")){ if(level == 0){ /* Only process include_dir from the main config file. */ token = strtok_r(NULL, "", &saveptr); if(!token){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty include_dir value in configuration."); return 1; } #ifdef WIN32 snprintf(dirpath, MAX_PATH, "%s\\*.conf", token); fh = FindFirstFile(dirpath, &find_data); if(fh == INVALID_HANDLE_VALUE){ /* No files found */ continue; } do{ len = strlen(token)+1+strlen(find_data.cFileName)+1; conf_file = mosquitto__malloc(len+1); if(!conf_file){ FindClose(fh); return MOSQ_ERR_NOMEM; } snprintf(conf_file, len, "%s\\%s", token, find_data.cFileName); conf_file[len] = '\0'; rc = config__read_file(config, reload, conf_file, cr, level+1, &lineno_ext); if(rc){ FindClose(fh); log__printf(NULL, MOSQ_LOG_ERR, "Error found at %s:%d.", conf_file, lineno_ext); mosquitto__free(conf_file); return rc; } mosquitto__free(conf_file); }while(FindNextFile(fh, &find_data)); FindClose(fh); #else dh = opendir(token); if(!dh){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open include_dir '%s'.", token); return 1; } while((de = readdir(dh)) != NULL){ if(strlen(de->d_name) > 5){ if(!strcmp(&de->d_name[strlen(de->d_name)-5], ".conf")){ len = strlen(token)+1+strlen(de->d_name)+1; conf_file = mosquitto__malloc(len+1); if(!conf_file){ closedir(dh); return MOSQ_ERR_NOMEM; } snprintf(conf_file, len, "%s/%s", token, de->d_name); conf_file[len] = '\0'; rc = config__read_file(config, reload, conf_file, cr, level+1, &lineno_ext); if(rc){ closedir(dh); log__printf(NULL, MOSQ_LOG_ERR, "Error found at %s:%d.", conf_file, lineno_ext); mosquitto__free(conf_file); return rc; } mosquitto__free(conf_file); } } } closedir(dh); #endif } }else if(!strcmp(token, "keepalive_interval")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_int(&token, "keepalive_interval", &cur_bridge->keepalive, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->keepalive < 5){ log__printf(NULL, MOSQ_LOG_NOTICE, "keepalive interval too low, using 5 seconds."); cur_bridge->keepalive = 5; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "keyfile")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "keyfile", &cur_listener->keyfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "listener")){ token = strtok_r(NULL, " ", &saveptr); if(token){ tmp_int = atoi(token); if(tmp_int < 1 || tmp_int > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } if(reload){ /* We reload listeners settings based on port number. * If the port number doesn't already exist, exit with a complaint. */ cur_listener = NULL; for(i=0; i<config->listener_count; i++){ if(config->listeners[i].port == tmp_int){ cur_listener = &config->listeners[i]; } } if(!cur_listener){ log__printf(NULL, MOSQ_LOG_ERR, "Error: It is not currently possible to add/remove listeners when reloading the config file."); return MOSQ_ERR_INVAL; } }else{ config->listener_count++; config->listeners = mosquitto__realloc(config->listeners, sizeof(struct mosquitto__listener)*config->listener_count); if(!config->listeners){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_listener = &config->listeners[config->listener_count-1]; memset(cur_listener, 0, sizeof(struct mosquitto__listener)); } cur_listener->security_options.allow_anonymous = -1; cur_listener->protocol = mp_mqtt; cur_listener->port = tmp_int; token = strtok_r(NULL, "", &saveptr); mosquitto__free(cur_listener->host); if(token){ cur_listener->host = mosquitto__strdup(token); }else{ cur_listener->host = NULL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty listener value in configuration."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "local_clientid")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge local clientd", &cur_bridge->local_clientid, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "local_password")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge local_password", &cur_bridge->local_password, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "local_username")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge local_username", &cur_bridge->local_username, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "log_dest")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->log_dest_set = 1; if(!strcmp(token, "none")){ cr->log_dest = MQTT3_LOG_NONE; }else if(!strcmp(token, "syslog")){ cr->log_dest |= MQTT3_LOG_SYSLOG; }else if(!strcmp(token, "stdout")){ cr->log_dest |= MQTT3_LOG_STDOUT; }else if(!strcmp(token, "stderr")){ cr->log_dest |= MQTT3_LOG_STDERR; }else if(!strcmp(token, "topic")){ cr->log_dest |= MQTT3_LOG_TOPIC; }else if(!strcmp(token, "file")){ cr->log_dest |= MQTT3_LOG_FILE; if(config->log_fptr || config->log_file){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate \"log_dest file\" value."); return MOSQ_ERR_INVAL; } /* Get remaining string. */ token = &token[strlen(token)+1]; while(token[0] == ' ' || token[0] == '\t'){ token++; } if(token[0]){ config->log_file = mosquitto__strdup(token); if(!config->log_file){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty \"log_dest file\" value in configuration."); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid log_dest value (%s).", token); return MOSQ_ERR_INVAL; } #if defined(WIN32) || defined(__CYGWIN__) if(service_handle){ if(cr->log_dest == MQTT3_LOG_STDOUT || cr->log_dest == MQTT3_LOG_STDERR){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot log to stdout/stderr when running as a Windows service."); return MOSQ_ERR_INVAL; } } #endif }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty log_dest value in configuration."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "log_facility")){ #if defined(WIN32) || defined(__CYGWIN__) log__printf(NULL, MOSQ_LOG_WARNING, "Warning: log_facility not supported on Windows."); #else if(conf__parse_int(&token, "log_facility", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; switch(tmp_int){ case 0: config->log_facility = LOG_LOCAL0; break; case 1: config->log_facility = LOG_LOCAL1; break; case 2: config->log_facility = LOG_LOCAL2; break; case 3: config->log_facility = LOG_LOCAL3; break; case 4: config->log_facility = LOG_LOCAL4; break; case 5: config->log_facility = LOG_LOCAL5; break; case 6: config->log_facility = LOG_LOCAL6; break; case 7: config->log_facility = LOG_LOCAL7; break; default: log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid log_facility value (%d).", tmp_int); return MOSQ_ERR_INVAL; } #endif }else if(!strcmp(token, "log_timestamp")){ if(conf__parse_bool(&token, token, &config->log_timestamp, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "log_type")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->log_type_set = 1; if(!strcmp(token, "none")){ cr->log_type = MOSQ_LOG_NONE; }else if(!strcmp(token, "information")){ cr->log_type |= MOSQ_LOG_INFO; }else if(!strcmp(token, "notice")){ cr->log_type |= MOSQ_LOG_NOTICE; }else if(!strcmp(token, "warning")){ cr->log_type |= MOSQ_LOG_WARNING; }else if(!strcmp(token, "error")){ cr->log_type |= MOSQ_LOG_ERR; }else if(!strcmp(token, "debug")){ cr->log_type |= MOSQ_LOG_DEBUG; }else if(!strcmp(token, "subscribe")){ cr->log_type |= MOSQ_LOG_SUBSCRIBE; }else if(!strcmp(token, "unsubscribe")){ cr->log_type |= MOSQ_LOG_UNSUBSCRIBE; #ifdef WITH_WEBSOCKETS }else if(!strcmp(token, "websockets")){ cr->log_type |= MOSQ_LOG_WEBSOCKETS; #endif }else if(!strcmp(token, "all")){ cr->log_type = INT_MAX; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid log_type value (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty log_type value in configuration."); } }else if(!strcmp(token, "max_connections")){ if(reload) continue; // Listeners not valid for reloading. token = strtok_r(NULL, " ", &saveptr); if(token){ cur_listener->max_connections = atoi(token); if(cur_listener->max_connections < 0) cur_listener->max_connections = -1; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_connections value in configuration."); } }else if(!strcmp(token, "max_inflight_bytes")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->max_inflight_bytes = atol(token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_inflight_bytes value in configuration."); } }else if(!strcmp(token, "max_inflight_messages")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->max_inflight_messages = atoi(token); if(cr->max_inflight_messages < 0) cr->max_inflight_messages = 0; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_inflight_messages value in configuration."); } }else if(!strcmp(token, "max_queued_bytes")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->max_queued_bytes = atol(token); /* 63 bits is ok right? */ }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_queued_bytes value in configuration."); } }else if(!strcmp(token, "max_queued_messages")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->max_queued_messages = atoi(token); if(cr->max_queued_messages < 0) cr->max_queued_messages = 0; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_queued_messages value in configuration."); } }else if(!strcmp(token, "memory_limit")){ ssize_t lim; if(conf__parse_ssize_t(&token, "memory_limit", &lim, saveptr)) return MOSQ_ERR_INVAL; if(lim < 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid memory_limit value (%ld).", lim); return MOSQ_ERR_INVAL; } memory__set_limit(lim); }else if(!strcmp(token, "message_size_limit")){ if(conf__parse_int(&token, "message_size_limit", (int *)&config->message_size_limit, saveptr)) return MOSQ_ERR_INVAL; if(config->message_size_limit > MQTT_MAX_PAYLOAD){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid message_size_limit value (%u).", config->message_size_limit); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "mount_point")){ if(reload) continue; // Listeners not valid for reloading. if(config->listener_count == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: You must use create a listener before using the mount_point option in the configuration file."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "mount_point", &cur_listener->mount_point, saveptr)) return MOSQ_ERR_INVAL; if(mosquitto_pub_topic_check(cur_listener->mount_point) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid mount_point '%s'. Does it contain a wildcard character?", cur_listener->mount_point); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "notifications")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "notifications", &cur_bridge->notifications, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "notifications_local_only")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration"); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "notifications_local_only", &cur_bridge->notifications_local_only, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "notification_topic")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "notification_topic", &cur_bridge->notification_topic, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "password") || !strcmp(token, "remote_password")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge remote_password", &cur_bridge->remote_password, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "password_file")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(reload){ mosquitto__free(cur_security_options->password_file); cur_security_options->password_file = NULL; } if(conf__parse_string(&token, "password_file", &cur_security_options->password_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "per_listener_settings")){ if(conf__parse_bool(&token, "per_listener_settings", &config->per_listener_settings, saveptr)) return MOSQ_ERR_INVAL; if(cur_security_options && config->per_listener_settings){ log__printf(NULL, MOSQ_LOG_ERR, "Error: per_listener_settings must be set before any other security settings."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "persistence") || !strcmp(token, "retained_persistence")){ if(conf__parse_bool(&token, token, &config->persistence, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "persistence_file")){ if(conf__parse_string(&token, "persistence_file", &config->persistence_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "persistence_location")){ if(conf__parse_string(&token, "persistence_location", &config->persistence_location, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "persistent_client_expiration")){ token = strtok_r(NULL, " ", &saveptr); if(token){ switch(token[strlen(token)-1]){ case 'h': expiration_mult = 3600; break; case 'd': expiration_mult = 86400; break; case 'w': expiration_mult = 86400*7; break; case 'm': expiration_mult = 86400*30; break; case 'y': expiration_mult = 86400*365; break; default: log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid persistent_client_expiration duration in configuration."); return MOSQ_ERR_INVAL; } token[strlen(token)-1] = '\0'; config->persistent_client_expiration = atoi(token)*expiration_mult; if(config->persistent_client_expiration <= 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid persistent_client_expiration duration in configuration."); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty persistent_client_expiration value in configuration."); } }else if(!strcmp(token, "pid_file")){ if(reload) continue; // pid file not valid for reloading. if(conf__parse_string(&token, "pid_file", &config->pid_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "port")){ if(reload) continue; // Listener not valid for reloading. if(config->default_listener.port){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Default listener port specified multiple times. Only the latest will be used."); } if(conf__parse_int(&token, "port", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 1 || tmp_int > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } config->default_listener.port = tmp_int; }else if(!strcmp(token, "protocol")){ token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "mqtt")){ cur_listener->protocol = mp_mqtt; /* }else if(!strcmp(token, "mqttsn")){ cur_listener->protocol = mp_mqttsn; */ }else if(!strcmp(token, "websockets")){ #ifdef WITH_WEBSOCKETS cur_listener->protocol = mp_websockets; config->have_websockets_listener = true; #else log__printf(NULL, MOSQ_LOG_ERR, "Error: Websockets support not available."); return MOSQ_ERR_INVAL; #endif }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid protocol value (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty protocol value in configuration."); } }else if(!strcmp(token, "psk_file")){ #ifdef WITH_TLS_PSK conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(reload){ mosquitto__free(cur_security_options->psk_file); cur_security_options->psk_file = NULL; } if(conf__parse_string(&token, "psk_file", &cur_security_options->psk_file, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS/TLS-PSK support not available."); #endif }else if(!strcmp(token, "psk_hint")){ #ifdef WITH_TLS_PSK if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "psk_hint", &cur_listener->psk_hint, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS/TLS-PSK support not available."); #endif }else if(!strcmp(token, "queue_qos0_messages")){ if(conf__parse_bool(&token, token, &config->queue_qos0_messages, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "require_certificate")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "require_certificate", &cur_listener->require_certificate, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "restart_timeout")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_int(&token, "restart_timeout", &cur_bridge->restart_timeout, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->restart_timeout < 1){ log__printf(NULL, MOSQ_LOG_NOTICE, "restart_timeout interval too low, using 1 second."); cur_bridge->restart_timeout = 1; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "retry_interval")){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: The retry_interval option is no longer available."); }else if(!strcmp(token, "round_robin")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "round_robin", &cur_bridge->round_robin, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "set_tcp_nodelay")){ if(conf__parse_bool(&token, "set_tcp_nodelay", &config->set_tcp_nodelay, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "start_type")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "automatic")){ cur_bridge->start_type = bst_automatic; }else if(!strcmp(token, "lazy")){ cur_bridge->start_type = bst_lazy; }else if(!strcmp(token, "manual")){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Manual start_type not supported."); return MOSQ_ERR_INVAL; }else if(!strcmp(token, "once")){ cur_bridge->start_type = bst_once; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid start_type value in configuration (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty start_type value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "socket_domain")){ if(reload) continue; // Listeners not valid for reloading. token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "ipv4")){ cur_listener->socket_domain = AF_INET; }else if(!strcmp(token, "ipv6")){ cur_listener->socket_domain = AF_INET6; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid socket_domain value \"%s\" in configuration.", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty socket_domain value in configuration."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "store_clean_interval")){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: store_clean_interval is no longer needed."); }else if(!strcmp(token, "sys_interval")){ if(conf__parse_int(&token, "sys_interval", &config->sys_interval, saveptr)) return MOSQ_ERR_INVAL; if(config->sys_interval < 0 || config->sys_interval > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid sys_interval value (%d).", config->sys_interval); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "threshold")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_int(&token, "threshold", &cur_bridge->threshold, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->threshold < 1){ log__printf(NULL, MOSQ_LOG_NOTICE, "threshold too low, using 1 message."); cur_bridge->threshold = 1; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "tls_version")){ #if defined(WITH_TLS) if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "tls_version", &cur_listener->tls_version, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "topic")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ cur_bridge->topic_count++; cur_bridge->topics = mosquitto__realloc(cur_bridge->topics, sizeof(struct mosquitto__bridge_topic)*cur_bridge->topic_count); if(!cur_bridge->topics){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_topic = &cur_bridge->topics[cur_bridge->topic_count-1]; if(!strcmp(token, "\"\"")){ cur_topic->topic = NULL; }else{ cur_topic->topic = mosquitto__strdup(token); if(!cur_topic->topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } cur_topic->direction = bd_out; cur_topic->qos = 0; cur_topic->local_prefix = NULL; cur_topic->remote_prefix = NULL; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty topic value in configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcasecmp(token, "out")){ cur_topic->direction = bd_out; }else if(!strcasecmp(token, "in")){ cur_topic->direction = bd_in; }else if(!strcasecmp(token, "both")){ cur_topic->direction = bd_both; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic direction '%s'.", token); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ cur_topic->qos = atoi(token); if(cur_topic->qos < 0 || cur_topic->qos > 2){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge QoS level '%s'.", token); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ cur_bridge->topic_remapping = true; if(!strcmp(token, "\"\"")){ cur_topic->local_prefix = NULL; }else{ if(mosquitto_pub_topic_check(token) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic local prefix '%s'.", token); return MOSQ_ERR_INVAL; } cur_topic->local_prefix = mosquitto__strdup(token); if(!cur_topic->local_prefix){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "\"\"")){ cur_topic->remote_prefix = NULL; }else{ if(mosquitto_pub_topic_check(token) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic remote prefix '%s'.", token); return MOSQ_ERR_INVAL; } cur_topic->remote_prefix = mosquitto__strdup(token); if(!cur_topic->remote_prefix){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } } } } } if(cur_topic->topic == NULL && (cur_topic->local_prefix == NULL || cur_topic->remote_prefix == NULL)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge remapping."); return MOSQ_ERR_INVAL; } if(cur_topic->local_prefix){ if(cur_topic->topic){ len = strlen(cur_topic->topic) + strlen(cur_topic->local_prefix)+1; cur_topic->local_topic = mosquitto__malloc(len+1); if(!cur_topic->local_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } snprintf(cur_topic->local_topic, len+1, "%s%s", cur_topic->local_prefix, cur_topic->topic); cur_topic->local_topic[len] = '\0'; }else{ cur_topic->local_topic = mosquitto__strdup(cur_topic->local_prefix); if(!cur_topic->local_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } }else{ cur_topic->local_topic = mosquitto__strdup(cur_topic->topic); if(!cur_topic->local_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } if(cur_topic->remote_prefix){ if(cur_topic->topic){ len = strlen(cur_topic->topic) + strlen(cur_topic->remote_prefix)+1; cur_topic->remote_topic = mosquitto__malloc(len+1); if(!cur_topic->remote_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } snprintf(cur_topic->remote_topic, len, "%s%s", cur_topic->remote_prefix, cur_topic->topic); cur_topic->remote_topic[len] = '\0'; }else{ cur_topic->remote_topic = mosquitto__strdup(cur_topic->remote_prefix); if(!cur_topic->remote_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } }else{ cur_topic->remote_topic = mosquitto__strdup(cur_topic->topic); if(!cur_topic->remote_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "try_private")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "try_private", &cur_bridge->try_private, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "upgrade_outgoing_qos")){ if(conf__parse_bool(&token, token, &config->upgrade_outgoing_qos, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "use_identity_as_username")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "use_identity_as_username", &cur_listener->use_identity_as_username, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "use_subject_as_username")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "use_subject_as_username", &cur_listener->use_subject_as_username, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "user")){ if(reload) continue; // Drop privileges user not valid for reloading. if(conf__parse_string(&token, "user", &config->user, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "use_username_as_clientid")){ if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "use_username_as_clientid", &cur_listener->use_username_as_clientid, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "username") || !strcmp(token, "remote_username")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ if(cur_bridge->remote_username){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate username value in bridge configuration."); return MOSQ_ERR_INVAL; } cur_bridge->remote_username = mosquitto__strdup(token); if(!cur_bridge->remote_username){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty username value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "websockets_log_level")){ #ifdef WITH_WEBSOCKETS if(conf__parse_int(&token, "websockets_log_level", &config->websockets_log_level, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Websockets support not available."); #endif }else if(!strcmp(token, "trace_level") || !strcmp(token, "ffdc_output") || !strcmp(token, "max_log_entries") || !strcmp(token, "trace_output")){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Unsupported rsmb configuration option \"%s\".", token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unknown configuration variable \"%s\".", token); return MOSQ_ERR_INVAL; } } } } return MOSQ_ERR_SUCCESS; } int config__read_file(struct mosquitto__config *config, bool reload, const char *file, struct config_recurse *cr, int level, int *lineno) { int rc; FILE *fptr = NULL; char *buf; int buflen; fptr = mosquitto__fopen(file, "rt", false); if(!fptr){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open config file %s\n", file); return 1; } buflen = 1000; buf = mosquitto__malloc(buflen); if(!buf){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); fclose(fptr); return MOSQ_ERR_NOMEM; } rc = config__read_file_core(config, reload, cr, level, lineno, fptr, &buf, &buflen); mosquitto__free(buf); fclose(fptr); return rc; } static int config__check(struct mosquitto__config *config) { /* Checks that are easy to make after the config has been loaded. */ #ifdef WITH_BRIDGE int i, j; struct mosquitto__bridge *bridge1, *bridge2; char hostname[256]; int len; /* Check for bridge duplicate local_clientid, need to generate missing IDs * first. */ for(i=0; i<config->bridge_count; i++){ bridge1 = &config->bridges[i]; if(!bridge1->remote_clientid){ if(!gethostname(hostname, 256)){ len = strlen(hostname) + strlen(bridge1->name) + 2; bridge1->remote_clientid = mosquitto__malloc(len); if(!bridge1->remote_clientid){ return MOSQ_ERR_NOMEM; } snprintf(bridge1->remote_clientid, len, "%s.%s", hostname, bridge1->name); }else{ return 1; } } if(!bridge1->local_clientid){ len = strlen(bridge1->remote_clientid) + strlen("local.") + 2; bridge1->local_clientid = mosquitto__malloc(len); if(!bridge1->local_clientid){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } snprintf(bridge1->local_clientid, len, "local.%s", bridge1->remote_clientid); } } for(i=0; i<config->bridge_count; i++){ bridge1 = &config->bridges[i]; for(j=i+1; j<config->bridge_count; j++){ bridge2 = &config->bridges[j]; if(!strcmp(bridge1->local_clientid, bridge2->local_clientid)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Bridge local_clientid " "'%s' is not unique. Try changing or setting the " "local_clientid value for one of the bridges.", bridge1->local_clientid); return MOSQ_ERR_INVAL; } } } #endif return MOSQ_ERR_SUCCESS; } static int conf__parse_bool(char **token, const char *name, bool *value, char *saveptr) { *token = strtok_r(NULL, " ", &saveptr); if(*token){ if(!strcmp(*token, "false") || !strcmp(*token, "0")){ *value = false; }else if(!strcmp(*token, "true") || !strcmp(*token, "1")){ *value = true; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid %s value (%s).", name, *token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static int conf__parse_int(char **token, const char *name, int *value, char *saveptr) { *token = strtok_r(NULL, " ", &saveptr); if(*token){ *value = atoi(*token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static int conf__parse_ssize_t(char **token, const char *name, ssize_t *value, char *saveptr) { *token = strtok_r(NULL, " ", &saveptr); if(*token){ *value = atol(*token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static int conf__parse_string(char **token, const char *name, char **value, char *saveptr) { *token = strtok_r(NULL, "", &saveptr); if(*token){ if(*value){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate %s value in configuration.", name); return MOSQ_ERR_INVAL; } /* Deal with multiple spaces at the beginning of the string. */ while((*token)[0] == ' ' || (*token)[0] == '\t'){ (*token)++; } if(mosquitto_validate_utf8(*token, strlen(*token))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Malformed UTF-8 in configuration."); return MOSQ_ERR_INVAL; } *value = mosquitto__strdup(*token); if(!*value){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-254/c/good_480_1
crossvul-cpp_data_bad_1547_0
/* * linux/fs/namei.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * Some corrections by tytso. */ /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname * lookup logic. */ /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture. */ #include <linux/init.h> #include <linux/export.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/namei.h> #include <linux/pagemap.h> #include <linux/fsnotify.h> #include <linux/personality.h> #include <linux/security.h> #include <linux/ima.h> #include <linux/syscalls.h> #include <linux/mount.h> #include <linux/audit.h> #include <linux/capability.h> #include <linux/file.h> #include <linux/fcntl.h> #include <linux/device_cgroup.h> #include <linux/fs_struct.h> #include <linux/posix_acl.h> #include <linux/hash.h> #include <asm/uaccess.h> #include "internal.h" #include "mount.h" /* [Feb-1997 T. Schoebel-Theuer] * Fundamental changes in the pathname lookup mechanisms (namei) * were necessary because of omirr. The reason is that omirr needs * to know the _real_ pathname, not the user-supplied one, in case * of symlinks (and also when transname replacements occur). * * The new code replaces the old recursive symlink resolution with * an iterative one (in case of non-nested symlink chains). It does * this with calls to <fs>_follow_link(). * As a side effect, dir_namei(), _namei() and follow_link() are now * replaced with a single function lookup_dentry() that can handle all * the special cases of the former code. * * With the new dcache, the pathname is stored at each inode, at least as * long as the refcount of the inode is positive. As a side effect, the * size of the dcache depends on the inode cache and thus is dynamic. * * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink * resolution to correspond with current state of the code. * * Note that the symlink resolution is not *completely* iterative. * There is still a significant amount of tail- and mid- recursion in * the algorithm. Also, note that <fs>_readlink() is not used in * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink() * may return different results than <fs>_follow_link(). Many virtual * filesystems (including /proc) exhibit this behavior. */ /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation: * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL * and the name already exists in form of a symlink, try to create the new * name indicated by the symlink. The old code always complained that the * name already exists, due to not following the symlink even if its target * is nonexistent. The new semantics affects also mknod() and link() when * the name is a symlink pointing to a non-existent name. * * I don't know which semantics is the right one, since I have no access * to standards. But I found by trial that HP-UX 9.0 has the full "new" * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the * "old" one. Personally, I think the new semantics is much more logical. * Note that "ln old new" where "new" is a symlink pointing to a non-existing * file does succeed in both HP-UX and SunOs, but not in Solaris * and in the old Linux semantics. */ /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink * semantics. See the comments in "open_namei" and "do_link" below. * * [10-Sep-98 Alan Modra] Another symlink change. */ /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks: * inside the path - always follow. * in the last component in creation/removal/renaming - never follow. * if LOOKUP_FOLLOW passed - follow. * if the pathname has trailing slashes - follow. * otherwise - don't follow. * (applied in that order). * * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT * restored for 2.4. This is the last surviving part of old 4.2BSD bug. * During the 2.4 we need to fix the userland stuff depending on it - * hopefully we will be able to get rid of that wart in 2.5. So far only * XEmacs seems to be relying on it... */ /* * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland) * implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives * any extra contention... */ /* In order to reduce some races, while at the same time doing additional * checking and hopefully speeding things up, we copy filenames to the * kernel data space before using them.. * * POSIX.1 2.4: an empty pathname is invalid (ENOENT). * PATH_MAX includes the nul terminator --RR. */ #define EMBEDDED_NAME_MAX (PATH_MAX - offsetof(struct filename, iname)) struct filename * getname_flags(const char __user *filename, int flags, int *empty) { struct filename *result; char *kname; int len; result = audit_reusename(filename); if (result) return result; result = __getname(); if (unlikely(!result)) return ERR_PTR(-ENOMEM); /* * First, try to embed the struct filename inside the names_cache * allocation */ kname = (char *)result->iname; result->name = kname; len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX); if (unlikely(len < 0)) { __putname(result); return ERR_PTR(len); } /* * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a * separate struct filename so we can dedicate the entire * names_cache allocation for the pathname, and re-do the copy from * userland. */ if (unlikely(len == EMBEDDED_NAME_MAX)) { const size_t size = offsetof(struct filename, iname[1]); kname = (char *)result; /* * size is chosen that way we to guarantee that * result->iname[0] is within the same object and that * kname can't be equal to result->iname, no matter what. */ result = kzalloc(size, GFP_KERNEL); if (unlikely(!result)) { __putname(kname); return ERR_PTR(-ENOMEM); } result->name = kname; len = strncpy_from_user(kname, filename, PATH_MAX); if (unlikely(len < 0)) { __putname(kname); kfree(result); return ERR_PTR(len); } if (unlikely(len == PATH_MAX)) { __putname(kname); kfree(result); return ERR_PTR(-ENAMETOOLONG); } } result->refcnt = 1; /* The empty path is special. */ if (unlikely(!len)) { if (empty) *empty = 1; if (!(flags & LOOKUP_EMPTY)) { putname(result); return ERR_PTR(-ENOENT); } } result->uptr = filename; result->aname = NULL; audit_getname(result); return result; } struct filename * getname(const char __user * filename) { return getname_flags(filename, 0, NULL); } struct filename * getname_kernel(const char * filename) { struct filename *result; int len = strlen(filename) + 1; result = __getname(); if (unlikely(!result)) return ERR_PTR(-ENOMEM); if (len <= EMBEDDED_NAME_MAX) { result->name = (char *)result->iname; } else if (len <= PATH_MAX) { struct filename *tmp; tmp = kmalloc(sizeof(*tmp), GFP_KERNEL); if (unlikely(!tmp)) { __putname(result); return ERR_PTR(-ENOMEM); } tmp->name = (char *)result; result = tmp; } else { __putname(result); return ERR_PTR(-ENAMETOOLONG); } memcpy((char *)result->name, filename, len); result->uptr = NULL; result->aname = NULL; result->refcnt = 1; audit_getname(result); return result; } void putname(struct filename *name) { BUG_ON(name->refcnt <= 0); if (--name->refcnt > 0) return; if (name->name != name->iname) { __putname(name->name); kfree(name); } else __putname(name); } static int check_acl(struct inode *inode, int mask) { #ifdef CONFIG_FS_POSIX_ACL struct posix_acl *acl; if (mask & MAY_NOT_BLOCK) { acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS); if (!acl) return -EAGAIN; /* no ->get_acl() calls in RCU mode... */ if (acl == ACL_NOT_CACHED) return -ECHILD; return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK); } acl = get_acl(inode, ACL_TYPE_ACCESS); if (IS_ERR(acl)) return PTR_ERR(acl); if (acl) { int error = posix_acl_permission(inode, acl, mask); posix_acl_release(acl); return error; } #endif return -EAGAIN; } /* * This does the basic permission checking */ static int acl_permission_check(struct inode *inode, int mask) { unsigned int mode = inode->i_mode; if (likely(uid_eq(current_fsuid(), inode->i_uid))) mode >>= 6; else { if (IS_POSIXACL(inode) && (mode & S_IRWXG)) { int error = check_acl(inode, mask); if (error != -EAGAIN) return error; } if (in_group_p(inode->i_gid)) mode >>= 3; } /* * If the DACs are ok we don't need any capability check. */ if ((mask & ~mode & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0) return 0; return -EACCES; } /** * generic_permission - check for access rights on a Posix-like filesystem * @inode: inode to check access rights for * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...) * * Used to check for read/write/execute permissions on a file. * We use "fsuid" for this, letting us set arbitrary permissions * for filesystem access without changing the "normal" uids which * are used for other things. * * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk * request cannot be satisfied (eg. requires blocking or too much complexity). * It would then be called again in ref-walk mode. */ int generic_permission(struct inode *inode, int mask) { int ret; /* * Do the basic permission checks. */ ret = acl_permission_check(inode, mask); if (ret != -EACCES) return ret; if (S_ISDIR(inode->i_mode)) { /* DACs are overridable for directories */ if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE)) return 0; if (!(mask & MAY_WRITE)) if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } /* * Read/write DACs are always overridable. * Executable DACs are overridable when there is * at least one exec bit set. */ if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO)) if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE)) return 0; /* * Searching includes executable on directories, else just read. */ mask &= MAY_READ | MAY_WRITE | MAY_EXEC; if (mask == MAY_READ) if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } EXPORT_SYMBOL(generic_permission); /* * We _really_ want to just do "generic_permission()" without * even looking at the inode->i_op values. So we keep a cache * flag in inode->i_opflags, that says "this has not special * permission function, use the fast case". */ static inline int do_inode_permission(struct inode *inode, int mask) { if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) { if (likely(inode->i_op->permission)) return inode->i_op->permission(inode, mask); /* This gets set once for the inode lifetime */ spin_lock(&inode->i_lock); inode->i_opflags |= IOP_FASTPERM; spin_unlock(&inode->i_lock); } return generic_permission(inode, mask); } /** * __inode_permission - Check for access rights to a given inode * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Check for read/write/execute permissions on an inode. * * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask. * * This does not check for a read-only file system. You probably want * inode_permission(). */ int __inode_permission(struct inode *inode, int mask) { int retval; if (unlikely(mask & MAY_WRITE)) { /* * Nobody gets write access to an immutable file. */ if (IS_IMMUTABLE(inode)) return -EACCES; } retval = do_inode_permission(inode, mask); if (retval) return retval; retval = devcgroup_inode_permission(inode, mask); if (retval) return retval; return security_inode_permission(inode, mask); } EXPORT_SYMBOL(__inode_permission); /** * sb_permission - Check superblock-level permissions * @sb: Superblock of inode to check permission on * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Separate out file-system wide checks from inode-specific permission checks. */ static int sb_permission(struct super_block *sb, struct inode *inode, int mask) { if (unlikely(mask & MAY_WRITE)) { umode_t mode = inode->i_mode; /* Nobody gets write access to a read-only fs. */ if ((sb->s_flags & MS_RDONLY) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) return -EROFS; } return 0; } /** * inode_permission - Check for access rights to a given inode * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Check for read/write/execute permissions on an inode. We use fs[ug]id for * this, letting us set arbitrary permissions for filesystem access without * changing the "normal" UIDs which are used for other things. * * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask. */ int inode_permission(struct inode *inode, int mask) { int retval; retval = sb_permission(inode->i_sb, inode, mask); if (retval) return retval; return __inode_permission(inode, mask); } EXPORT_SYMBOL(inode_permission); /** * path_get - get a reference to a path * @path: path to get the reference to * * Given a path increment the reference count to the dentry and the vfsmount. */ void path_get(const struct path *path) { mntget(path->mnt); dget(path->dentry); } EXPORT_SYMBOL(path_get); /** * path_put - put a reference to a path * @path: path to put the reference to * * Given a path decrement the reference count to the dentry and the vfsmount. */ void path_put(const struct path *path) { dput(path->dentry); mntput(path->mnt); } EXPORT_SYMBOL(path_put); #define EMBEDDED_LEVELS 2 struct nameidata { struct path path; struct qstr last; struct path root; struct inode *inode; /* path.dentry.d_inode */ unsigned int flags; unsigned seq, m_seq; int last_type; unsigned depth; int total_link_count; struct saved { struct path link; void *cookie; const char *name; struct inode *inode; unsigned seq; } *stack, internal[EMBEDDED_LEVELS]; struct filename *name; struct nameidata *saved; unsigned root_seq; int dfd; }; static void set_nameidata(struct nameidata *p, int dfd, struct filename *name) { struct nameidata *old = current->nameidata; p->stack = p->internal; p->dfd = dfd; p->name = name; p->total_link_count = old ? old->total_link_count : 0; p->saved = old; current->nameidata = p; } static void restore_nameidata(void) { struct nameidata *now = current->nameidata, *old = now->saved; current->nameidata = old; if (old) old->total_link_count = now->total_link_count; if (now->stack != now->internal) { kfree(now->stack); now->stack = now->internal; } } static int __nd_alloc_stack(struct nameidata *nd) { struct saved *p; if (nd->flags & LOOKUP_RCU) { p= kmalloc(MAXSYMLINKS * sizeof(struct saved), GFP_ATOMIC); if (unlikely(!p)) return -ECHILD; } else { p= kmalloc(MAXSYMLINKS * sizeof(struct saved), GFP_KERNEL); if (unlikely(!p)) return -ENOMEM; } memcpy(p, nd->internal, sizeof(nd->internal)); nd->stack = p; return 0; } static inline int nd_alloc_stack(struct nameidata *nd) { if (likely(nd->depth != EMBEDDED_LEVELS)) return 0; if (likely(nd->stack != nd->internal)) return 0; return __nd_alloc_stack(nd); } static void drop_links(struct nameidata *nd) { int i = nd->depth; while (i--) { struct saved *last = nd->stack + i; struct inode *inode = last->inode; if (last->cookie && inode->i_op->put_link) { inode->i_op->put_link(inode, last->cookie); last->cookie = NULL; } } } static void terminate_walk(struct nameidata *nd) { drop_links(nd); if (!(nd->flags & LOOKUP_RCU)) { int i; path_put(&nd->path); for (i = 0; i < nd->depth; i++) path_put(&nd->stack[i].link); if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) { path_put(&nd->root); nd->root.mnt = NULL; } } else { nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); } nd->depth = 0; } /* path_put is needed afterwards regardless of success or failure */ static bool legitimize_path(struct nameidata *nd, struct path *path, unsigned seq) { int res = __legitimize_mnt(path->mnt, nd->m_seq); if (unlikely(res)) { if (res > 0) path->mnt = NULL; path->dentry = NULL; return false; } if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) { path->dentry = NULL; return false; } return !read_seqcount_retry(&path->dentry->d_seq, seq); } static bool legitimize_links(struct nameidata *nd) { int i; for (i = 0; i < nd->depth; i++) { struct saved *last = nd->stack + i; if (unlikely(!legitimize_path(nd, &last->link, last->seq))) { drop_links(nd); nd->depth = i + 1; return false; } } return true; } /* * Path walking has 2 modes, rcu-walk and ref-walk (see * Documentation/filesystems/path-lookup.txt). In situations when we can't * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab * normal reference counts on dentries and vfsmounts to transition to rcu-walk * mode. Refcounts are grabbed at the last known good point before rcu-walk * got stuck, so ref-walk may continue from there. If this is not successful * (eg. a seqcount has changed), then failure is returned and it's up to caller * to restart the path walk from the beginning in ref-walk mode. */ /** * unlazy_walk - try to switch to ref-walk mode. * @nd: nameidata pathwalk data * @dentry: child of nd->path.dentry or NULL * @seq: seq number to check dentry against * Returns: 0 on success, -ECHILD on failure * * unlazy_walk attempts to legitimize the current nd->path, nd->root and dentry * for ref-walk mode. @dentry must be a path found by a do_lookup call on * @nd or NULL. Must be called from rcu-walk context. * Nothing should touch nameidata between unlazy_walk() failure and * terminate_walk(). */ static int unlazy_walk(struct nameidata *nd, struct dentry *dentry, unsigned seq) { struct dentry *parent = nd->path.dentry; BUG_ON(!(nd->flags & LOOKUP_RCU)); nd->flags &= ~LOOKUP_RCU; if (unlikely(!legitimize_links(nd))) goto out2; if (unlikely(!legitimize_mnt(nd->path.mnt, nd->m_seq))) goto out2; if (unlikely(!lockref_get_not_dead(&parent->d_lockref))) goto out1; /* * For a negative lookup, the lookup sequence point is the parents * sequence point, and it only needs to revalidate the parent dentry. * * For a positive lookup, we need to move both the parent and the * dentry from the RCU domain to be properly refcounted. And the * sequence number in the dentry validates *both* dentry counters, * since we checked the sequence number of the parent after we got * the child sequence number. So we know the parent must still * be valid if the child sequence number is still valid. */ if (!dentry) { if (read_seqcount_retry(&parent->d_seq, nd->seq)) goto out; BUG_ON(nd->inode != parent->d_inode); } else { if (!lockref_get_not_dead(&dentry->d_lockref)) goto out; if (read_seqcount_retry(&dentry->d_seq, seq)) goto drop_dentry; } /* * Sequence counts matched. Now make sure that the root is * still valid and get it if required. */ if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) { if (unlikely(!legitimize_path(nd, &nd->root, nd->root_seq))) { rcu_read_unlock(); dput(dentry); return -ECHILD; } } rcu_read_unlock(); return 0; drop_dentry: rcu_read_unlock(); dput(dentry); goto drop_root_mnt; out2: nd->path.mnt = NULL; out1: nd->path.dentry = NULL; out: rcu_read_unlock(); drop_root_mnt: if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; return -ECHILD; } static int unlazy_link(struct nameidata *nd, struct path *link, unsigned seq) { if (unlikely(!legitimize_path(nd, link, seq))) { drop_links(nd); nd->depth = 0; nd->flags &= ~LOOKUP_RCU; nd->path.mnt = NULL; nd->path.dentry = NULL; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); } else if (likely(unlazy_walk(nd, NULL, 0)) == 0) { return 0; } path_put(link); return -ECHILD; } static inline int d_revalidate(struct dentry *dentry, unsigned int flags) { return dentry->d_op->d_revalidate(dentry, flags); } /** * complete_walk - successful completion of path walk * @nd: pointer nameidata * * If we had been in RCU mode, drop out of it and legitimize nd->path. * Revalidate the final result, unless we'd already done that during * the path walk or the filesystem doesn't ask for it. Return 0 on * success, -error on failure. In case of failure caller does not * need to drop nd->path. */ static int complete_walk(struct nameidata *nd) { struct dentry *dentry = nd->path.dentry; int status; if (nd->flags & LOOKUP_RCU) { if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; if (unlikely(unlazy_walk(nd, NULL, 0))) return -ECHILD; } if (likely(!(nd->flags & LOOKUP_JUMPED))) return 0; if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE))) return 0; status = dentry->d_op->d_weak_revalidate(dentry, nd->flags); if (status > 0) return 0; if (!status) status = -ESTALE; return status; } static void set_root(struct nameidata *nd) { get_fs_root(current->fs, &nd->root); } static void set_root_rcu(struct nameidata *nd) { struct fs_struct *fs = current->fs; unsigned seq; do { seq = read_seqcount_begin(&fs->seq); nd->root = fs->root; nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq); } while (read_seqcount_retry(&fs->seq, seq)); } static void path_put_conditional(struct path *path, struct nameidata *nd) { dput(path->dentry); if (path->mnt != nd->path.mnt) mntput(path->mnt); } static inline void path_to_nameidata(const struct path *path, struct nameidata *nd) { if (!(nd->flags & LOOKUP_RCU)) { dput(nd->path.dentry); if (nd->path.mnt != path->mnt) mntput(nd->path.mnt); } nd->path.mnt = path->mnt; nd->path.dentry = path->dentry; } /* * Helper to directly jump to a known parsed path from ->follow_link, * caller must have taken a reference to path beforehand. */ void nd_jump_link(struct path *path) { struct nameidata *nd = current->nameidata; path_put(&nd->path); nd->path = *path; nd->inode = nd->path.dentry->d_inode; nd->flags |= LOOKUP_JUMPED; } static inline void put_link(struct nameidata *nd) { struct saved *last = nd->stack + --nd->depth; struct inode *inode = last->inode; if (last->cookie && inode->i_op->put_link) inode->i_op->put_link(inode, last->cookie); if (!(nd->flags & LOOKUP_RCU)) path_put(&last->link); } int sysctl_protected_symlinks __read_mostly = 0; int sysctl_protected_hardlinks __read_mostly = 0; /** * may_follow_link - Check symlink following for unsafe situations * @nd: nameidata pathwalk data * * In the case of the sysctl_protected_symlinks sysctl being enabled, * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is * in a sticky world-writable directory. This is to protect privileged * processes from failing races against path names that may change out * from under them by way of other users creating malicious symlinks. * It will permit symlinks to be followed only when outside a sticky * world-writable directory, or when the uid of the symlink and follower * match, or when the directory owner matches the symlink's owner. * * Returns 0 if following the symlink is allowed, -ve on error. */ static inline int may_follow_link(struct nameidata *nd) { const struct inode *inode; const struct inode *parent; if (!sysctl_protected_symlinks) return 0; /* Allowed if owner and follower match. */ inode = nd->stack[0].inode; if (uid_eq(current_cred()->fsuid, inode->i_uid)) return 0; /* Allowed if parent directory not sticky and world-writable. */ parent = nd->inode; if ((parent->i_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH)) return 0; /* Allowed if parent directory and link owner match. */ if (uid_eq(parent->i_uid, inode->i_uid)) return 0; if (nd->flags & LOOKUP_RCU) return -ECHILD; audit_log_link_denied("follow_link", &nd->stack[0].link); return -EACCES; } /** * safe_hardlink_source - Check for safe hardlink conditions * @inode: the source inode to hardlink from * * Return false if at least one of the following conditions: * - inode is not a regular file * - inode is setuid * - inode is setgid and group-exec * - access failure for read and write * * Otherwise returns true. */ static bool safe_hardlink_source(struct inode *inode) { umode_t mode = inode->i_mode; /* Special files should not get pinned to the filesystem. */ if (!S_ISREG(mode)) return false; /* Setuid files should not get pinned to the filesystem. */ if (mode & S_ISUID) return false; /* Executable setgid files should not get pinned to the filesystem. */ if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) return false; /* Hardlinking to unreadable or unwritable sources is dangerous. */ if (inode_permission(inode, MAY_READ | MAY_WRITE)) return false; return true; } /** * may_linkat - Check permissions for creating a hardlink * @link: the source to hardlink from * * Block hardlink when all of: * - sysctl_protected_hardlinks enabled * - fsuid does not match inode * - hardlink source is unsafe (see safe_hardlink_source() above) * - not CAP_FOWNER * * Returns 0 if successful, -ve on error. */ static int may_linkat(struct path *link) { const struct cred *cred; struct inode *inode; if (!sysctl_protected_hardlinks) return 0; cred = current_cred(); inode = link->dentry->d_inode; /* Source inode owner (or CAP_FOWNER) can hardlink all they like, * otherwise, it must be a safe source. */ if (uid_eq(cred->fsuid, inode->i_uid) || safe_hardlink_source(inode) || capable(CAP_FOWNER)) return 0; audit_log_link_denied("linkat", link); return -EPERM; } static __always_inline const char *get_link(struct nameidata *nd) { struct saved *last = nd->stack + nd->depth - 1; struct dentry *dentry = last->link.dentry; struct inode *inode = last->inode; int error; const char *res; if (!(nd->flags & LOOKUP_RCU)) { touch_atime(&last->link); cond_resched(); } else if (atime_needs_update(&last->link, inode)) { if (unlikely(unlazy_walk(nd, NULL, 0))) return ERR_PTR(-ECHILD); touch_atime(&last->link); } error = security_inode_follow_link(dentry, inode, nd->flags & LOOKUP_RCU); if (unlikely(error)) return ERR_PTR(error); nd->last_type = LAST_BIND; res = inode->i_link; if (!res) { if (nd->flags & LOOKUP_RCU) { if (unlikely(unlazy_walk(nd, NULL, 0))) return ERR_PTR(-ECHILD); } res = inode->i_op->follow_link(dentry, &last->cookie); if (IS_ERR_OR_NULL(res)) { last->cookie = NULL; return res; } } if (*res == '/') { if (nd->flags & LOOKUP_RCU) { struct dentry *d; if (!nd->root.mnt) set_root_rcu(nd); nd->path = nd->root; d = nd->path.dentry; nd->inode = d->d_inode; nd->seq = nd->root_seq; if (unlikely(read_seqcount_retry(&d->d_seq, nd->seq))) return ERR_PTR(-ECHILD); } else { if (!nd->root.mnt) set_root(nd); path_put(&nd->path); nd->path = nd->root; path_get(&nd->root); nd->inode = nd->path.dentry->d_inode; } nd->flags |= LOOKUP_JUMPED; while (unlikely(*++res == '/')) ; } if (!*res) res = NULL; return res; } /* * follow_up - Find the mountpoint of path's vfsmount * * Given a path, find the mountpoint of its source file system. * Replace @path with the path of the mountpoint in the parent mount. * Up is towards /. * * Return 1 if we went up a level and 0 if we were already at the * root. */ int follow_up(struct path *path) { struct mount *mnt = real_mount(path->mnt); struct mount *parent; struct dentry *mountpoint; read_seqlock_excl(&mount_lock); parent = mnt->mnt_parent; if (parent == mnt) { read_sequnlock_excl(&mount_lock); return 0; } mntget(&parent->mnt); mountpoint = dget(mnt->mnt_mountpoint); read_sequnlock_excl(&mount_lock); dput(path->dentry); path->dentry = mountpoint; mntput(path->mnt); path->mnt = &parent->mnt; return 1; } EXPORT_SYMBOL(follow_up); /* * Perform an automount * - return -EISDIR to tell follow_managed() to stop and return the path we * were called with. */ static int follow_automount(struct path *path, struct nameidata *nd, bool *need_mntput) { struct vfsmount *mnt; int err; if (!path->dentry->d_op || !path->dentry->d_op->d_automount) return -EREMOTE; /* We don't want to mount if someone's just doing a stat - * unless they're stat'ing a directory and appended a '/' to * the name. * * We do, however, want to mount if someone wants to open or * create a file of any type under the mountpoint, wants to * traverse through the mountpoint or wants to open the * mounted directory. Also, autofs may mark negative dentries * as being automount points. These will need the attentions * of the daemon to instantiate them before they can be used. */ if (!(nd->flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY | LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) && path->dentry->d_inode) return -EISDIR; nd->total_link_count++; if (nd->total_link_count >= 40) return -ELOOP; mnt = path->dentry->d_op->d_automount(path); if (IS_ERR(mnt)) { /* * The filesystem is allowed to return -EISDIR here to indicate * it doesn't want to automount. For instance, autofs would do * this so that its userspace daemon can mount on this dentry. * * However, we can only permit this if it's a terminal point in * the path being looked up; if it wasn't then the remainder of * the path is inaccessible and we should say so. */ if (PTR_ERR(mnt) == -EISDIR && (nd->flags & LOOKUP_PARENT)) return -EREMOTE; return PTR_ERR(mnt); } if (!mnt) /* mount collision */ return 0; if (!*need_mntput) { /* lock_mount() may release path->mnt on error */ mntget(path->mnt); *need_mntput = true; } err = finish_automount(mnt, path); switch (err) { case -EBUSY: /* Someone else made a mount here whilst we were busy */ return 0; case 0: path_put(path); path->mnt = mnt; path->dentry = dget(mnt->mnt_root); return 0; default: return err; } } /* * Handle a dentry that is managed in some way. * - Flagged for transit management (autofs) * - Flagged as mountpoint * - Flagged as automount point * * This may only be called in refwalk mode. * * Serialization is taken care of in namespace.c */ static int follow_managed(struct path *path, struct nameidata *nd) { struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */ unsigned managed; bool need_mntput = false; int ret = 0; /* Given that we're not holding a lock here, we retain the value in a * local variable for each dentry as we look at it so that we don't see * the components of that value change under us */ while (managed = ACCESS_ONCE(path->dentry->d_flags), managed &= DCACHE_MANAGED_DENTRY, unlikely(managed != 0)) { /* Allow the filesystem to manage the transit without i_mutex * being held. */ if (managed & DCACHE_MANAGE_TRANSIT) { BUG_ON(!path->dentry->d_op); BUG_ON(!path->dentry->d_op->d_manage); ret = path->dentry->d_op->d_manage(path->dentry, false); if (ret < 0) break; } /* Transit to a mounted filesystem. */ if (managed & DCACHE_MOUNTED) { struct vfsmount *mounted = lookup_mnt(path); if (mounted) { dput(path->dentry); if (need_mntput) mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); need_mntput = true; continue; } /* Something is mounted on this dentry in another * namespace and/or whatever was mounted there in this * namespace got unmounted before lookup_mnt() could * get it */ } /* Handle an automount point */ if (managed & DCACHE_NEED_AUTOMOUNT) { ret = follow_automount(path, nd, &need_mntput); if (ret < 0) break; continue; } /* We didn't change the current path point */ break; } if (need_mntput && path->mnt == mnt) mntput(path->mnt); if (ret == -EISDIR) ret = 0; if (need_mntput) nd->flags |= LOOKUP_JUMPED; if (unlikely(ret < 0)) path_put_conditional(path, nd); return ret; } int follow_down_one(struct path *path) { struct vfsmount *mounted; mounted = lookup_mnt(path); if (mounted) { dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); return 1; } return 0; } EXPORT_SYMBOL(follow_down_one); static inline int managed_dentry_rcu(struct dentry *dentry) { return (dentry->d_flags & DCACHE_MANAGE_TRANSIT) ? dentry->d_op->d_manage(dentry, true) : 0; } /* * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if * we meet a managed dentry that would need blocking. */ static bool __follow_mount_rcu(struct nameidata *nd, struct path *path, struct inode **inode, unsigned *seqp) { for (;;) { struct mount *mounted; /* * Don't forget we might have a non-mountpoint managed dentry * that wants to block transit. */ switch (managed_dentry_rcu(path->dentry)) { case -ECHILD: default: return false; case -EISDIR: return true; case 0: break; } if (!d_mountpoint(path->dentry)) return !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT); mounted = __lookup_mnt(path->mnt, path->dentry); if (!mounted) break; path->mnt = &mounted->mnt; path->dentry = mounted->mnt.mnt_root; nd->flags |= LOOKUP_JUMPED; *seqp = read_seqcount_begin(&path->dentry->d_seq); /* * Update the inode too. We don't need to re-check the * dentry sequence number here after this d_inode read, * because a mount-point is always pinned. */ *inode = path->dentry->d_inode; } return !read_seqretry(&mount_lock, nd->m_seq) && !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT); } static int follow_dotdot_rcu(struct nameidata *nd) { struct inode *inode = nd->inode; if (!nd->root.mnt) set_root_rcu(nd); while (1) { if (path_equal(&nd->path, &nd->root)) break; if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; inode = parent->d_inode; seq = read_seqcount_begin(&parent->d_seq); if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq))) return -ECHILD; nd->path.dentry = parent; nd->seq = seq; break; } else { struct mount *mnt = real_mount(nd->path.mnt); struct mount *mparent = mnt->mnt_parent; struct dentry *mountpoint = mnt->mnt_mountpoint; struct inode *inode2 = mountpoint->d_inode; unsigned seq = read_seqcount_begin(&mountpoint->d_seq); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (&mparent->mnt == nd->path.mnt) break; /* we know that mountpoint was pinned */ nd->path.dentry = mountpoint; nd->path.mnt = &mparent->mnt; inode = inode2; nd->seq = seq; } } while (unlikely(d_mountpoint(nd->path.dentry))) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } nd->inode = inode; return 0; } /* * Follow down to the covering mount currently visible to userspace. At each * point, the filesystem owning that dentry may be queried as to whether the * caller is permitted to proceed or not. */ int follow_down(struct path *path) { unsigned managed; int ret; while (managed = ACCESS_ONCE(path->dentry->d_flags), unlikely(managed & DCACHE_MANAGED_DENTRY)) { /* Allow the filesystem to manage the transit without i_mutex * being held. * * We indicate to the filesystem if someone is trying to mount * something here. This gives autofs the chance to deny anyone * other than its daemon the right to mount on its * superstructure. * * The filesystem may sleep at this point. */ if (managed & DCACHE_MANAGE_TRANSIT) { BUG_ON(!path->dentry->d_op); BUG_ON(!path->dentry->d_op->d_manage); ret = path->dentry->d_op->d_manage( path->dentry, false); if (ret < 0) return ret == -EISDIR ? 0 : ret; } /* Transit to a mounted filesystem. */ if (managed & DCACHE_MOUNTED) { struct vfsmount *mounted = lookup_mnt(path); if (!mounted) break; dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); continue; } /* Don't handle automount points here */ break; } return 0; } EXPORT_SYMBOL(follow_down); /* * Skip to top of mountpoint pile in refwalk mode for follow_dotdot() */ static void follow_mount(struct path *path) { while (d_mountpoint(path->dentry)) { struct vfsmount *mounted = lookup_mnt(path); if (!mounted) break; dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); } } static void follow_dotdot(struct nameidata *nd) { if (!nd->root.mnt) set_root(nd); while(1) { struct dentry *old = nd->path.dentry; if (nd->path.dentry == nd->root.dentry && nd->path.mnt == nd->root.mnt) { break; } if (nd->path.dentry != nd->path.mnt->mnt_root) { /* rare case of legitimate dget_parent()... */ nd->path.dentry = dget_parent(nd->path.dentry); dput(old); break; } if (!follow_up(&nd->path)) break; } follow_mount(&nd->path); nd->inode = nd->path.dentry->d_inode; } /* * This looks up the name in dcache, possibly revalidates the old dentry and * allocates a new one if not found or not valid. In the need_lookup argument * returns whether i_op->lookup is necessary. * * dir->d_inode->i_mutex must be held */ static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir, unsigned int flags, bool *need_lookup) { struct dentry *dentry; int error; *need_lookup = false; dentry = d_lookup(dir, name); if (dentry) { if (dentry->d_flags & DCACHE_OP_REVALIDATE) { error = d_revalidate(dentry, flags); if (unlikely(error <= 0)) { if (error < 0) { dput(dentry); return ERR_PTR(error); } else { d_invalidate(dentry); dput(dentry); dentry = NULL; } } } } if (!dentry) { dentry = d_alloc(dir, name); if (unlikely(!dentry)) return ERR_PTR(-ENOMEM); *need_lookup = true; } return dentry; } /* * Call i_op->lookup on the dentry. The dentry must be negative and * unhashed. * * dir->d_inode->i_mutex must be held */ static struct dentry *lookup_real(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct dentry *old; /* Don't create child dentry for a dead directory. */ if (unlikely(IS_DEADDIR(dir))) { dput(dentry); return ERR_PTR(-ENOENT); } old = dir->i_op->lookup(dir, dentry, flags); if (unlikely(old)) { dput(dentry); dentry = old; } return dentry; } static struct dentry *__lookup_hash(struct qstr *name, struct dentry *base, unsigned int flags) { bool need_lookup; struct dentry *dentry; dentry = lookup_dcache(name, base, flags, &need_lookup); if (!need_lookup) return dentry; return lookup_real(base->d_inode, dentry, flags); } /* * It's more convoluted than I'd like it to be, but... it's still fairly * small and for now I'd prefer to have fast path as straight as possible. * It _is_ time-critical. */ static int lookup_fast(struct nameidata *nd, struct path *path, struct inode **inode, unsigned *seqp) { struct vfsmount *mnt = nd->path.mnt; struct dentry *dentry, *parent = nd->path.dentry; int need_reval = 1; int status = 1; int err; /* * Rename seqlock is not required here because in the off chance * of a false negative due to a concurrent rename, we're going to * do the non-racy lookup, below. */ if (nd->flags & LOOKUP_RCU) { unsigned seq; bool negative; dentry = __d_lookup_rcu(parent, &nd->last, &seq); if (!dentry) goto unlazy; /* * This sequence count validates that the inode matches * the dentry name information from lookup. */ *inode = d_backing_inode(dentry); negative = d_is_negative(dentry); if (read_seqcount_retry(&dentry->d_seq, seq)) return -ECHILD; if (negative) return -ENOENT; /* * This sequence count validates that the parent had no * changes while we did the lookup of the dentry above. * * The memory barrier in read_seqcount_begin of child is * enough, we can use __read_seqcount_retry here. */ if (__read_seqcount_retry(&parent->d_seq, nd->seq)) return -ECHILD; *seqp = seq; if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE)) { status = d_revalidate(dentry, nd->flags); if (unlikely(status <= 0)) { if (status != -ECHILD) need_reval = 0; goto unlazy; } } path->mnt = mnt; path->dentry = dentry; if (likely(__follow_mount_rcu(nd, path, inode, seqp))) return 0; unlazy: if (unlazy_walk(nd, dentry, seq)) return -ECHILD; } else { dentry = __d_lookup(parent, &nd->last); } if (unlikely(!dentry)) goto need_lookup; if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE) && need_reval) status = d_revalidate(dentry, nd->flags); if (unlikely(status <= 0)) { if (status < 0) { dput(dentry); return status; } d_invalidate(dentry); dput(dentry); goto need_lookup; } if (unlikely(d_is_negative(dentry))) { dput(dentry); return -ENOENT; } path->mnt = mnt; path->dentry = dentry; err = follow_managed(path, nd); if (likely(!err)) *inode = d_backing_inode(path->dentry); return err; need_lookup: return 1; } /* Fast lookup failed, do it the slow way */ static int lookup_slow(struct nameidata *nd, struct path *path) { struct dentry *dentry, *parent; parent = nd->path.dentry; BUG_ON(nd->inode != parent->d_inode); mutex_lock(&parent->d_inode->i_mutex); dentry = __lookup_hash(&nd->last, parent, nd->flags); mutex_unlock(&parent->d_inode->i_mutex); if (IS_ERR(dentry)) return PTR_ERR(dentry); path->mnt = nd->path.mnt; path->dentry = dentry; return follow_managed(path, nd); } static inline int may_lookup(struct nameidata *nd) { if (nd->flags & LOOKUP_RCU) { int err = inode_permission(nd->inode, MAY_EXEC|MAY_NOT_BLOCK); if (err != -ECHILD) return err; if (unlazy_walk(nd, NULL, 0)) return -ECHILD; } return inode_permission(nd->inode, MAY_EXEC); } static inline int handle_dots(struct nameidata *nd, int type) { if (type == LAST_DOTDOT) { if (nd->flags & LOOKUP_RCU) { return follow_dotdot_rcu(nd); } else follow_dotdot(nd); } return 0; } static int pick_link(struct nameidata *nd, struct path *link, struct inode *inode, unsigned seq) { int error; struct saved *last; if (unlikely(nd->total_link_count++ >= MAXSYMLINKS)) { path_to_nameidata(link, nd); return -ELOOP; } if (!(nd->flags & LOOKUP_RCU)) { if (link->mnt == nd->path.mnt) mntget(link->mnt); } error = nd_alloc_stack(nd); if (unlikely(error)) { if (error == -ECHILD) { if (unlikely(unlazy_link(nd, link, seq))) return -ECHILD; error = nd_alloc_stack(nd); } if (error) { path_put(link); return error; } } last = nd->stack + nd->depth++; last->link = *link; last->cookie = NULL; last->inode = inode; last->seq = seq; return 1; } /* * Do we need to follow links? We _really_ want to be able * to do this check without having to look at inode->i_op, * so we keep a cache of "no, this doesn't need follow_link" * for the common case. */ static inline int should_follow_link(struct nameidata *nd, struct path *link, int follow, struct inode *inode, unsigned seq) { if (likely(!d_is_symlink(link->dentry))) return 0; if (!follow) return 0; return pick_link(nd, link, inode, seq); } enum {WALK_GET = 1, WALK_PUT = 2}; static int walk_component(struct nameidata *nd, int flags) { struct path path; struct inode *inode; unsigned seq; int err; /* * "." and ".." are special - ".." especially so because it has * to be able to know about the current root directory and * parent relationships. */ if (unlikely(nd->last_type != LAST_NORM)) { err = handle_dots(nd, nd->last_type); if (flags & WALK_PUT) put_link(nd); return err; } err = lookup_fast(nd, &path, &inode, &seq); if (unlikely(err)) { if (err < 0) return err; err = lookup_slow(nd, &path); if (err < 0) return err; inode = d_backing_inode(path.dentry); seq = 0; /* we are already out of RCU mode */ err = -ENOENT; if (d_is_negative(path.dentry)) goto out_path_put; } if (flags & WALK_PUT) put_link(nd); err = should_follow_link(nd, &path, flags & WALK_GET, inode, seq); if (unlikely(err)) return err; path_to_nameidata(&path, nd); nd->inode = inode; nd->seq = seq; return 0; out_path_put: path_to_nameidata(&path, nd); return err; } /* * We can do the critical dentry name comparison and hashing * operations one word at a time, but we are limited to: * * - Architectures with fast unaligned word accesses. We could * do a "get_unaligned()" if this helps and is sufficiently * fast. * * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we * do not trap on the (extremely unlikely) case of a page * crossing operation. * * - Furthermore, we need an efficient 64-bit compile for the * 64-bit case in order to generate the "number of bytes in * the final mask". Again, that could be replaced with a * efficient population count instruction or similar. */ #ifdef CONFIG_DCACHE_WORD_ACCESS #include <asm/word-at-a-time.h> #ifdef CONFIG_64BIT static inline unsigned int fold_hash(unsigned long hash) { return hash_64(hash, 32); } #else /* 32-bit case */ #define fold_hash(x) (x) #endif unsigned int full_name_hash(const unsigned char *name, unsigned int len) { unsigned long a, mask; unsigned long hash = 0; for (;;) { a = load_unaligned_zeropad(name); if (len < sizeof(unsigned long)) break; hash += a; hash *= 9; name += sizeof(unsigned long); len -= sizeof(unsigned long); if (!len) goto done; } mask = bytemask_from_count(len); hash += mask & a; done: return fold_hash(hash); } EXPORT_SYMBOL(full_name_hash); /* * Calculate the length and hash of the path component, and * return the "hash_len" as the result. */ static inline u64 hash_name(const char *name) { unsigned long a, b, adata, bdata, mask, hash, len; const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS; hash = a = 0; len = -sizeof(unsigned long); do { hash = (hash + a) * 9; len += sizeof(unsigned long); a = load_unaligned_zeropad(name+len); b = a ^ REPEAT_BYTE('/'); } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants))); adata = prep_zero_mask(a, adata, &constants); bdata = prep_zero_mask(b, bdata, &constants); mask = create_zero_mask(adata | bdata); hash += a & zero_bytemask(mask); len += find_zero(mask); return hashlen_create(fold_hash(hash), len); } #else unsigned int full_name_hash(const unsigned char *name, unsigned int len) { unsigned long hash = init_name_hash(); while (len--) hash = partial_name_hash(*name++, hash); return end_name_hash(hash); } EXPORT_SYMBOL(full_name_hash); /* * We know there's a real path component here of at least * one character. */ static inline u64 hash_name(const char *name) { unsigned long hash = init_name_hash(); unsigned long len = 0, c; c = (unsigned char)*name; do { len++; hash = partial_name_hash(c, hash); c = (unsigned char)name[len]; } while (c && c != '/'); return hashlen_create(end_name_hash(hash), len); } #endif /* * Name resolution. * This is the basic name resolution function, turning a pathname into * the final dentry. We expect 'base' to be positive and a directory. * * Returns 0 and nd will have valid dentry and mnt on success. * Returns error and drops reference to input namei data on failure. */ static int link_path_walk(const char *name, struct nameidata *nd) { int err; while (*name=='/') name++; if (!*name) return 0; /* At this point we know we have a real path component. */ for(;;) { u64 hash_len; int type; err = may_lookup(nd); if (err) return err; hash_len = hash_name(name); type = LAST_NORM; if (name[0] == '.') switch (hashlen_len(hash_len)) { case 2: if (name[1] == '.') { type = LAST_DOTDOT; nd->flags |= LOOKUP_JUMPED; } break; case 1: type = LAST_DOT; } if (likely(type == LAST_NORM)) { struct dentry *parent = nd->path.dentry; nd->flags &= ~LOOKUP_JUMPED; if (unlikely(parent->d_flags & DCACHE_OP_HASH)) { struct qstr this = { { .hash_len = hash_len }, .name = name }; err = parent->d_op->d_hash(parent, &this); if (err < 0) return err; hash_len = this.hash_len; name = this.name; } } nd->last.hash_len = hash_len; nd->last.name = name; nd->last_type = type; name += hashlen_len(hash_len); if (!*name) goto OK; /* * If it wasn't NUL, we know it was '/'. Skip that * slash, and continue until no more slashes. */ do { name++; } while (unlikely(*name == '/')); if (unlikely(!*name)) { OK: /* pathname body, done */ if (!nd->depth) return 0; name = nd->stack[nd->depth - 1].name; /* trailing symlink, done */ if (!name) return 0; /* last component of nested symlink */ err = walk_component(nd, WALK_GET | WALK_PUT); } else { err = walk_component(nd, WALK_GET); } if (err < 0) return err; if (err) { const char *s = get_link(nd); if (unlikely(IS_ERR(s))) return PTR_ERR(s); err = 0; if (unlikely(!s)) { /* jumped */ put_link(nd); } else { nd->stack[nd->depth - 1].name = name; name = s; continue; } } if (unlikely(!d_can_lookup(nd->path.dentry))) { if (nd->flags & LOOKUP_RCU) { if (unlazy_walk(nd, NULL, 0)) return -ECHILD; } return -ENOTDIR; } } } static const char *path_init(struct nameidata *nd, unsigned flags) { int retval = 0; const char *s = nd->name->name; nd->last_type = LAST_ROOT; /* if there are only slashes... */ nd->flags = flags | LOOKUP_JUMPED | LOOKUP_PARENT; nd->depth = 0; nd->total_link_count = 0; if (flags & LOOKUP_ROOT) { struct dentry *root = nd->root.dentry; struct inode *inode = root->d_inode; if (*s) { if (!d_can_lookup(root)) return ERR_PTR(-ENOTDIR); retval = inode_permission(inode, MAY_EXEC); if (retval) return ERR_PTR(retval); } nd->path = nd->root; nd->inode = inode; if (flags & LOOKUP_RCU) { rcu_read_lock(); nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); nd->root_seq = nd->seq; nd->m_seq = read_seqbegin(&mount_lock); } else { path_get(&nd->path); } return s; } nd->root.mnt = NULL; nd->m_seq = read_seqbegin(&mount_lock); if (*s == '/') { if (flags & LOOKUP_RCU) { rcu_read_lock(); set_root_rcu(nd); nd->seq = nd->root_seq; } else { set_root(nd); path_get(&nd->root); } nd->path = nd->root; } else if (nd->dfd == AT_FDCWD) { if (flags & LOOKUP_RCU) { struct fs_struct *fs = current->fs; unsigned seq; rcu_read_lock(); do { seq = read_seqcount_begin(&fs->seq); nd->path = fs->pwd; nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); } while (read_seqcount_retry(&fs->seq, seq)); } else { get_fs_pwd(current->fs, &nd->path); } } else { /* Caller must check execute permissions on the starting path component */ struct fd f = fdget_raw(nd->dfd); struct dentry *dentry; if (!f.file) return ERR_PTR(-EBADF); dentry = f.file->f_path.dentry; if (*s) { if (!d_can_lookup(dentry)) { fdput(f); return ERR_PTR(-ENOTDIR); } } nd->path = f.file->f_path; if (flags & LOOKUP_RCU) { rcu_read_lock(); nd->inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } else { path_get(&nd->path); nd->inode = nd->path.dentry->d_inode; } fdput(f); return s; } nd->inode = nd->path.dentry->d_inode; if (!(flags & LOOKUP_RCU)) return s; if (likely(!read_seqcount_retry(&nd->path.dentry->d_seq, nd->seq))) return s; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); return ERR_PTR(-ECHILD); } static const char *trailing_symlink(struct nameidata *nd) { const char *s; int error = may_follow_link(nd); if (unlikely(error)) return ERR_PTR(error); nd->flags |= LOOKUP_PARENT; nd->stack[0].name = NULL; s = get_link(nd); return s ? s : ""; } static inline int lookup_last(struct nameidata *nd) { if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; nd->flags &= ~LOOKUP_PARENT; return walk_component(nd, nd->flags & LOOKUP_FOLLOW ? nd->depth ? WALK_PUT | WALK_GET : WALK_GET : 0); } /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */ static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path) { const char *s = path_init(nd, flags); int err; if (IS_ERR(s)) return PTR_ERR(s); while (!(err = link_path_walk(s, nd)) && ((err = lookup_last(nd)) > 0)) { s = trailing_symlink(nd); if (IS_ERR(s)) { err = PTR_ERR(s); break; } } if (!err) err = complete_walk(nd); if (!err && nd->flags & LOOKUP_DIRECTORY) if (!d_can_lookup(nd->path.dentry)) err = -ENOTDIR; if (!err) { *path = nd->path; nd->path.mnt = NULL; nd->path.dentry = NULL; } terminate_walk(nd); return err; } static int filename_lookup(int dfd, struct filename *name, unsigned flags, struct path *path, struct path *root) { int retval; struct nameidata nd; if (IS_ERR(name)) return PTR_ERR(name); if (unlikely(root)) { nd.root = *root; flags |= LOOKUP_ROOT; } set_nameidata(&nd, dfd, name); retval = path_lookupat(&nd, flags | LOOKUP_RCU, path); if (unlikely(retval == -ECHILD)) retval = path_lookupat(&nd, flags, path); if (unlikely(retval == -ESTALE)) retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path); if (likely(!retval)) audit_inode(name, path->dentry, flags & LOOKUP_PARENT); restore_nameidata(); putname(name); return retval; } /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */ static int path_parentat(struct nameidata *nd, unsigned flags, struct path *parent) { const char *s = path_init(nd, flags); int err; if (IS_ERR(s)) return PTR_ERR(s); err = link_path_walk(s, nd); if (!err) err = complete_walk(nd); if (!err) { *parent = nd->path; nd->path.mnt = NULL; nd->path.dentry = NULL; } terminate_walk(nd); return err; } static struct filename *filename_parentat(int dfd, struct filename *name, unsigned int flags, struct path *parent, struct qstr *last, int *type) { int retval; struct nameidata nd; if (IS_ERR(name)) return name; set_nameidata(&nd, dfd, name); retval = path_parentat(&nd, flags | LOOKUP_RCU, parent); if (unlikely(retval == -ECHILD)) retval = path_parentat(&nd, flags, parent); if (unlikely(retval == -ESTALE)) retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent); if (likely(!retval)) { *last = nd.last; *type = nd.last_type; audit_inode(name, parent->dentry, LOOKUP_PARENT); } else { putname(name); name = ERR_PTR(retval); } restore_nameidata(); return name; } /* does lookup, returns the object with parent locked */ struct dentry *kern_path_locked(const char *name, struct path *path) { struct filename *filename; struct dentry *d; struct qstr last; int type; filename = filename_parentat(AT_FDCWD, getname_kernel(name), 0, path, &last, &type); if (IS_ERR(filename)) return ERR_CAST(filename); if (unlikely(type != LAST_NORM)) { path_put(path); putname(filename); return ERR_PTR(-EINVAL); } mutex_lock_nested(&path->dentry->d_inode->i_mutex, I_MUTEX_PARENT); d = __lookup_hash(&last, path->dentry, 0); if (IS_ERR(d)) { mutex_unlock(&path->dentry->d_inode->i_mutex); path_put(path); } putname(filename); return d; } int kern_path(const char *name, unsigned int flags, struct path *path) { return filename_lookup(AT_FDCWD, getname_kernel(name), flags, path, NULL); } EXPORT_SYMBOL(kern_path); /** * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair * @dentry: pointer to dentry of the base directory * @mnt: pointer to vfs mount of the base directory * @name: pointer to file name * @flags: lookup flags * @path: pointer to struct path to fill */ int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt, const char *name, unsigned int flags, struct path *path) { struct path root = {.mnt = mnt, .dentry = dentry}; /* the first argument of filename_lookup() is ignored with root */ return filename_lookup(AT_FDCWD, getname_kernel(name), flags , path, &root); } EXPORT_SYMBOL(vfs_path_lookup); /** * lookup_one_len - filesystem helper to lookup single pathname component * @name: pathname component to lookup * @base: base directory to lookup from * @len: maximum length @len should be interpreted to * * Note that this routine is purely a helper for filesystem usage and should * not be called by generic code. */ struct dentry *lookup_one_len(const char *name, struct dentry *base, int len) { struct qstr this; unsigned int c; int err; WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex)); this.name = name; this.len = len; this.hash = full_name_hash(name, len); if (!len) return ERR_PTR(-EACCES); if (unlikely(name[0] == '.')) { if (len < 2 || (len == 2 && name[1] == '.')) return ERR_PTR(-EACCES); } while (len--) { c = *(const unsigned char *)name++; if (c == '/' || c == '\0') return ERR_PTR(-EACCES); } /* * See if the low-level filesystem might want * to use its own hash.. */ if (base->d_flags & DCACHE_OP_HASH) { int err = base->d_op->d_hash(base, &this); if (err < 0) return ERR_PTR(err); } err = inode_permission(base->d_inode, MAY_EXEC); if (err) return ERR_PTR(err); return __lookup_hash(&this, base, 0); } EXPORT_SYMBOL(lookup_one_len); int user_path_at_empty(int dfd, const char __user *name, unsigned flags, struct path *path, int *empty) { return filename_lookup(dfd, getname_flags(name, flags, empty), flags, path, NULL); } EXPORT_SYMBOL(user_path_at_empty); /* * NB: most callers don't do anything directly with the reference to the * to struct filename, but the nd->last pointer points into the name string * allocated by getname. So we must hold the reference to it until all * path-walking is complete. */ static inline struct filename * user_path_parent(int dfd, const char __user *path, struct path *parent, struct qstr *last, int *type, unsigned int flags) { /* only LOOKUP_REVAL is allowed in extra flags */ return filename_parentat(dfd, getname(path), flags & LOOKUP_REVAL, parent, last, type); } /** * mountpoint_last - look up last component for umount * @nd: pathwalk nameidata - currently pointing at parent directory of "last" * @path: pointer to container for result * * This is a special lookup_last function just for umount. In this case, we * need to resolve the path without doing any revalidation. * * The nameidata should be the result of doing a LOOKUP_PARENT pathwalk. Since * mountpoints are always pinned in the dcache, their ancestors are too. Thus, * in almost all cases, this lookup will be served out of the dcache. The only * cases where it won't are if nd->last refers to a symlink or the path is * bogus and it doesn't exist. * * Returns: * -error: if there was an error during lookup. This includes -ENOENT if the * lookup found a negative dentry. The nd->path reference will also be * put in this case. * * 0: if we successfully resolved nd->path and found it to not to be a * symlink that needs to be followed. "path" will also be populated. * The nd->path reference will also be put. * * 1: if we successfully resolved nd->last and found it to be a symlink * that needs to be followed. "path" will be populated with the path * to the link, and nd->path will *not* be put. */ static int mountpoint_last(struct nameidata *nd, struct path *path) { int error = 0; struct dentry *dentry; struct dentry *dir = nd->path.dentry; /* If we're in rcuwalk, drop out of it to handle last component */ if (nd->flags & LOOKUP_RCU) { if (unlazy_walk(nd, NULL, 0)) return -ECHILD; } nd->flags &= ~LOOKUP_PARENT; if (unlikely(nd->last_type != LAST_NORM)) { error = handle_dots(nd, nd->last_type); if (error) return error; dentry = dget(nd->path.dentry); goto done; } mutex_lock(&dir->d_inode->i_mutex); dentry = d_lookup(dir, &nd->last); if (!dentry) { /* * No cached dentry. Mounted dentries are pinned in the cache, * so that means that this dentry is probably a symlink or the * path doesn't actually point to a mounted dentry. */ dentry = d_alloc(dir, &nd->last); if (!dentry) { mutex_unlock(&dir->d_inode->i_mutex); return -ENOMEM; } dentry = lookup_real(dir->d_inode, dentry, nd->flags); if (IS_ERR(dentry)) { mutex_unlock(&dir->d_inode->i_mutex); return PTR_ERR(dentry); } } mutex_unlock(&dir->d_inode->i_mutex); done: if (d_is_negative(dentry)) { dput(dentry); return -ENOENT; } if (nd->depth) put_link(nd); path->dentry = dentry; path->mnt = nd->path.mnt; error = should_follow_link(nd, path, nd->flags & LOOKUP_FOLLOW, d_backing_inode(dentry), 0); if (unlikely(error)) return error; mntget(path->mnt); follow_mount(path); return 0; } /** * path_mountpoint - look up a path to be umounted * @nameidata: lookup context * @flags: lookup flags * @path: pointer to container for result * * Look up the given name, but don't attempt to revalidate the last component. * Returns 0 and "path" will be valid on success; Returns error otherwise. */ static int path_mountpoint(struct nameidata *nd, unsigned flags, struct path *path) { const char *s = path_init(nd, flags); int err; if (IS_ERR(s)) return PTR_ERR(s); while (!(err = link_path_walk(s, nd)) && (err = mountpoint_last(nd, path)) > 0) { s = trailing_symlink(nd); if (IS_ERR(s)) { err = PTR_ERR(s); break; } } terminate_walk(nd); return err; } static int filename_mountpoint(int dfd, struct filename *name, struct path *path, unsigned int flags) { struct nameidata nd; int error; if (IS_ERR(name)) return PTR_ERR(name); set_nameidata(&nd, dfd, name); error = path_mountpoint(&nd, flags | LOOKUP_RCU, path); if (unlikely(error == -ECHILD)) error = path_mountpoint(&nd, flags, path); if (unlikely(error == -ESTALE)) error = path_mountpoint(&nd, flags | LOOKUP_REVAL, path); if (likely(!error)) audit_inode(name, path->dentry, 0); restore_nameidata(); putname(name); return error; } /** * user_path_mountpoint_at - lookup a path from userland in order to umount it * @dfd: directory file descriptor * @name: pathname from userland * @flags: lookup flags * @path: pointer to container to hold result * * A umount is a special case for path walking. We're not actually interested * in the inode in this situation, and ESTALE errors can be a problem. We * simply want track down the dentry and vfsmount attached at the mountpoint * and avoid revalidating the last component. * * Returns 0 and populates "path" on success. */ int user_path_mountpoint_at(int dfd, const char __user *name, unsigned int flags, struct path *path) { return filename_mountpoint(dfd, getname(name), path, flags); } int kern_path_mountpoint(int dfd, const char *name, struct path *path, unsigned int flags) { return filename_mountpoint(dfd, getname_kernel(name), path, flags); } EXPORT_SYMBOL(kern_path_mountpoint); int __check_sticky(struct inode *dir, struct inode *inode) { kuid_t fsuid = current_fsuid(); if (uid_eq(inode->i_uid, fsuid)) return 0; if (uid_eq(dir->i_uid, fsuid)) return 0; return !capable_wrt_inode_uidgid(inode, CAP_FOWNER); } EXPORT_SYMBOL(__check_sticky); /* * Check whether we can remove a link victim from directory dir, check * whether the type of victim is right. * 1. We can't do it if dir is read-only (done in permission()) * 2. We should have write and exec permissions on dir * 3. We can't remove anything from append-only dir * 4. We can't do anything with immutable dir (done in permission()) * 5. If the sticky bit on dir is set we should either * a. be owner of dir, or * b. be owner of victim, or * c. have CAP_FOWNER capability * 6. If the victim is append-only or immutable we can't do antyhing with * links pointing to it. * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR. * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR. * 9. We can't remove a root or mountpoint. * 10. We don't allow removal of NFS sillyrenamed files; it's handled by * nfs_async_unlink(). */ static int may_delete(struct inode *dir, struct dentry *victim, bool isdir) { struct inode *inode = d_backing_inode(victim); int error; if (d_is_negative(victim)) return -ENOENT; BUG_ON(!inode); BUG_ON(victim->d_parent->d_inode != dir); audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE); error = inode_permission(dir, MAY_WRITE | MAY_EXEC); if (error) return error; if (IS_APPEND(dir)) return -EPERM; if (check_sticky(dir, inode) || IS_APPEND(inode) || IS_IMMUTABLE(inode) || IS_SWAPFILE(inode)) return -EPERM; if (isdir) { if (!d_is_dir(victim)) return -ENOTDIR; if (IS_ROOT(victim)) return -EBUSY; } else if (d_is_dir(victim)) return -EISDIR; if (IS_DEADDIR(dir)) return -ENOENT; if (victim->d_flags & DCACHE_NFSFS_RENAMED) return -EBUSY; return 0; } /* Check whether we can create an object with dentry child in directory * dir. * 1. We can't do it if child already exists (open has special treatment for * this case, but since we are inlined it's OK) * 2. We can't do it if dir is read-only (done in permission()) * 3. We should have write and exec permissions on dir * 4. We can't do it if dir is immutable (done in permission()) */ static inline int may_create(struct inode *dir, struct dentry *child) { audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE); if (child->d_inode) return -EEXIST; if (IS_DEADDIR(dir)) return -ENOENT; return inode_permission(dir, MAY_WRITE | MAY_EXEC); } /* * p1 and p2 should be directories on the same fs. */ struct dentry *lock_rename(struct dentry *p1, struct dentry *p2) { struct dentry *p; if (p1 == p2) { mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); return NULL; } mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex); p = d_ancestor(p2, p1); if (p) { mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD); return p; } p = d_ancestor(p1, p2); if (p) { mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD); return p; } mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT2); return NULL; } EXPORT_SYMBOL(lock_rename); void unlock_rename(struct dentry *p1, struct dentry *p2) { mutex_unlock(&p1->d_inode->i_mutex); if (p1 != p2) { mutex_unlock(&p2->d_inode->i_mutex); mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex); } } EXPORT_SYMBOL(unlock_rename); int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool want_excl) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->create) return -EACCES; /* shouldn't it be ENOSYS? */ mode &= S_IALLUGO; mode |= S_IFREG; error = security_inode_create(dir, dentry, mode); if (error) return error; error = dir->i_op->create(dir, dentry, mode, want_excl); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_create); static int may_open(struct path *path, int acc_mode, int flag) { struct dentry *dentry = path->dentry; struct inode *inode = dentry->d_inode; int error; /* O_PATH? */ if (!acc_mode) return 0; if (!inode) return -ENOENT; switch (inode->i_mode & S_IFMT) { case S_IFLNK: return -ELOOP; case S_IFDIR: if (acc_mode & MAY_WRITE) return -EISDIR; break; case S_IFBLK: case S_IFCHR: if (path->mnt->mnt_flags & MNT_NODEV) return -EACCES; /*FALLTHRU*/ case S_IFIFO: case S_IFSOCK: flag &= ~O_TRUNC; break; } error = inode_permission(inode, acc_mode); if (error) return error; /* * An append-only file must be opened in append mode for writing. */ if (IS_APPEND(inode)) { if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND)) return -EPERM; if (flag & O_TRUNC) return -EPERM; } /* O_NOATIME can only be set by the owner or superuser */ if (flag & O_NOATIME && !inode_owner_or_capable(inode)) return -EPERM; return 0; } static int handle_truncate(struct file *filp) { struct path *path = &filp->f_path; struct inode *inode = path->dentry->d_inode; int error = get_write_access(inode); if (error) return error; /* * Refuse to truncate files with mandatory locks held on them. */ error = locks_verify_locked(filp); if (!error) error = security_path_truncate(path); if (!error) { error = do_truncate(path->dentry, 0, ATTR_MTIME|ATTR_CTIME|ATTR_OPEN, filp); } put_write_access(inode); return error; } static inline int open_to_namei_flags(int flag) { if ((flag & O_ACCMODE) == 3) flag--; return flag; } static int may_o_create(struct path *dir, struct dentry *dentry, umode_t mode) { int error = security_path_mknod(dir, dentry, mode, 0); if (error) return error; error = inode_permission(dir->dentry->d_inode, MAY_WRITE | MAY_EXEC); if (error) return error; return security_inode_create(dir->dentry->d_inode, dentry, mode); } /* * Attempt to atomically look up, create and open a file from a negative * dentry. * * Returns 0 if successful. The file will have been created and attached to * @file by the filesystem calling finish_open(). * * Returns 1 if the file was looked up only or didn't need creating. The * caller will need to perform the open themselves. @path will have been * updated to point to the new dentry. This may be negative. * * Returns an error code otherwise. */ static int atomic_open(struct nameidata *nd, struct dentry *dentry, struct path *path, struct file *file, const struct open_flags *op, bool got_write, bool need_lookup, int *opened) { struct inode *dir = nd->path.dentry->d_inode; unsigned open_flag = open_to_namei_flags(op->open_flag); umode_t mode; int error; int acc_mode; int create_error = 0; struct dentry *const DENTRY_NOT_SET = (void *) -1UL; bool excl; BUG_ON(dentry->d_inode); /* Don't create child dentry for a dead directory. */ if (unlikely(IS_DEADDIR(dir))) { error = -ENOENT; goto out; } mode = op->mode; if ((open_flag & O_CREAT) && !IS_POSIXACL(dir)) mode &= ~current_umask(); excl = (open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT); if (excl) open_flag &= ~O_TRUNC; /* * Checking write permission is tricky, bacuse we don't know if we are * going to actually need it: O_CREAT opens should work as long as the * file exists. But checking existence breaks atomicity. The trick is * to check access and if not granted clear O_CREAT from the flags. * * Another problem is returing the "right" error value (e.g. for an * O_EXCL open we want to return EEXIST not EROFS). */ if (((open_flag & (O_CREAT | O_TRUNC)) || (open_flag & O_ACCMODE) != O_RDONLY) && unlikely(!got_write)) { if (!(open_flag & O_CREAT)) { /* * No O_CREATE -> atomicity not a requirement -> fall * back to lookup + open */ goto no_open; } else if (open_flag & (O_EXCL | O_TRUNC)) { /* Fall back and fail with the right error */ create_error = -EROFS; goto no_open; } else { /* No side effects, safe to clear O_CREAT */ create_error = -EROFS; open_flag &= ~O_CREAT; } } if (open_flag & O_CREAT) { error = may_o_create(&nd->path, dentry, mode); if (error) { create_error = error; if (open_flag & O_EXCL) goto no_open; open_flag &= ~O_CREAT; } } if (nd->flags & LOOKUP_DIRECTORY) open_flag |= O_DIRECTORY; file->f_path.dentry = DENTRY_NOT_SET; file->f_path.mnt = nd->path.mnt; error = dir->i_op->atomic_open(dir, dentry, file, open_flag, mode, opened); if (error < 0) { if (create_error && error == -ENOENT) error = create_error; goto out; } if (error) { /* returned 1, that is */ if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) { error = -EIO; goto out; } if (file->f_path.dentry) { dput(dentry); dentry = file->f_path.dentry; } if (*opened & FILE_CREATED) fsnotify_create(dir, dentry); if (!dentry->d_inode) { WARN_ON(*opened & FILE_CREATED); if (create_error) { error = create_error; goto out; } } else { if (excl && !(*opened & FILE_CREATED)) { error = -EEXIST; goto out; } } goto looked_up; } /* * We didn't have the inode before the open, so check open permission * here. */ acc_mode = op->acc_mode; if (*opened & FILE_CREATED) { WARN_ON(!(open_flag & O_CREAT)); fsnotify_create(dir, dentry); acc_mode = MAY_OPEN; } error = may_open(&file->f_path, acc_mode, open_flag); if (error) fput(file); out: dput(dentry); return error; no_open: if (need_lookup) { dentry = lookup_real(dir, dentry, nd->flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (create_error) { int open_flag = op->open_flag; error = create_error; if ((open_flag & O_EXCL)) { if (!dentry->d_inode) goto out; } else if (!dentry->d_inode) { goto out; } else if ((open_flag & O_TRUNC) && d_is_reg(dentry)) { goto out; } /* will fail later, go on to get the right error */ } } looked_up: path->dentry = dentry; path->mnt = nd->path.mnt; return 1; } /* * Look up and maybe create and open the last component. * * Must be called with i_mutex held on parent. * * Returns 0 if the file was successfully atomically created (if necessary) and * opened. In this case the file will be returned attached to @file. * * Returns 1 if the file was not completely opened at this time, though lookups * and creations will have been performed and the dentry returned in @path will * be positive upon return if O_CREAT was specified. If O_CREAT wasn't * specified then a negative dentry may be returned. * * An error code is returned otherwise. * * FILE_CREATE will be set in @*opened if the dentry was created and will be * cleared otherwise prior to returning. */ static int lookup_open(struct nameidata *nd, struct path *path, struct file *file, const struct open_flags *op, bool got_write, int *opened) { struct dentry *dir = nd->path.dentry; struct inode *dir_inode = dir->d_inode; struct dentry *dentry; int error; bool need_lookup; *opened &= ~FILE_CREATED; dentry = lookup_dcache(&nd->last, dir, nd->flags, &need_lookup); if (IS_ERR(dentry)) return PTR_ERR(dentry); /* Cached positive dentry: will open in f_op->open */ if (!need_lookup && dentry->d_inode) goto out_no_open; if ((nd->flags & LOOKUP_OPEN) && dir_inode->i_op->atomic_open) { return atomic_open(nd, dentry, path, file, op, got_write, need_lookup, opened); } if (need_lookup) { BUG_ON(dentry->d_inode); dentry = lookup_real(dir_inode, dentry, nd->flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); } /* Negative dentry, just create the file */ if (!dentry->d_inode && (op->open_flag & O_CREAT)) { umode_t mode = op->mode; if (!IS_POSIXACL(dir->d_inode)) mode &= ~current_umask(); /* * This write is needed to ensure that a * rw->ro transition does not occur between * the time when the file is created and when * a permanent write count is taken through * the 'struct file' in finish_open(). */ if (!got_write) { error = -EROFS; goto out_dput; } *opened |= FILE_CREATED; error = security_path_mknod(&nd->path, dentry, mode, 0); if (error) goto out_dput; error = vfs_create(dir->d_inode, dentry, mode, nd->flags & LOOKUP_EXCL); if (error) goto out_dput; } out_no_open: path->dentry = dentry; path->mnt = nd->path.mnt; return 1; out_dput: dput(dentry); return error; } /* * Handle the last step of open() */ static int do_last(struct nameidata *nd, struct file *file, const struct open_flags *op, int *opened) { struct dentry *dir = nd->path.dentry; int open_flag = op->open_flag; bool will_truncate = (open_flag & O_TRUNC) != 0; bool got_write = false; int acc_mode = op->acc_mode; unsigned seq; struct inode *inode; struct path save_parent = { .dentry = NULL, .mnt = NULL }; struct path path; bool retried = false; int error; nd->flags &= ~LOOKUP_PARENT; nd->flags |= op->intent; if (nd->last_type != LAST_NORM) { error = handle_dots(nd, nd->last_type); if (unlikely(error)) return error; goto finish_open; } if (!(open_flag & O_CREAT)) { if (nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; /* we _can_ be in RCU mode here */ error = lookup_fast(nd, &path, &inode, &seq); if (likely(!error)) goto finish_lookup; if (error < 0) return error; BUG_ON(nd->inode != dir->d_inode); } else { /* create side of things */ /* * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED * has been cleared when we got to the last component we are * about to look up */ error = complete_walk(nd); if (error) return error; audit_inode(nd->name, dir, LOOKUP_PARENT); /* trailing slashes? */ if (unlikely(nd->last.name[nd->last.len])) return -EISDIR; } retry_lookup: if (op->open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) { error = mnt_want_write(nd->path.mnt); if (!error) got_write = true; /* * do _not_ fail yet - we might not need that or fail with * a different error; let lookup_open() decide; we'll be * dropping this one anyway. */ } mutex_lock(&dir->d_inode->i_mutex); error = lookup_open(nd, &path, file, op, got_write, opened); mutex_unlock(&dir->d_inode->i_mutex); if (error <= 0) { if (error) goto out; if ((*opened & FILE_CREATED) || !S_ISREG(file_inode(file)->i_mode)) will_truncate = false; audit_inode(nd->name, file->f_path.dentry, 0); goto opened; } if (*opened & FILE_CREATED) { /* Don't check for write permission, don't truncate */ open_flag &= ~O_TRUNC; will_truncate = false; acc_mode = MAY_OPEN; path_to_nameidata(&path, nd); goto finish_open_created; } /* * create/update audit record if it already exists. */ if (d_is_positive(path.dentry)) audit_inode(nd->name, path.dentry, 0); /* * If atomic_open() acquired write access it is dropped now due to * possible mount and symlink following (this might be optimized away if * necessary...) */ if (got_write) { mnt_drop_write(nd->path.mnt); got_write = false; } if (unlikely((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT))) { path_to_nameidata(&path, nd); return -EEXIST; } error = follow_managed(&path, nd); if (unlikely(error < 0)) return error; BUG_ON(nd->flags & LOOKUP_RCU); inode = d_backing_inode(path.dentry); seq = 0; /* out of RCU mode, so the value doesn't matter */ if (unlikely(d_is_negative(path.dentry))) { path_to_nameidata(&path, nd); return -ENOENT; } finish_lookup: if (nd->depth) put_link(nd); error = should_follow_link(nd, &path, nd->flags & LOOKUP_FOLLOW, inode, seq); if (unlikely(error)) return error; if (unlikely(d_is_symlink(path.dentry)) && !(open_flag & O_PATH)) { path_to_nameidata(&path, nd); return -ELOOP; } if ((nd->flags & LOOKUP_RCU) || nd->path.mnt != path.mnt) { path_to_nameidata(&path, nd); } else { save_parent.dentry = nd->path.dentry; save_parent.mnt = mntget(path.mnt); nd->path.dentry = path.dentry; } nd->inode = inode; nd->seq = seq; /* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */ finish_open: error = complete_walk(nd); if (error) { path_put(&save_parent); return error; } audit_inode(nd->name, nd->path.dentry, 0); error = -EISDIR; if ((open_flag & O_CREAT) && d_is_dir(nd->path.dentry)) goto out; error = -ENOTDIR; if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry)) goto out; if (!d_is_reg(nd->path.dentry)) will_truncate = false; if (will_truncate) { error = mnt_want_write(nd->path.mnt); if (error) goto out; got_write = true; } finish_open_created: error = may_open(&nd->path, acc_mode, open_flag); if (error) goto out; BUG_ON(*opened & FILE_OPENED); /* once it's opened, it's opened */ error = vfs_open(&nd->path, file, current_cred()); if (!error) { *opened |= FILE_OPENED; } else { if (error == -EOPENSTALE) goto stale_open; goto out; } opened: error = open_check_o_direct(file); if (error) goto exit_fput; error = ima_file_check(file, op->acc_mode, *opened); if (error) goto exit_fput; if (will_truncate) { error = handle_truncate(file); if (error) goto exit_fput; } out: if (got_write) mnt_drop_write(nd->path.mnt); path_put(&save_parent); return error; exit_fput: fput(file); goto out; stale_open: /* If no saved parent or already retried then can't retry */ if (!save_parent.dentry || retried) goto out; BUG_ON(save_parent.dentry != dir); path_put(&nd->path); nd->path = save_parent; nd->inode = dir->d_inode; save_parent.mnt = NULL; save_parent.dentry = NULL; if (got_write) { mnt_drop_write(nd->path.mnt); got_write = false; } retried = true; goto retry_lookup; } static int do_tmpfile(struct nameidata *nd, unsigned flags, const struct open_flags *op, struct file *file, int *opened) { static const struct qstr name = QSTR_INIT("/", 1); struct dentry *child; struct inode *dir; struct path path; int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path); if (unlikely(error)) return error; error = mnt_want_write(path.mnt); if (unlikely(error)) goto out; dir = path.dentry->d_inode; /* we want directory to be writable */ error = inode_permission(dir, MAY_WRITE | MAY_EXEC); if (error) goto out2; if (!dir->i_op->tmpfile) { error = -EOPNOTSUPP; goto out2; } child = d_alloc(path.dentry, &name); if (unlikely(!child)) { error = -ENOMEM; goto out2; } dput(path.dentry); path.dentry = child; error = dir->i_op->tmpfile(dir, child, op->mode); if (error) goto out2; audit_inode(nd->name, child, 0); /* Don't check for other permissions, the inode was just created */ error = may_open(&path, MAY_OPEN, op->open_flag); if (error) goto out2; file->f_path.mnt = path.mnt; error = finish_open(file, child, NULL, opened); if (error) goto out2; error = open_check_o_direct(file); if (error) { fput(file); } else if (!(op->open_flag & O_EXCL)) { struct inode *inode = file_inode(file); spin_lock(&inode->i_lock); inode->i_state |= I_LINKABLE; spin_unlock(&inode->i_lock); } out2: mnt_drop_write(path.mnt); out: path_put(&path); return error; } static struct file *path_openat(struct nameidata *nd, const struct open_flags *op, unsigned flags) { const char *s; struct file *file; int opened = 0; int error; file = get_empty_filp(); if (IS_ERR(file)) return file; file->f_flags = op->open_flag; if (unlikely(file->f_flags & __O_TMPFILE)) { error = do_tmpfile(nd, flags, op, file, &opened); goto out2; } s = path_init(nd, flags); if (IS_ERR(s)) { put_filp(file); return ERR_CAST(s); } while (!(error = link_path_walk(s, nd)) && (error = do_last(nd, file, op, &opened)) > 0) { nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL); s = trailing_symlink(nd); if (IS_ERR(s)) { error = PTR_ERR(s); break; } } terminate_walk(nd); out2: if (!(opened & FILE_OPENED)) { BUG_ON(!error); put_filp(file); } if (unlikely(error)) { if (error == -EOPENSTALE) { if (flags & LOOKUP_RCU) error = -ECHILD; else error = -ESTALE; } file = ERR_PTR(error); } return file; } struct file *do_filp_open(int dfd, struct filename *pathname, const struct open_flags *op) { struct nameidata nd; int flags = op->lookup_flags; struct file *filp; set_nameidata(&nd, dfd, pathname); filp = path_openat(&nd, op, flags | LOOKUP_RCU); if (unlikely(filp == ERR_PTR(-ECHILD))) filp = path_openat(&nd, op, flags); if (unlikely(filp == ERR_PTR(-ESTALE))) filp = path_openat(&nd, op, flags | LOOKUP_REVAL); restore_nameidata(); return filp; } struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt, const char *name, const struct open_flags *op) { struct nameidata nd; struct file *file; struct filename *filename; int flags = op->lookup_flags | LOOKUP_ROOT; nd.root.mnt = mnt; nd.root.dentry = dentry; if (d_is_symlink(dentry) && op->intent & LOOKUP_OPEN) return ERR_PTR(-ELOOP); filename = getname_kernel(name); if (unlikely(IS_ERR(filename))) return ERR_CAST(filename); set_nameidata(&nd, -1, filename); file = path_openat(&nd, op, flags | LOOKUP_RCU); if (unlikely(file == ERR_PTR(-ECHILD))) file = path_openat(&nd, op, flags); if (unlikely(file == ERR_PTR(-ESTALE))) file = path_openat(&nd, op, flags | LOOKUP_REVAL); restore_nameidata(); putname(filename); return file; } static struct dentry *filename_create(int dfd, struct filename *name, struct path *path, unsigned int lookup_flags) { struct dentry *dentry = ERR_PTR(-EEXIST); struct qstr last; int type; int err2; int error; bool is_dir = (lookup_flags & LOOKUP_DIRECTORY); /* * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any * other flags passed in are ignored! */ lookup_flags &= LOOKUP_REVAL; name = filename_parentat(dfd, name, lookup_flags, path, &last, &type); if (IS_ERR(name)) return ERR_CAST(name); /* * Yucky last component or no last component at all? * (foo/., foo/.., /////) */ if (unlikely(type != LAST_NORM)) goto out; /* don't fail immediately if it's r/o, at least try to report other errors */ err2 = mnt_want_write(path->mnt); /* * Do the final lookup. */ lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL; mutex_lock_nested(&path->dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = __lookup_hash(&last, path->dentry, lookup_flags); if (IS_ERR(dentry)) goto unlock; error = -EEXIST; if (d_is_positive(dentry)) goto fail; /* * Special case - lookup gave negative, but... we had foo/bar/ * From the vfs_mknod() POV we just have a negative dentry - * all is fine. Let's be bastards - you had / on the end, you've * been asking for (non-existent) directory. -ENOENT for you. */ if (unlikely(!is_dir && last.name[last.len])) { error = -ENOENT; goto fail; } if (unlikely(err2)) { error = err2; goto fail; } putname(name); return dentry; fail: dput(dentry); dentry = ERR_PTR(error); unlock: mutex_unlock(&path->dentry->d_inode->i_mutex); if (!err2) mnt_drop_write(path->mnt); out: path_put(path); putname(name); return dentry; } struct dentry *kern_path_create(int dfd, const char *pathname, struct path *path, unsigned int lookup_flags) { return filename_create(dfd, getname_kernel(pathname), path, lookup_flags); } EXPORT_SYMBOL(kern_path_create); void done_path_create(struct path *path, struct dentry *dentry) { dput(dentry); mutex_unlock(&path->dentry->d_inode->i_mutex); mnt_drop_write(path->mnt); path_put(path); } EXPORT_SYMBOL(done_path_create); inline struct dentry *user_path_create(int dfd, const char __user *pathname, struct path *path, unsigned int lookup_flags) { return filename_create(dfd, getname(pathname), path, lookup_flags); } EXPORT_SYMBOL(user_path_create); int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev) { int error = may_create(dir, dentry); if (error) return error; if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD)) return -EPERM; if (!dir->i_op->mknod) return -EPERM; error = devcgroup_inode_mknod(mode, dev); if (error) return error; error = security_inode_mknod(dir, dentry, mode, dev); if (error) return error; error = dir->i_op->mknod(dir, dentry, mode, dev); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_mknod); static int may_mknod(umode_t mode) { switch (mode & S_IFMT) { case S_IFREG: case S_IFCHR: case S_IFBLK: case S_IFIFO: case S_IFSOCK: case 0: /* zero mode translates to S_IFREG */ return 0; case S_IFDIR: return -EPERM; default: return -EINVAL; } } SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode, unsigned, dev) { struct dentry *dentry; struct path path; int error; unsigned int lookup_flags = 0; error = may_mknod(mode); if (error) return error; retry: dentry = user_path_create(dfd, filename, &path, lookup_flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (!IS_POSIXACL(path.dentry->d_inode)) mode &= ~current_umask(); error = security_path_mknod(&path, dentry, mode, dev); if (error) goto out; switch (mode & S_IFMT) { case 0: case S_IFREG: error = vfs_create(path.dentry->d_inode,dentry,mode,true); break; case S_IFCHR: case S_IFBLK: error = vfs_mknod(path.dentry->d_inode,dentry,mode, new_decode_dev(dev)); break; case S_IFIFO: case S_IFSOCK: error = vfs_mknod(path.dentry->d_inode,dentry,mode,0); break; } out: done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev) { return sys_mknodat(AT_FDCWD, filename, mode, dev); } int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { int error = may_create(dir, dentry); unsigned max_links = dir->i_sb->s_max_links; if (error) return error; if (!dir->i_op->mkdir) return -EPERM; mode &= (S_IRWXUGO|S_ISVTX); error = security_inode_mkdir(dir, dentry, mode); if (error) return error; if (max_links && dir->i_nlink >= max_links) return -EMLINK; error = dir->i_op->mkdir(dir, dentry, mode); if (!error) fsnotify_mkdir(dir, dentry); return error; } EXPORT_SYMBOL(vfs_mkdir); SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode) { struct dentry *dentry; struct path path; int error; unsigned int lookup_flags = LOOKUP_DIRECTORY; retry: dentry = user_path_create(dfd, pathname, &path, lookup_flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (!IS_POSIXACL(path.dentry->d_inode)) mode &= ~current_umask(); error = security_path_mkdir(&path, dentry, mode); if (!error) error = vfs_mkdir(path.dentry->d_inode, dentry, mode); done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode) { return sys_mkdirat(AT_FDCWD, pathname, mode); } /* * The dentry_unhash() helper will try to drop the dentry early: we * should have a usage count of 1 if we're the only user of this * dentry, and if that is true (possibly after pruning the dcache), * then we drop the dentry now. * * A low-level filesystem can, if it choses, legally * do a * * if (!d_unhashed(dentry)) * return -EBUSY; * * if it cannot handle the case of removing a directory * that is still in use by something else.. */ void dentry_unhash(struct dentry *dentry) { shrink_dcache_parent(dentry); spin_lock(&dentry->d_lock); if (dentry->d_lockref.count == 1) __d_drop(dentry); spin_unlock(&dentry->d_lock); } EXPORT_SYMBOL(dentry_unhash); int vfs_rmdir(struct inode *dir, struct dentry *dentry) { int error = may_delete(dir, dentry, 1); if (error) return error; if (!dir->i_op->rmdir) return -EPERM; dget(dentry); mutex_lock(&dentry->d_inode->i_mutex); error = -EBUSY; if (is_local_mountpoint(dentry)) goto out; error = security_inode_rmdir(dir, dentry); if (error) goto out; shrink_dcache_parent(dentry); error = dir->i_op->rmdir(dir, dentry); if (error) goto out; dentry->d_inode->i_flags |= S_DEAD; dont_mount(dentry); detach_mounts(dentry); out: mutex_unlock(&dentry->d_inode->i_mutex); dput(dentry); if (!error) d_delete(dentry); return error; } EXPORT_SYMBOL(vfs_rmdir); static long do_rmdir(int dfd, const char __user *pathname) { int error = 0; struct filename *name; struct dentry *dentry; struct path path; struct qstr last; int type; unsigned int lookup_flags = 0; retry: name = user_path_parent(dfd, pathname, &path, &last, &type, lookup_flags); if (IS_ERR(name)) return PTR_ERR(name); switch (type) { case LAST_DOTDOT: error = -ENOTEMPTY; goto exit1; case LAST_DOT: error = -EINVAL; goto exit1; case LAST_ROOT: error = -EBUSY; goto exit1; } error = mnt_want_write(path.mnt); if (error) goto exit1; mutex_lock_nested(&path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = __lookup_hash(&last, path.dentry, lookup_flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto exit2; if (!dentry->d_inode) { error = -ENOENT; goto exit3; } error = security_path_rmdir(&path, dentry); if (error) goto exit3; error = vfs_rmdir(path.dentry->d_inode, dentry); exit3: dput(dentry); exit2: mutex_unlock(&path.dentry->d_inode->i_mutex); mnt_drop_write(path.mnt); exit1: path_put(&path); putname(name); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE1(rmdir, const char __user *, pathname) { return do_rmdir(AT_FDCWD, pathname); } /** * vfs_unlink - unlink a filesystem object * @dir: parent directory * @dentry: victim * @delegated_inode: returns victim inode, if the inode is delegated. * * The caller must hold dir->i_mutex. * * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and * return a reference to the inode in delegated_inode. The caller * should then break the delegation on that inode and retry. Because * breaking a delegation may take a long time, the caller should drop * dir->i_mutex before doing so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. */ int vfs_unlink(struct inode *dir, struct dentry *dentry, struct inode **delegated_inode) { struct inode *target = dentry->d_inode; int error = may_delete(dir, dentry, 0); if (error) return error; if (!dir->i_op->unlink) return -EPERM; mutex_lock(&target->i_mutex); if (is_local_mountpoint(dentry)) error = -EBUSY; else { error = security_inode_unlink(dir, dentry); if (!error) { error = try_break_deleg(target, delegated_inode); if (error) goto out; error = dir->i_op->unlink(dir, dentry); if (!error) { dont_mount(dentry); detach_mounts(dentry); } } } out: mutex_unlock(&target->i_mutex); /* We don't d_delete() NFS sillyrenamed files--they still exist. */ if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) { fsnotify_link_count(target); d_delete(dentry); } return error; } EXPORT_SYMBOL(vfs_unlink); /* * Make sure that the actual truncation of the file will occur outside its * directory's i_mutex. Truncate can take a long time if there is a lot of * writeout happening, and we don't want to prevent access to the directory * while waiting on the I/O. */ static long do_unlinkat(int dfd, const char __user *pathname) { int error; struct filename *name; struct dentry *dentry; struct path path; struct qstr last; int type; struct inode *inode = NULL; struct inode *delegated_inode = NULL; unsigned int lookup_flags = 0; retry: name = user_path_parent(dfd, pathname, &path, &last, &type, lookup_flags); if (IS_ERR(name)) return PTR_ERR(name); error = -EISDIR; if (type != LAST_NORM) goto exit1; error = mnt_want_write(path.mnt); if (error) goto exit1; retry_deleg: mutex_lock_nested(&path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = __lookup_hash(&last, path.dentry, lookup_flags); error = PTR_ERR(dentry); if (!IS_ERR(dentry)) { /* Why not before? Because we want correct error value */ if (last.name[last.len]) goto slashes; inode = dentry->d_inode; if (d_is_negative(dentry)) goto slashes; ihold(inode); error = security_path_unlink(&path, dentry); if (error) goto exit2; error = vfs_unlink(path.dentry->d_inode, dentry, &delegated_inode); exit2: dput(dentry); } mutex_unlock(&path.dentry->d_inode->i_mutex); if (inode) iput(inode); /* truncate the inode here */ inode = NULL; if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) goto retry_deleg; } mnt_drop_write(path.mnt); exit1: path_put(&path); putname(name); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; inode = NULL; goto retry; } return error; slashes: if (d_is_negative(dentry)) error = -ENOENT; else if (d_is_dir(dentry)) error = -EISDIR; else error = -ENOTDIR; goto exit2; } SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag) { if ((flag & ~AT_REMOVEDIR) != 0) return -EINVAL; if (flag & AT_REMOVEDIR) return do_rmdir(dfd, pathname); return do_unlinkat(dfd, pathname); } SYSCALL_DEFINE1(unlink, const char __user *, pathname) { return do_unlinkat(AT_FDCWD, pathname); } int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->symlink) return -EPERM; error = security_inode_symlink(dir, dentry, oldname); if (error) return error; error = dir->i_op->symlink(dir, dentry, oldname); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_symlink); SYSCALL_DEFINE3(symlinkat, const char __user *, oldname, int, newdfd, const char __user *, newname) { int error; struct filename *from; struct dentry *dentry; struct path path; unsigned int lookup_flags = 0; from = getname(oldname); if (IS_ERR(from)) return PTR_ERR(from); retry: dentry = user_path_create(newdfd, newname, &path, lookup_flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto out_putname; error = security_path_symlink(&path, dentry, from->name); if (!error) error = vfs_symlink(path.dentry->d_inode, dentry, from->name); done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } out_putname: putname(from); return error; } SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname) { return sys_symlinkat(oldname, AT_FDCWD, newname); } /** * vfs_link - create a new link * @old_dentry: object to be linked * @dir: new parent * @new_dentry: where to create the new link * @delegated_inode: returns inode needing a delegation break * * The caller must hold dir->i_mutex * * If vfs_link discovers a delegation on the to-be-linked file in need * of breaking, it will return -EWOULDBLOCK and return a reference to the * inode in delegated_inode. The caller should then break the delegation * and retry. Because breaking a delegation may take a long time, the * caller should drop the i_mutex before doing so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. */ int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode) { struct inode *inode = old_dentry->d_inode; unsigned max_links = dir->i_sb->s_max_links; int error; if (!inode) return -ENOENT; error = may_create(dir, new_dentry); if (error) return error; if (dir->i_sb != inode->i_sb) return -EXDEV; /* * A link to an append-only or immutable file cannot be created. */ if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) return -EPERM; if (!dir->i_op->link) return -EPERM; if (S_ISDIR(inode->i_mode)) return -EPERM; error = security_inode_link(old_dentry, dir, new_dentry); if (error) return error; mutex_lock(&inode->i_mutex); /* Make sure we don't allow creating hardlink to an unlinked file */ if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE)) error = -ENOENT; else if (max_links && inode->i_nlink >= max_links) error = -EMLINK; else { error = try_break_deleg(inode, delegated_inode); if (!error) error = dir->i_op->link(old_dentry, dir, new_dentry); } if (!error && (inode->i_state & I_LINKABLE)) { spin_lock(&inode->i_lock); inode->i_state &= ~I_LINKABLE; spin_unlock(&inode->i_lock); } mutex_unlock(&inode->i_mutex); if (!error) fsnotify_link(dir, inode, new_dentry); return error; } EXPORT_SYMBOL(vfs_link); /* * Hardlinks are often used in delicate situations. We avoid * security-related surprises by not following symlinks on the * newname. --KAB * * We don't follow them on the oldname either to be compatible * with linux 2.0, and to avoid hard-linking to directories * and other special files. --ADM */ SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname, int, flags) { struct dentry *new_dentry; struct path old_path, new_path; struct inode *delegated_inode = NULL; int how = 0; int error; if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) return -EINVAL; /* * To use null names we require CAP_DAC_READ_SEARCH * This ensures that not everyone will be able to create * handlink using the passed filedescriptor. */ if (flags & AT_EMPTY_PATH) { if (!capable(CAP_DAC_READ_SEARCH)) return -ENOENT; how = LOOKUP_EMPTY; } if (flags & AT_SYMLINK_FOLLOW) how |= LOOKUP_FOLLOW; retry: error = user_path_at(olddfd, oldname, how, &old_path); if (error) return error; new_dentry = user_path_create(newdfd, newname, &new_path, (how & LOOKUP_REVAL)); error = PTR_ERR(new_dentry); if (IS_ERR(new_dentry)) goto out; error = -EXDEV; if (old_path.mnt != new_path.mnt) goto out_dput; error = may_linkat(&old_path); if (unlikely(error)) goto out_dput; error = security_path_link(old_path.dentry, &new_path, new_dentry); if (error) goto out_dput; error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode); out_dput: done_path_create(&new_path, new_dentry); if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) { path_put(&old_path); goto retry; } } if (retry_estale(error, how)) { path_put(&old_path); how |= LOOKUP_REVAL; goto retry; } out: path_put(&old_path); return error; } SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname) { return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0); } /** * vfs_rename - rename a filesystem object * @old_dir: parent of source * @old_dentry: source * @new_dir: parent of destination * @new_dentry: destination * @delegated_inode: returns an inode needing a delegation break * @flags: rename flags * * The caller must hold multiple mutexes--see lock_rename()). * * If vfs_rename discovers a delegation in need of breaking at either * the source or destination, it will return -EWOULDBLOCK and return a * reference to the inode in delegated_inode. The caller should then * break the delegation and retry. Because breaking a delegation may * take a long time, the caller should drop all locks before doing * so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. * * The worst of all namespace operations - renaming directory. "Perverted" * doesn't even start to describe it. Somebody in UCB had a heck of a trip... * Problems: * a) we can get into loop creation. * b) race potential - two innocent renames can create a loop together. * That's where 4.4 screws up. Current fix: serialization on * sb->s_vfs_rename_mutex. We might be more accurate, but that's another * story. * c) we have to lock _four_ objects - parents and victim (if it exists), * and source (if it is not a directory). * And that - after we got ->i_mutex on parents (until then we don't know * whether the target exists). Solution: try to be smart with locking * order for inodes. We rely on the fact that tree topology may change * only under ->s_vfs_rename_mutex _and_ that parent of the object we * move will be locked. Thus we can rank directories by the tree * (ancestors first) and rank all non-directories after them. * That works since everybody except rename does "lock parent, lookup, * lock child" and rename is under ->s_vfs_rename_mutex. * HOWEVER, it relies on the assumption that any object with ->lookup() * has no more than 1 dentry. If "hybrid" objects will ever appear, * we'd better make sure that there's no link(2) for them. * d) conversion from fhandle to dentry may come in the wrong moment - when * we are removing the target. Solution: we will have to grab ->i_mutex * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on * ->i_mutex on parents, which works but leads to some truly excessive * locking]. */ int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, struct inode **delegated_inode, unsigned int flags) { int error; bool is_dir = d_is_dir(old_dentry); const unsigned char *old_name; struct inode *source = old_dentry->d_inode; struct inode *target = new_dentry->d_inode; bool new_is_dir = false; unsigned max_links = new_dir->i_sb->s_max_links; if (source == target) return 0; error = may_delete(old_dir, old_dentry, is_dir); if (error) return error; if (!target) { error = may_create(new_dir, new_dentry); } else { new_is_dir = d_is_dir(new_dentry); if (!(flags & RENAME_EXCHANGE)) error = may_delete(new_dir, new_dentry, is_dir); else error = may_delete(new_dir, new_dentry, new_is_dir); } if (error) return error; if (!old_dir->i_op->rename && !old_dir->i_op->rename2) return -EPERM; if (flags && !old_dir->i_op->rename2) return -EINVAL; /* * If we are going to change the parent - check write permissions, * we'll need to flip '..'. */ if (new_dir != old_dir) { if (is_dir) { error = inode_permission(source, MAY_WRITE); if (error) return error; } if ((flags & RENAME_EXCHANGE) && new_is_dir) { error = inode_permission(target, MAY_WRITE); if (error) return error; } } error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry, flags); if (error) return error; old_name = fsnotify_oldname_init(old_dentry->d_name.name); dget(new_dentry); if (!is_dir || (flags & RENAME_EXCHANGE)) lock_two_nondirectories(source, target); else if (target) mutex_lock(&target->i_mutex); error = -EBUSY; if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry)) goto out; if (max_links && new_dir != old_dir) { error = -EMLINK; if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links) goto out; if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir && old_dir->i_nlink >= max_links) goto out; } if (is_dir && !(flags & RENAME_EXCHANGE) && target) shrink_dcache_parent(new_dentry); if (!is_dir) { error = try_break_deleg(source, delegated_inode); if (error) goto out; } if (target && !new_is_dir) { error = try_break_deleg(target, delegated_inode); if (error) goto out; } if (!old_dir->i_op->rename2) { error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry); } else { WARN_ON(old_dir->i_op->rename != NULL); error = old_dir->i_op->rename2(old_dir, old_dentry, new_dir, new_dentry, flags); } if (error) goto out; if (!(flags & RENAME_EXCHANGE) && target) { if (is_dir) target->i_flags |= S_DEAD; dont_mount(new_dentry); detach_mounts(new_dentry); } if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) { if (!(flags & RENAME_EXCHANGE)) d_move(old_dentry, new_dentry); else d_exchange(old_dentry, new_dentry); } out: if (!is_dir || (flags & RENAME_EXCHANGE)) unlock_two_nondirectories(source, target); else if (target) mutex_unlock(&target->i_mutex); dput(new_dentry); if (!error) { fsnotify_move(old_dir, new_dir, old_name, is_dir, !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry); if (flags & RENAME_EXCHANGE) { fsnotify_move(new_dir, old_dir, old_dentry->d_name.name, new_is_dir, NULL, new_dentry); } } fsnotify_oldname_free(old_name); return error; } EXPORT_SYMBOL(vfs_rename); SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname, unsigned int, flags) { struct dentry *old_dentry, *new_dentry; struct dentry *trap; struct path old_path, new_path; struct qstr old_last, new_last; int old_type, new_type; struct inode *delegated_inode = NULL; struct filename *from; struct filename *to; unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET; bool should_retry = false; int error; if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT)) return -EINVAL; if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) && (flags & RENAME_EXCHANGE)) return -EINVAL; if ((flags & RENAME_WHITEOUT) && !capable(CAP_MKNOD)) return -EPERM; if (flags & RENAME_EXCHANGE) target_flags = 0; retry: from = user_path_parent(olddfd, oldname, &old_path, &old_last, &old_type, lookup_flags); if (IS_ERR(from)) { error = PTR_ERR(from); goto exit; } to = user_path_parent(newdfd, newname, &new_path, &new_last, &new_type, lookup_flags); if (IS_ERR(to)) { error = PTR_ERR(to); goto exit1; } error = -EXDEV; if (old_path.mnt != new_path.mnt) goto exit2; error = -EBUSY; if (old_type != LAST_NORM) goto exit2; if (flags & RENAME_NOREPLACE) error = -EEXIST; if (new_type != LAST_NORM) goto exit2; error = mnt_want_write(old_path.mnt); if (error) goto exit2; retry_deleg: trap = lock_rename(new_path.dentry, old_path.dentry); old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags); error = PTR_ERR(old_dentry); if (IS_ERR(old_dentry)) goto exit3; /* source must exist */ error = -ENOENT; if (d_is_negative(old_dentry)) goto exit4; new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags); error = PTR_ERR(new_dentry); if (IS_ERR(new_dentry)) goto exit4; error = -EEXIST; if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry)) goto exit5; if (flags & RENAME_EXCHANGE) { error = -ENOENT; if (d_is_negative(new_dentry)) goto exit5; if (!d_is_dir(new_dentry)) { error = -ENOTDIR; if (new_last.name[new_last.len]) goto exit5; } } /* unless the source is a directory trailing slashes give -ENOTDIR */ if (!d_is_dir(old_dentry)) { error = -ENOTDIR; if (old_last.name[old_last.len]) goto exit5; if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len]) goto exit5; } /* source should not be ancestor of target */ error = -EINVAL; if (old_dentry == trap) goto exit5; /* target should not be an ancestor of source */ if (!(flags & RENAME_EXCHANGE)) error = -ENOTEMPTY; if (new_dentry == trap) goto exit5; error = security_path_rename(&old_path, old_dentry, &new_path, new_dentry, flags); if (error) goto exit5; error = vfs_rename(old_path.dentry->d_inode, old_dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode, flags); exit5: dput(new_dentry); exit4: dput(old_dentry); exit3: unlock_rename(new_path.dentry, old_path.dentry); if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) goto retry_deleg; } mnt_drop_write(old_path.mnt); exit2: if (retry_estale(error, lookup_flags)) should_retry = true; path_put(&new_path); putname(to); exit1: path_put(&old_path); putname(from); if (should_retry) { should_retry = false; lookup_flags |= LOOKUP_REVAL; goto retry; } exit: return error; } SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname) { return sys_renameat2(olddfd, oldname, newdfd, newname, 0); } SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname) { return sys_renameat2(AT_FDCWD, oldname, AT_FDCWD, newname, 0); } int vfs_whiteout(struct inode *dir, struct dentry *dentry) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->mknod) return -EPERM; return dir->i_op->mknod(dir, dentry, S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV); } EXPORT_SYMBOL(vfs_whiteout); int readlink_copy(char __user *buffer, int buflen, const char *link) { int len = PTR_ERR(link); if (IS_ERR(link)) goto out; len = strlen(link); if (len > (unsigned) buflen) len = buflen; if (copy_to_user(buffer, link, len)) len = -EFAULT; out: return len; } EXPORT_SYMBOL(readlink_copy); /* * A helper for ->readlink(). This should be used *ONLY* for symlinks that * have ->follow_link() touching nd only in nd_set_link(). Using (or not * using) it for any given inode is up to filesystem. */ int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen) { void *cookie; struct inode *inode = d_inode(dentry); const char *link = inode->i_link; int res; if (!link) { link = inode->i_op->follow_link(dentry, &cookie); if (IS_ERR(link)) return PTR_ERR(link); } res = readlink_copy(buffer, buflen, link); if (inode->i_op->put_link) inode->i_op->put_link(inode, cookie); return res; } EXPORT_SYMBOL(generic_readlink); /* get the link contents into pagecache */ static char *page_getlink(struct dentry * dentry, struct page **ppage) { char *kaddr; struct page *page; struct address_space *mapping = dentry->d_inode->i_mapping; page = read_mapping_page(mapping, 0, NULL); if (IS_ERR(page)) return (char*)page; *ppage = page; kaddr = kmap(page); nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1); return kaddr; } int page_readlink(struct dentry *dentry, char __user *buffer, int buflen) { struct page *page = NULL; int res = readlink_copy(buffer, buflen, page_getlink(dentry, &page)); if (page) { kunmap(page); page_cache_release(page); } return res; } EXPORT_SYMBOL(page_readlink); const char *page_follow_link_light(struct dentry *dentry, void **cookie) { struct page *page = NULL; char *res = page_getlink(dentry, &page); if (!IS_ERR(res)) *cookie = page; return res; } EXPORT_SYMBOL(page_follow_link_light); void page_put_link(struct inode *unused, void *cookie) { struct page *page = cookie; kunmap(page); page_cache_release(page); } EXPORT_SYMBOL(page_put_link); /* * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS */ int __page_symlink(struct inode *inode, const char *symname, int len, int nofs) { struct address_space *mapping = inode->i_mapping; struct page *page; void *fsdata; int err; char *kaddr; unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE; if (nofs) flags |= AOP_FLAG_NOFS; retry: err = pagecache_write_begin(NULL, mapping, 0, len-1, flags, &page, &fsdata); if (err) goto fail; kaddr = kmap_atomic(page); memcpy(kaddr, symname, len-1); kunmap_atomic(kaddr); err = pagecache_write_end(NULL, mapping, 0, len-1, len-1, page, fsdata); if (err < 0) goto fail; if (err < len-1) goto retry; mark_inode_dirty(inode); return 0; fail: return err; } EXPORT_SYMBOL(__page_symlink); int page_symlink(struct inode *inode, const char *symname, int len) { return __page_symlink(inode, symname, len, !(mapping_gfp_mask(inode->i_mapping) & __GFP_FS)); } EXPORT_SYMBOL(page_symlink); const struct inode_operations page_symlink_inode_operations = { .readlink = generic_readlink, .follow_link = page_follow_link_light, .put_link = page_put_link, }; EXPORT_SYMBOL(page_symlink_inode_operations);
./CrossVul/dataset_final_sorted/CWE-254/c/bad_1547_0
crossvul-cpp_data_good_2305_0
/* (C) 1999-2001 Paul `Rusty' Russell * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org> * * 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. */ #include <linux/types.h> #include <linux/jiffies.h> #include <linux/timer.h> #include <linux/netfilter.h> #include <net/netfilter/nf_conntrack_l4proto.h> static unsigned int nf_ct_generic_timeout __read_mostly = 600*HZ; static bool nf_generic_should_process(u8 proto) { switch (proto) { #ifdef CONFIG_NF_CT_PROTO_SCTP_MODULE case IPPROTO_SCTP: return false; #endif #ifdef CONFIG_NF_CT_PROTO_DCCP_MODULE case IPPROTO_DCCP: return false; #endif #ifdef CONFIG_NF_CT_PROTO_GRE_MODULE case IPPROTO_GRE: return false; #endif #ifdef CONFIG_NF_CT_PROTO_UDPLITE_MODULE case IPPROTO_UDPLITE: return false; #endif default: return true; } } static inline struct nf_generic_net *generic_pernet(struct net *net) { return &net->ct.nf_ct_proto.generic; } static bool generic_pkt_to_tuple(const struct sk_buff *skb, unsigned int dataoff, struct nf_conntrack_tuple *tuple) { tuple->src.u.all = 0; tuple->dst.u.all = 0; return true; } static bool generic_invert_tuple(struct nf_conntrack_tuple *tuple, const struct nf_conntrack_tuple *orig) { tuple->src.u.all = 0; tuple->dst.u.all = 0; return true; } /* Print out the per-protocol part of the tuple. */ static int generic_print_tuple(struct seq_file *s, const struct nf_conntrack_tuple *tuple) { return 0; } static unsigned int *generic_get_timeouts(struct net *net) { return &(generic_pernet(net)->timeout); } /* Returns verdict for packet, or -1 for invalid. */ static int generic_packet(struct nf_conn *ct, const struct sk_buff *skb, unsigned int dataoff, enum ip_conntrack_info ctinfo, u_int8_t pf, unsigned int hooknum, unsigned int *timeout) { nf_ct_refresh_acct(ct, ctinfo, skb, *timeout); return NF_ACCEPT; } /* Called when a new connection for this protocol found. */ static bool generic_new(struct nf_conn *ct, const struct sk_buff *skb, unsigned int dataoff, unsigned int *timeouts) { return nf_generic_should_process(nf_ct_protonum(ct)); } #if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT) #include <linux/netfilter/nfnetlink.h> #include <linux/netfilter/nfnetlink_cttimeout.h> static int generic_timeout_nlattr_to_obj(struct nlattr *tb[], struct net *net, void *data) { unsigned int *timeout = data; struct nf_generic_net *gn = generic_pernet(net); if (tb[CTA_TIMEOUT_GENERIC_TIMEOUT]) *timeout = ntohl(nla_get_be32(tb[CTA_TIMEOUT_GENERIC_TIMEOUT])) * HZ; else { /* Set default generic timeout. */ *timeout = gn->timeout; } return 0; } static int generic_timeout_obj_to_nlattr(struct sk_buff *skb, const void *data) { const unsigned int *timeout = data; if (nla_put_be32(skb, CTA_TIMEOUT_GENERIC_TIMEOUT, htonl(*timeout / HZ))) goto nla_put_failure; return 0; nla_put_failure: return -ENOSPC; } static const struct nla_policy generic_timeout_nla_policy[CTA_TIMEOUT_GENERIC_MAX+1] = { [CTA_TIMEOUT_GENERIC_TIMEOUT] = { .type = NLA_U32 }, }; #endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */ #ifdef CONFIG_SYSCTL static struct ctl_table generic_sysctl_table[] = { { .procname = "nf_conntrack_generic_timeout", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { } }; #ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT static struct ctl_table generic_compat_sysctl_table[] = { { .procname = "ip_conntrack_generic_timeout", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { } }; #endif /* CONFIG_NF_CONNTRACK_PROC_COMPAT */ #endif /* CONFIG_SYSCTL */ static int generic_kmemdup_sysctl_table(struct nf_proto_net *pn, struct nf_generic_net *gn) { #ifdef CONFIG_SYSCTL pn->ctl_table = kmemdup(generic_sysctl_table, sizeof(generic_sysctl_table), GFP_KERNEL); if (!pn->ctl_table) return -ENOMEM; pn->ctl_table[0].data = &gn->timeout; #endif return 0; } static int generic_kmemdup_compat_sysctl_table(struct nf_proto_net *pn, struct nf_generic_net *gn) { #ifdef CONFIG_SYSCTL #ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT pn->ctl_compat_table = kmemdup(generic_compat_sysctl_table, sizeof(generic_compat_sysctl_table), GFP_KERNEL); if (!pn->ctl_compat_table) return -ENOMEM; pn->ctl_compat_table[0].data = &gn->timeout; #endif #endif return 0; } static int generic_init_net(struct net *net, u_int16_t proto) { int ret; struct nf_generic_net *gn = generic_pernet(net); struct nf_proto_net *pn = &gn->pn; gn->timeout = nf_ct_generic_timeout; ret = generic_kmemdup_compat_sysctl_table(pn, gn); if (ret < 0) return ret; ret = generic_kmemdup_sysctl_table(pn, gn); if (ret < 0) nf_ct_kfree_compat_sysctl_table(pn); return ret; } static struct nf_proto_net *generic_get_net_proto(struct net *net) { return &net->ct.nf_ct_proto.generic.pn; } struct nf_conntrack_l4proto nf_conntrack_l4proto_generic __read_mostly = { .l3proto = PF_UNSPEC, .l4proto = 255, .name = "unknown", .pkt_to_tuple = generic_pkt_to_tuple, .invert_tuple = generic_invert_tuple, .print_tuple = generic_print_tuple, .packet = generic_packet, .get_timeouts = generic_get_timeouts, .new = generic_new, #if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT) .ctnl_timeout = { .nlattr_to_obj = generic_timeout_nlattr_to_obj, .obj_to_nlattr = generic_timeout_obj_to_nlattr, .nlattr_max = CTA_TIMEOUT_GENERIC_MAX, .obj_size = sizeof(unsigned int), .nla_policy = generic_timeout_nla_policy, }, #endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */ .init_net = generic_init_net, .get_net_proto = generic_get_net_proto, };
./CrossVul/dataset_final_sorted/CWE-254/c/good_2305_0
crossvul-cpp_data_good_1547_0
/* * linux/fs/namei.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * Some corrections by tytso. */ /* [Feb 1997 T. Schoebel-Theuer] Complete rewrite of the pathname * lookup logic. */ /* [Feb-Apr 2000, AV] Rewrite to the new namespace architecture. */ #include <linux/init.h> #include <linux/export.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/namei.h> #include <linux/pagemap.h> #include <linux/fsnotify.h> #include <linux/personality.h> #include <linux/security.h> #include <linux/ima.h> #include <linux/syscalls.h> #include <linux/mount.h> #include <linux/audit.h> #include <linux/capability.h> #include <linux/file.h> #include <linux/fcntl.h> #include <linux/device_cgroup.h> #include <linux/fs_struct.h> #include <linux/posix_acl.h> #include <linux/hash.h> #include <asm/uaccess.h> #include "internal.h" #include "mount.h" /* [Feb-1997 T. Schoebel-Theuer] * Fundamental changes in the pathname lookup mechanisms (namei) * were necessary because of omirr. The reason is that omirr needs * to know the _real_ pathname, not the user-supplied one, in case * of symlinks (and also when transname replacements occur). * * The new code replaces the old recursive symlink resolution with * an iterative one (in case of non-nested symlink chains). It does * this with calls to <fs>_follow_link(). * As a side effect, dir_namei(), _namei() and follow_link() are now * replaced with a single function lookup_dentry() that can handle all * the special cases of the former code. * * With the new dcache, the pathname is stored at each inode, at least as * long as the refcount of the inode is positive. As a side effect, the * size of the dcache depends on the inode cache and thus is dynamic. * * [29-Apr-1998 C. Scott Ananian] Updated above description of symlink * resolution to correspond with current state of the code. * * Note that the symlink resolution is not *completely* iterative. * There is still a significant amount of tail- and mid- recursion in * the algorithm. Also, note that <fs>_readlink() is not used in * lookup_dentry(): lookup_dentry() on the result of <fs>_readlink() * may return different results than <fs>_follow_link(). Many virtual * filesystems (including /proc) exhibit this behavior. */ /* [24-Feb-97 T. Schoebel-Theuer] Side effects caused by new implementation: * New symlink semantics: when open() is called with flags O_CREAT | O_EXCL * and the name already exists in form of a symlink, try to create the new * name indicated by the symlink. The old code always complained that the * name already exists, due to not following the symlink even if its target * is nonexistent. The new semantics affects also mknod() and link() when * the name is a symlink pointing to a non-existent name. * * I don't know which semantics is the right one, since I have no access * to standards. But I found by trial that HP-UX 9.0 has the full "new" * semantics implemented, while SunOS 4.1.1 and Solaris (SunOS 5.4) have the * "old" one. Personally, I think the new semantics is much more logical. * Note that "ln old new" where "new" is a symlink pointing to a non-existing * file does succeed in both HP-UX and SunOs, but not in Solaris * and in the old Linux semantics. */ /* [16-Dec-97 Kevin Buhr] For security reasons, we change some symlink * semantics. See the comments in "open_namei" and "do_link" below. * * [10-Sep-98 Alan Modra] Another symlink change. */ /* [Feb-Apr 2000 AV] Complete rewrite. Rules for symlinks: * inside the path - always follow. * in the last component in creation/removal/renaming - never follow. * if LOOKUP_FOLLOW passed - follow. * if the pathname has trailing slashes - follow. * otherwise - don't follow. * (applied in that order). * * [Jun 2000 AV] Inconsistent behaviour of open() in case if flags==O_CREAT * restored for 2.4. This is the last surviving part of old 4.2BSD bug. * During the 2.4 we need to fix the userland stuff depending on it - * hopefully we will be able to get rid of that wart in 2.5. So far only * XEmacs seems to be relying on it... */ /* * [Sep 2001 AV] Single-semaphore locking scheme (kudos to David Holland) * implemented. Let's see if raised priority of ->s_vfs_rename_mutex gives * any extra contention... */ /* In order to reduce some races, while at the same time doing additional * checking and hopefully speeding things up, we copy filenames to the * kernel data space before using them.. * * POSIX.1 2.4: an empty pathname is invalid (ENOENT). * PATH_MAX includes the nul terminator --RR. */ #define EMBEDDED_NAME_MAX (PATH_MAX - offsetof(struct filename, iname)) struct filename * getname_flags(const char __user *filename, int flags, int *empty) { struct filename *result; char *kname; int len; result = audit_reusename(filename); if (result) return result; result = __getname(); if (unlikely(!result)) return ERR_PTR(-ENOMEM); /* * First, try to embed the struct filename inside the names_cache * allocation */ kname = (char *)result->iname; result->name = kname; len = strncpy_from_user(kname, filename, EMBEDDED_NAME_MAX); if (unlikely(len < 0)) { __putname(result); return ERR_PTR(len); } /* * Uh-oh. We have a name that's approaching PATH_MAX. Allocate a * separate struct filename so we can dedicate the entire * names_cache allocation for the pathname, and re-do the copy from * userland. */ if (unlikely(len == EMBEDDED_NAME_MAX)) { const size_t size = offsetof(struct filename, iname[1]); kname = (char *)result; /* * size is chosen that way we to guarantee that * result->iname[0] is within the same object and that * kname can't be equal to result->iname, no matter what. */ result = kzalloc(size, GFP_KERNEL); if (unlikely(!result)) { __putname(kname); return ERR_PTR(-ENOMEM); } result->name = kname; len = strncpy_from_user(kname, filename, PATH_MAX); if (unlikely(len < 0)) { __putname(kname); kfree(result); return ERR_PTR(len); } if (unlikely(len == PATH_MAX)) { __putname(kname); kfree(result); return ERR_PTR(-ENAMETOOLONG); } } result->refcnt = 1; /* The empty path is special. */ if (unlikely(!len)) { if (empty) *empty = 1; if (!(flags & LOOKUP_EMPTY)) { putname(result); return ERR_PTR(-ENOENT); } } result->uptr = filename; result->aname = NULL; audit_getname(result); return result; } struct filename * getname(const char __user * filename) { return getname_flags(filename, 0, NULL); } struct filename * getname_kernel(const char * filename) { struct filename *result; int len = strlen(filename) + 1; result = __getname(); if (unlikely(!result)) return ERR_PTR(-ENOMEM); if (len <= EMBEDDED_NAME_MAX) { result->name = (char *)result->iname; } else if (len <= PATH_MAX) { struct filename *tmp; tmp = kmalloc(sizeof(*tmp), GFP_KERNEL); if (unlikely(!tmp)) { __putname(result); return ERR_PTR(-ENOMEM); } tmp->name = (char *)result; result = tmp; } else { __putname(result); return ERR_PTR(-ENAMETOOLONG); } memcpy((char *)result->name, filename, len); result->uptr = NULL; result->aname = NULL; result->refcnt = 1; audit_getname(result); return result; } void putname(struct filename *name) { BUG_ON(name->refcnt <= 0); if (--name->refcnt > 0) return; if (name->name != name->iname) { __putname(name->name); kfree(name); } else __putname(name); } static int check_acl(struct inode *inode, int mask) { #ifdef CONFIG_FS_POSIX_ACL struct posix_acl *acl; if (mask & MAY_NOT_BLOCK) { acl = get_cached_acl_rcu(inode, ACL_TYPE_ACCESS); if (!acl) return -EAGAIN; /* no ->get_acl() calls in RCU mode... */ if (acl == ACL_NOT_CACHED) return -ECHILD; return posix_acl_permission(inode, acl, mask & ~MAY_NOT_BLOCK); } acl = get_acl(inode, ACL_TYPE_ACCESS); if (IS_ERR(acl)) return PTR_ERR(acl); if (acl) { int error = posix_acl_permission(inode, acl, mask); posix_acl_release(acl); return error; } #endif return -EAGAIN; } /* * This does the basic permission checking */ static int acl_permission_check(struct inode *inode, int mask) { unsigned int mode = inode->i_mode; if (likely(uid_eq(current_fsuid(), inode->i_uid))) mode >>= 6; else { if (IS_POSIXACL(inode) && (mode & S_IRWXG)) { int error = check_acl(inode, mask); if (error != -EAGAIN) return error; } if (in_group_p(inode->i_gid)) mode >>= 3; } /* * If the DACs are ok we don't need any capability check. */ if ((mask & ~mode & (MAY_READ | MAY_WRITE | MAY_EXEC)) == 0) return 0; return -EACCES; } /** * generic_permission - check for access rights on a Posix-like filesystem * @inode: inode to check access rights for * @mask: right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC, ...) * * Used to check for read/write/execute permissions on a file. * We use "fsuid" for this, letting us set arbitrary permissions * for filesystem access without changing the "normal" uids which * are used for other things. * * generic_permission is rcu-walk aware. It returns -ECHILD in case an rcu-walk * request cannot be satisfied (eg. requires blocking or too much complexity). * It would then be called again in ref-walk mode. */ int generic_permission(struct inode *inode, int mask) { int ret; /* * Do the basic permission checks. */ ret = acl_permission_check(inode, mask); if (ret != -EACCES) return ret; if (S_ISDIR(inode->i_mode)) { /* DACs are overridable for directories */ if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE)) return 0; if (!(mask & MAY_WRITE)) if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } /* * Read/write DACs are always overridable. * Executable DACs are overridable when there is * at least one exec bit set. */ if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO)) if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE)) return 0; /* * Searching includes executable on directories, else just read. */ mask &= MAY_READ | MAY_WRITE | MAY_EXEC; if (mask == MAY_READ) if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH)) return 0; return -EACCES; } EXPORT_SYMBOL(generic_permission); /* * We _really_ want to just do "generic_permission()" without * even looking at the inode->i_op values. So we keep a cache * flag in inode->i_opflags, that says "this has not special * permission function, use the fast case". */ static inline int do_inode_permission(struct inode *inode, int mask) { if (unlikely(!(inode->i_opflags & IOP_FASTPERM))) { if (likely(inode->i_op->permission)) return inode->i_op->permission(inode, mask); /* This gets set once for the inode lifetime */ spin_lock(&inode->i_lock); inode->i_opflags |= IOP_FASTPERM; spin_unlock(&inode->i_lock); } return generic_permission(inode, mask); } /** * __inode_permission - Check for access rights to a given inode * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Check for read/write/execute permissions on an inode. * * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask. * * This does not check for a read-only file system. You probably want * inode_permission(). */ int __inode_permission(struct inode *inode, int mask) { int retval; if (unlikely(mask & MAY_WRITE)) { /* * Nobody gets write access to an immutable file. */ if (IS_IMMUTABLE(inode)) return -EACCES; } retval = do_inode_permission(inode, mask); if (retval) return retval; retval = devcgroup_inode_permission(inode, mask); if (retval) return retval; return security_inode_permission(inode, mask); } EXPORT_SYMBOL(__inode_permission); /** * sb_permission - Check superblock-level permissions * @sb: Superblock of inode to check permission on * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Separate out file-system wide checks from inode-specific permission checks. */ static int sb_permission(struct super_block *sb, struct inode *inode, int mask) { if (unlikely(mask & MAY_WRITE)) { umode_t mode = inode->i_mode; /* Nobody gets write access to a read-only fs. */ if ((sb->s_flags & MS_RDONLY) && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) return -EROFS; } return 0; } /** * inode_permission - Check for access rights to a given inode * @inode: Inode to check permission on * @mask: Right to check for (%MAY_READ, %MAY_WRITE, %MAY_EXEC) * * Check for read/write/execute permissions on an inode. We use fs[ug]id for * this, letting us set arbitrary permissions for filesystem access without * changing the "normal" UIDs which are used for other things. * * When checking for MAY_APPEND, MAY_WRITE must also be set in @mask. */ int inode_permission(struct inode *inode, int mask) { int retval; retval = sb_permission(inode->i_sb, inode, mask); if (retval) return retval; return __inode_permission(inode, mask); } EXPORT_SYMBOL(inode_permission); /** * path_get - get a reference to a path * @path: path to get the reference to * * Given a path increment the reference count to the dentry and the vfsmount. */ void path_get(const struct path *path) { mntget(path->mnt); dget(path->dentry); } EXPORT_SYMBOL(path_get); /** * path_put - put a reference to a path * @path: path to put the reference to * * Given a path decrement the reference count to the dentry and the vfsmount. */ void path_put(const struct path *path) { dput(path->dentry); mntput(path->mnt); } EXPORT_SYMBOL(path_put); #define EMBEDDED_LEVELS 2 struct nameidata { struct path path; struct qstr last; struct path root; struct inode *inode; /* path.dentry.d_inode */ unsigned int flags; unsigned seq, m_seq; int last_type; unsigned depth; int total_link_count; struct saved { struct path link; void *cookie; const char *name; struct inode *inode; unsigned seq; } *stack, internal[EMBEDDED_LEVELS]; struct filename *name; struct nameidata *saved; unsigned root_seq; int dfd; }; static void set_nameidata(struct nameidata *p, int dfd, struct filename *name) { struct nameidata *old = current->nameidata; p->stack = p->internal; p->dfd = dfd; p->name = name; p->total_link_count = old ? old->total_link_count : 0; p->saved = old; current->nameidata = p; } static void restore_nameidata(void) { struct nameidata *now = current->nameidata, *old = now->saved; current->nameidata = old; if (old) old->total_link_count = now->total_link_count; if (now->stack != now->internal) { kfree(now->stack); now->stack = now->internal; } } static int __nd_alloc_stack(struct nameidata *nd) { struct saved *p; if (nd->flags & LOOKUP_RCU) { p= kmalloc(MAXSYMLINKS * sizeof(struct saved), GFP_ATOMIC); if (unlikely(!p)) return -ECHILD; } else { p= kmalloc(MAXSYMLINKS * sizeof(struct saved), GFP_KERNEL); if (unlikely(!p)) return -ENOMEM; } memcpy(p, nd->internal, sizeof(nd->internal)); nd->stack = p; return 0; } /** * path_connected - Verify that a path->dentry is below path->mnt.mnt_root * @path: nameidate to verify * * Rename can sometimes move a file or directory outside of a bind * mount, path_connected allows those cases to be detected. */ static bool path_connected(const struct path *path) { struct vfsmount *mnt = path->mnt; /* Only bind mounts can have disconnected paths */ if (mnt->mnt_root == mnt->mnt_sb->s_root) return true; return is_subdir(path->dentry, mnt->mnt_root); } static inline int nd_alloc_stack(struct nameidata *nd) { if (likely(nd->depth != EMBEDDED_LEVELS)) return 0; if (likely(nd->stack != nd->internal)) return 0; return __nd_alloc_stack(nd); } static void drop_links(struct nameidata *nd) { int i = nd->depth; while (i--) { struct saved *last = nd->stack + i; struct inode *inode = last->inode; if (last->cookie && inode->i_op->put_link) { inode->i_op->put_link(inode, last->cookie); last->cookie = NULL; } } } static void terminate_walk(struct nameidata *nd) { drop_links(nd); if (!(nd->flags & LOOKUP_RCU)) { int i; path_put(&nd->path); for (i = 0; i < nd->depth; i++) path_put(&nd->stack[i].link); if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) { path_put(&nd->root); nd->root.mnt = NULL; } } else { nd->flags &= ~LOOKUP_RCU; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); } nd->depth = 0; } /* path_put is needed afterwards regardless of success or failure */ static bool legitimize_path(struct nameidata *nd, struct path *path, unsigned seq) { int res = __legitimize_mnt(path->mnt, nd->m_seq); if (unlikely(res)) { if (res > 0) path->mnt = NULL; path->dentry = NULL; return false; } if (unlikely(!lockref_get_not_dead(&path->dentry->d_lockref))) { path->dentry = NULL; return false; } return !read_seqcount_retry(&path->dentry->d_seq, seq); } static bool legitimize_links(struct nameidata *nd) { int i; for (i = 0; i < nd->depth; i++) { struct saved *last = nd->stack + i; if (unlikely(!legitimize_path(nd, &last->link, last->seq))) { drop_links(nd); nd->depth = i + 1; return false; } } return true; } /* * Path walking has 2 modes, rcu-walk and ref-walk (see * Documentation/filesystems/path-lookup.txt). In situations when we can't * continue in RCU mode, we attempt to drop out of rcu-walk mode and grab * normal reference counts on dentries and vfsmounts to transition to rcu-walk * mode. Refcounts are grabbed at the last known good point before rcu-walk * got stuck, so ref-walk may continue from there. If this is not successful * (eg. a seqcount has changed), then failure is returned and it's up to caller * to restart the path walk from the beginning in ref-walk mode. */ /** * unlazy_walk - try to switch to ref-walk mode. * @nd: nameidata pathwalk data * @dentry: child of nd->path.dentry or NULL * @seq: seq number to check dentry against * Returns: 0 on success, -ECHILD on failure * * unlazy_walk attempts to legitimize the current nd->path, nd->root and dentry * for ref-walk mode. @dentry must be a path found by a do_lookup call on * @nd or NULL. Must be called from rcu-walk context. * Nothing should touch nameidata between unlazy_walk() failure and * terminate_walk(). */ static int unlazy_walk(struct nameidata *nd, struct dentry *dentry, unsigned seq) { struct dentry *parent = nd->path.dentry; BUG_ON(!(nd->flags & LOOKUP_RCU)); nd->flags &= ~LOOKUP_RCU; if (unlikely(!legitimize_links(nd))) goto out2; if (unlikely(!legitimize_mnt(nd->path.mnt, nd->m_seq))) goto out2; if (unlikely(!lockref_get_not_dead(&parent->d_lockref))) goto out1; /* * For a negative lookup, the lookup sequence point is the parents * sequence point, and it only needs to revalidate the parent dentry. * * For a positive lookup, we need to move both the parent and the * dentry from the RCU domain to be properly refcounted. And the * sequence number in the dentry validates *both* dentry counters, * since we checked the sequence number of the parent after we got * the child sequence number. So we know the parent must still * be valid if the child sequence number is still valid. */ if (!dentry) { if (read_seqcount_retry(&parent->d_seq, nd->seq)) goto out; BUG_ON(nd->inode != parent->d_inode); } else { if (!lockref_get_not_dead(&dentry->d_lockref)) goto out; if (read_seqcount_retry(&dentry->d_seq, seq)) goto drop_dentry; } /* * Sequence counts matched. Now make sure that the root is * still valid and get it if required. */ if (nd->root.mnt && !(nd->flags & LOOKUP_ROOT)) { if (unlikely(!legitimize_path(nd, &nd->root, nd->root_seq))) { rcu_read_unlock(); dput(dentry); return -ECHILD; } } rcu_read_unlock(); return 0; drop_dentry: rcu_read_unlock(); dput(dentry); goto drop_root_mnt; out2: nd->path.mnt = NULL; out1: nd->path.dentry = NULL; out: rcu_read_unlock(); drop_root_mnt: if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; return -ECHILD; } static int unlazy_link(struct nameidata *nd, struct path *link, unsigned seq) { if (unlikely(!legitimize_path(nd, link, seq))) { drop_links(nd); nd->depth = 0; nd->flags &= ~LOOKUP_RCU; nd->path.mnt = NULL; nd->path.dentry = NULL; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); } else if (likely(unlazy_walk(nd, NULL, 0)) == 0) { return 0; } path_put(link); return -ECHILD; } static inline int d_revalidate(struct dentry *dentry, unsigned int flags) { return dentry->d_op->d_revalidate(dentry, flags); } /** * complete_walk - successful completion of path walk * @nd: pointer nameidata * * If we had been in RCU mode, drop out of it and legitimize nd->path. * Revalidate the final result, unless we'd already done that during * the path walk or the filesystem doesn't ask for it. Return 0 on * success, -error on failure. In case of failure caller does not * need to drop nd->path. */ static int complete_walk(struct nameidata *nd) { struct dentry *dentry = nd->path.dentry; int status; if (nd->flags & LOOKUP_RCU) { if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; if (unlikely(unlazy_walk(nd, NULL, 0))) return -ECHILD; } if (likely(!(nd->flags & LOOKUP_JUMPED))) return 0; if (likely(!(dentry->d_flags & DCACHE_OP_WEAK_REVALIDATE))) return 0; status = dentry->d_op->d_weak_revalidate(dentry, nd->flags); if (status > 0) return 0; if (!status) status = -ESTALE; return status; } static void set_root(struct nameidata *nd) { get_fs_root(current->fs, &nd->root); } static void set_root_rcu(struct nameidata *nd) { struct fs_struct *fs = current->fs; unsigned seq; do { seq = read_seqcount_begin(&fs->seq); nd->root = fs->root; nd->root_seq = __read_seqcount_begin(&nd->root.dentry->d_seq); } while (read_seqcount_retry(&fs->seq, seq)); } static void path_put_conditional(struct path *path, struct nameidata *nd) { dput(path->dentry); if (path->mnt != nd->path.mnt) mntput(path->mnt); } static inline void path_to_nameidata(const struct path *path, struct nameidata *nd) { if (!(nd->flags & LOOKUP_RCU)) { dput(nd->path.dentry); if (nd->path.mnt != path->mnt) mntput(nd->path.mnt); } nd->path.mnt = path->mnt; nd->path.dentry = path->dentry; } /* * Helper to directly jump to a known parsed path from ->follow_link, * caller must have taken a reference to path beforehand. */ void nd_jump_link(struct path *path) { struct nameidata *nd = current->nameidata; path_put(&nd->path); nd->path = *path; nd->inode = nd->path.dentry->d_inode; nd->flags |= LOOKUP_JUMPED; } static inline void put_link(struct nameidata *nd) { struct saved *last = nd->stack + --nd->depth; struct inode *inode = last->inode; if (last->cookie && inode->i_op->put_link) inode->i_op->put_link(inode, last->cookie); if (!(nd->flags & LOOKUP_RCU)) path_put(&last->link); } int sysctl_protected_symlinks __read_mostly = 0; int sysctl_protected_hardlinks __read_mostly = 0; /** * may_follow_link - Check symlink following for unsafe situations * @nd: nameidata pathwalk data * * In the case of the sysctl_protected_symlinks sysctl being enabled, * CAP_DAC_OVERRIDE needs to be specifically ignored if the symlink is * in a sticky world-writable directory. This is to protect privileged * processes from failing races against path names that may change out * from under them by way of other users creating malicious symlinks. * It will permit symlinks to be followed only when outside a sticky * world-writable directory, or when the uid of the symlink and follower * match, or when the directory owner matches the symlink's owner. * * Returns 0 if following the symlink is allowed, -ve on error. */ static inline int may_follow_link(struct nameidata *nd) { const struct inode *inode; const struct inode *parent; if (!sysctl_protected_symlinks) return 0; /* Allowed if owner and follower match. */ inode = nd->stack[0].inode; if (uid_eq(current_cred()->fsuid, inode->i_uid)) return 0; /* Allowed if parent directory not sticky and world-writable. */ parent = nd->inode; if ((parent->i_mode & (S_ISVTX|S_IWOTH)) != (S_ISVTX|S_IWOTH)) return 0; /* Allowed if parent directory and link owner match. */ if (uid_eq(parent->i_uid, inode->i_uid)) return 0; if (nd->flags & LOOKUP_RCU) return -ECHILD; audit_log_link_denied("follow_link", &nd->stack[0].link); return -EACCES; } /** * safe_hardlink_source - Check for safe hardlink conditions * @inode: the source inode to hardlink from * * Return false if at least one of the following conditions: * - inode is not a regular file * - inode is setuid * - inode is setgid and group-exec * - access failure for read and write * * Otherwise returns true. */ static bool safe_hardlink_source(struct inode *inode) { umode_t mode = inode->i_mode; /* Special files should not get pinned to the filesystem. */ if (!S_ISREG(mode)) return false; /* Setuid files should not get pinned to the filesystem. */ if (mode & S_ISUID) return false; /* Executable setgid files should not get pinned to the filesystem. */ if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) return false; /* Hardlinking to unreadable or unwritable sources is dangerous. */ if (inode_permission(inode, MAY_READ | MAY_WRITE)) return false; return true; } /** * may_linkat - Check permissions for creating a hardlink * @link: the source to hardlink from * * Block hardlink when all of: * - sysctl_protected_hardlinks enabled * - fsuid does not match inode * - hardlink source is unsafe (see safe_hardlink_source() above) * - not CAP_FOWNER * * Returns 0 if successful, -ve on error. */ static int may_linkat(struct path *link) { const struct cred *cred; struct inode *inode; if (!sysctl_protected_hardlinks) return 0; cred = current_cred(); inode = link->dentry->d_inode; /* Source inode owner (or CAP_FOWNER) can hardlink all they like, * otherwise, it must be a safe source. */ if (uid_eq(cred->fsuid, inode->i_uid) || safe_hardlink_source(inode) || capable(CAP_FOWNER)) return 0; audit_log_link_denied("linkat", link); return -EPERM; } static __always_inline const char *get_link(struct nameidata *nd) { struct saved *last = nd->stack + nd->depth - 1; struct dentry *dentry = last->link.dentry; struct inode *inode = last->inode; int error; const char *res; if (!(nd->flags & LOOKUP_RCU)) { touch_atime(&last->link); cond_resched(); } else if (atime_needs_update(&last->link, inode)) { if (unlikely(unlazy_walk(nd, NULL, 0))) return ERR_PTR(-ECHILD); touch_atime(&last->link); } error = security_inode_follow_link(dentry, inode, nd->flags & LOOKUP_RCU); if (unlikely(error)) return ERR_PTR(error); nd->last_type = LAST_BIND; res = inode->i_link; if (!res) { if (nd->flags & LOOKUP_RCU) { if (unlikely(unlazy_walk(nd, NULL, 0))) return ERR_PTR(-ECHILD); } res = inode->i_op->follow_link(dentry, &last->cookie); if (IS_ERR_OR_NULL(res)) { last->cookie = NULL; return res; } } if (*res == '/') { if (nd->flags & LOOKUP_RCU) { struct dentry *d; if (!nd->root.mnt) set_root_rcu(nd); nd->path = nd->root; d = nd->path.dentry; nd->inode = d->d_inode; nd->seq = nd->root_seq; if (unlikely(read_seqcount_retry(&d->d_seq, nd->seq))) return ERR_PTR(-ECHILD); } else { if (!nd->root.mnt) set_root(nd); path_put(&nd->path); nd->path = nd->root; path_get(&nd->root); nd->inode = nd->path.dentry->d_inode; } nd->flags |= LOOKUP_JUMPED; while (unlikely(*++res == '/')) ; } if (!*res) res = NULL; return res; } /* * follow_up - Find the mountpoint of path's vfsmount * * Given a path, find the mountpoint of its source file system. * Replace @path with the path of the mountpoint in the parent mount. * Up is towards /. * * Return 1 if we went up a level and 0 if we were already at the * root. */ int follow_up(struct path *path) { struct mount *mnt = real_mount(path->mnt); struct mount *parent; struct dentry *mountpoint; read_seqlock_excl(&mount_lock); parent = mnt->mnt_parent; if (parent == mnt) { read_sequnlock_excl(&mount_lock); return 0; } mntget(&parent->mnt); mountpoint = dget(mnt->mnt_mountpoint); read_sequnlock_excl(&mount_lock); dput(path->dentry); path->dentry = mountpoint; mntput(path->mnt); path->mnt = &parent->mnt; return 1; } EXPORT_SYMBOL(follow_up); /* * Perform an automount * - return -EISDIR to tell follow_managed() to stop and return the path we * were called with. */ static int follow_automount(struct path *path, struct nameidata *nd, bool *need_mntput) { struct vfsmount *mnt; int err; if (!path->dentry->d_op || !path->dentry->d_op->d_automount) return -EREMOTE; /* We don't want to mount if someone's just doing a stat - * unless they're stat'ing a directory and appended a '/' to * the name. * * We do, however, want to mount if someone wants to open or * create a file of any type under the mountpoint, wants to * traverse through the mountpoint or wants to open the * mounted directory. Also, autofs may mark negative dentries * as being automount points. These will need the attentions * of the daemon to instantiate them before they can be used. */ if (!(nd->flags & (LOOKUP_PARENT | LOOKUP_DIRECTORY | LOOKUP_OPEN | LOOKUP_CREATE | LOOKUP_AUTOMOUNT)) && path->dentry->d_inode) return -EISDIR; nd->total_link_count++; if (nd->total_link_count >= 40) return -ELOOP; mnt = path->dentry->d_op->d_automount(path); if (IS_ERR(mnt)) { /* * The filesystem is allowed to return -EISDIR here to indicate * it doesn't want to automount. For instance, autofs would do * this so that its userspace daemon can mount on this dentry. * * However, we can only permit this if it's a terminal point in * the path being looked up; if it wasn't then the remainder of * the path is inaccessible and we should say so. */ if (PTR_ERR(mnt) == -EISDIR && (nd->flags & LOOKUP_PARENT)) return -EREMOTE; return PTR_ERR(mnt); } if (!mnt) /* mount collision */ return 0; if (!*need_mntput) { /* lock_mount() may release path->mnt on error */ mntget(path->mnt); *need_mntput = true; } err = finish_automount(mnt, path); switch (err) { case -EBUSY: /* Someone else made a mount here whilst we were busy */ return 0; case 0: path_put(path); path->mnt = mnt; path->dentry = dget(mnt->mnt_root); return 0; default: return err; } } /* * Handle a dentry that is managed in some way. * - Flagged for transit management (autofs) * - Flagged as mountpoint * - Flagged as automount point * * This may only be called in refwalk mode. * * Serialization is taken care of in namespace.c */ static int follow_managed(struct path *path, struct nameidata *nd) { struct vfsmount *mnt = path->mnt; /* held by caller, must be left alone */ unsigned managed; bool need_mntput = false; int ret = 0; /* Given that we're not holding a lock here, we retain the value in a * local variable for each dentry as we look at it so that we don't see * the components of that value change under us */ while (managed = ACCESS_ONCE(path->dentry->d_flags), managed &= DCACHE_MANAGED_DENTRY, unlikely(managed != 0)) { /* Allow the filesystem to manage the transit without i_mutex * being held. */ if (managed & DCACHE_MANAGE_TRANSIT) { BUG_ON(!path->dentry->d_op); BUG_ON(!path->dentry->d_op->d_manage); ret = path->dentry->d_op->d_manage(path->dentry, false); if (ret < 0) break; } /* Transit to a mounted filesystem. */ if (managed & DCACHE_MOUNTED) { struct vfsmount *mounted = lookup_mnt(path); if (mounted) { dput(path->dentry); if (need_mntput) mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); need_mntput = true; continue; } /* Something is mounted on this dentry in another * namespace and/or whatever was mounted there in this * namespace got unmounted before lookup_mnt() could * get it */ } /* Handle an automount point */ if (managed & DCACHE_NEED_AUTOMOUNT) { ret = follow_automount(path, nd, &need_mntput); if (ret < 0) break; continue; } /* We didn't change the current path point */ break; } if (need_mntput && path->mnt == mnt) mntput(path->mnt); if (ret == -EISDIR) ret = 0; if (need_mntput) nd->flags |= LOOKUP_JUMPED; if (unlikely(ret < 0)) path_put_conditional(path, nd); return ret; } int follow_down_one(struct path *path) { struct vfsmount *mounted; mounted = lookup_mnt(path); if (mounted) { dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); return 1; } return 0; } EXPORT_SYMBOL(follow_down_one); static inline int managed_dentry_rcu(struct dentry *dentry) { return (dentry->d_flags & DCACHE_MANAGE_TRANSIT) ? dentry->d_op->d_manage(dentry, true) : 0; } /* * Try to skip to top of mountpoint pile in rcuwalk mode. Fail if * we meet a managed dentry that would need blocking. */ static bool __follow_mount_rcu(struct nameidata *nd, struct path *path, struct inode **inode, unsigned *seqp) { for (;;) { struct mount *mounted; /* * Don't forget we might have a non-mountpoint managed dentry * that wants to block transit. */ switch (managed_dentry_rcu(path->dentry)) { case -ECHILD: default: return false; case -EISDIR: return true; case 0: break; } if (!d_mountpoint(path->dentry)) return !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT); mounted = __lookup_mnt(path->mnt, path->dentry); if (!mounted) break; path->mnt = &mounted->mnt; path->dentry = mounted->mnt.mnt_root; nd->flags |= LOOKUP_JUMPED; *seqp = read_seqcount_begin(&path->dentry->d_seq); /* * Update the inode too. We don't need to re-check the * dentry sequence number here after this d_inode read, * because a mount-point is always pinned. */ *inode = path->dentry->d_inode; } return !read_seqretry(&mount_lock, nd->m_seq) && !(path->dentry->d_flags & DCACHE_NEED_AUTOMOUNT); } static int follow_dotdot_rcu(struct nameidata *nd) { struct inode *inode = nd->inode; if (!nd->root.mnt) set_root_rcu(nd); while (1) { if (path_equal(&nd->path, &nd->root)) break; if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; inode = parent->d_inode; seq = read_seqcount_begin(&parent->d_seq); if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq))) return -ECHILD; nd->path.dentry = parent; nd->seq = seq; if (unlikely(!path_connected(&nd->path))) return -ENOENT; break; } else { struct mount *mnt = real_mount(nd->path.mnt); struct mount *mparent = mnt->mnt_parent; struct dentry *mountpoint = mnt->mnt_mountpoint; struct inode *inode2 = mountpoint->d_inode; unsigned seq = read_seqcount_begin(&mountpoint->d_seq); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (&mparent->mnt == nd->path.mnt) break; /* we know that mountpoint was pinned */ nd->path.dentry = mountpoint; nd->path.mnt = &mparent->mnt; inode = inode2; nd->seq = seq; } } while (unlikely(d_mountpoint(nd->path.dentry))) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } nd->inode = inode; return 0; } /* * Follow down to the covering mount currently visible to userspace. At each * point, the filesystem owning that dentry may be queried as to whether the * caller is permitted to proceed or not. */ int follow_down(struct path *path) { unsigned managed; int ret; while (managed = ACCESS_ONCE(path->dentry->d_flags), unlikely(managed & DCACHE_MANAGED_DENTRY)) { /* Allow the filesystem to manage the transit without i_mutex * being held. * * We indicate to the filesystem if someone is trying to mount * something here. This gives autofs the chance to deny anyone * other than its daemon the right to mount on its * superstructure. * * The filesystem may sleep at this point. */ if (managed & DCACHE_MANAGE_TRANSIT) { BUG_ON(!path->dentry->d_op); BUG_ON(!path->dentry->d_op->d_manage); ret = path->dentry->d_op->d_manage( path->dentry, false); if (ret < 0) return ret == -EISDIR ? 0 : ret; } /* Transit to a mounted filesystem. */ if (managed & DCACHE_MOUNTED) { struct vfsmount *mounted = lookup_mnt(path); if (!mounted) break; dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); continue; } /* Don't handle automount points here */ break; } return 0; } EXPORT_SYMBOL(follow_down); /* * Skip to top of mountpoint pile in refwalk mode for follow_dotdot() */ static void follow_mount(struct path *path) { while (d_mountpoint(path->dentry)) { struct vfsmount *mounted = lookup_mnt(path); if (!mounted) break; dput(path->dentry); mntput(path->mnt); path->mnt = mounted; path->dentry = dget(mounted->mnt_root); } } static int follow_dotdot(struct nameidata *nd) { if (!nd->root.mnt) set_root(nd); while(1) { struct dentry *old = nd->path.dentry; if (nd->path.dentry == nd->root.dentry && nd->path.mnt == nd->root.mnt) { break; } if (nd->path.dentry != nd->path.mnt->mnt_root) { /* rare case of legitimate dget_parent()... */ nd->path.dentry = dget_parent(nd->path.dentry); dput(old); if (unlikely(!path_connected(&nd->path))) return -ENOENT; break; } if (!follow_up(&nd->path)) break; } follow_mount(&nd->path); nd->inode = nd->path.dentry->d_inode; return 0; } /* * This looks up the name in dcache, possibly revalidates the old dentry and * allocates a new one if not found or not valid. In the need_lookup argument * returns whether i_op->lookup is necessary. * * dir->d_inode->i_mutex must be held */ static struct dentry *lookup_dcache(struct qstr *name, struct dentry *dir, unsigned int flags, bool *need_lookup) { struct dentry *dentry; int error; *need_lookup = false; dentry = d_lookup(dir, name); if (dentry) { if (dentry->d_flags & DCACHE_OP_REVALIDATE) { error = d_revalidate(dentry, flags); if (unlikely(error <= 0)) { if (error < 0) { dput(dentry); return ERR_PTR(error); } else { d_invalidate(dentry); dput(dentry); dentry = NULL; } } } } if (!dentry) { dentry = d_alloc(dir, name); if (unlikely(!dentry)) return ERR_PTR(-ENOMEM); *need_lookup = true; } return dentry; } /* * Call i_op->lookup on the dentry. The dentry must be negative and * unhashed. * * dir->d_inode->i_mutex must be held */ static struct dentry *lookup_real(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct dentry *old; /* Don't create child dentry for a dead directory. */ if (unlikely(IS_DEADDIR(dir))) { dput(dentry); return ERR_PTR(-ENOENT); } old = dir->i_op->lookup(dir, dentry, flags); if (unlikely(old)) { dput(dentry); dentry = old; } return dentry; } static struct dentry *__lookup_hash(struct qstr *name, struct dentry *base, unsigned int flags) { bool need_lookup; struct dentry *dentry; dentry = lookup_dcache(name, base, flags, &need_lookup); if (!need_lookup) return dentry; return lookup_real(base->d_inode, dentry, flags); } /* * It's more convoluted than I'd like it to be, but... it's still fairly * small and for now I'd prefer to have fast path as straight as possible. * It _is_ time-critical. */ static int lookup_fast(struct nameidata *nd, struct path *path, struct inode **inode, unsigned *seqp) { struct vfsmount *mnt = nd->path.mnt; struct dentry *dentry, *parent = nd->path.dentry; int need_reval = 1; int status = 1; int err; /* * Rename seqlock is not required here because in the off chance * of a false negative due to a concurrent rename, we're going to * do the non-racy lookup, below. */ if (nd->flags & LOOKUP_RCU) { unsigned seq; bool negative; dentry = __d_lookup_rcu(parent, &nd->last, &seq); if (!dentry) goto unlazy; /* * This sequence count validates that the inode matches * the dentry name information from lookup. */ *inode = d_backing_inode(dentry); negative = d_is_negative(dentry); if (read_seqcount_retry(&dentry->d_seq, seq)) return -ECHILD; if (negative) return -ENOENT; /* * This sequence count validates that the parent had no * changes while we did the lookup of the dentry above. * * The memory barrier in read_seqcount_begin of child is * enough, we can use __read_seqcount_retry here. */ if (__read_seqcount_retry(&parent->d_seq, nd->seq)) return -ECHILD; *seqp = seq; if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE)) { status = d_revalidate(dentry, nd->flags); if (unlikely(status <= 0)) { if (status != -ECHILD) need_reval = 0; goto unlazy; } } path->mnt = mnt; path->dentry = dentry; if (likely(__follow_mount_rcu(nd, path, inode, seqp))) return 0; unlazy: if (unlazy_walk(nd, dentry, seq)) return -ECHILD; } else { dentry = __d_lookup(parent, &nd->last); } if (unlikely(!dentry)) goto need_lookup; if (unlikely(dentry->d_flags & DCACHE_OP_REVALIDATE) && need_reval) status = d_revalidate(dentry, nd->flags); if (unlikely(status <= 0)) { if (status < 0) { dput(dentry); return status; } d_invalidate(dentry); dput(dentry); goto need_lookup; } if (unlikely(d_is_negative(dentry))) { dput(dentry); return -ENOENT; } path->mnt = mnt; path->dentry = dentry; err = follow_managed(path, nd); if (likely(!err)) *inode = d_backing_inode(path->dentry); return err; need_lookup: return 1; } /* Fast lookup failed, do it the slow way */ static int lookup_slow(struct nameidata *nd, struct path *path) { struct dentry *dentry, *parent; parent = nd->path.dentry; BUG_ON(nd->inode != parent->d_inode); mutex_lock(&parent->d_inode->i_mutex); dentry = __lookup_hash(&nd->last, parent, nd->flags); mutex_unlock(&parent->d_inode->i_mutex); if (IS_ERR(dentry)) return PTR_ERR(dentry); path->mnt = nd->path.mnt; path->dentry = dentry; return follow_managed(path, nd); } static inline int may_lookup(struct nameidata *nd) { if (nd->flags & LOOKUP_RCU) { int err = inode_permission(nd->inode, MAY_EXEC|MAY_NOT_BLOCK); if (err != -ECHILD) return err; if (unlazy_walk(nd, NULL, 0)) return -ECHILD; } return inode_permission(nd->inode, MAY_EXEC); } static inline int handle_dots(struct nameidata *nd, int type) { if (type == LAST_DOTDOT) { if (nd->flags & LOOKUP_RCU) { return follow_dotdot_rcu(nd); } else return follow_dotdot(nd); } return 0; } static int pick_link(struct nameidata *nd, struct path *link, struct inode *inode, unsigned seq) { int error; struct saved *last; if (unlikely(nd->total_link_count++ >= MAXSYMLINKS)) { path_to_nameidata(link, nd); return -ELOOP; } if (!(nd->flags & LOOKUP_RCU)) { if (link->mnt == nd->path.mnt) mntget(link->mnt); } error = nd_alloc_stack(nd); if (unlikely(error)) { if (error == -ECHILD) { if (unlikely(unlazy_link(nd, link, seq))) return -ECHILD; error = nd_alloc_stack(nd); } if (error) { path_put(link); return error; } } last = nd->stack + nd->depth++; last->link = *link; last->cookie = NULL; last->inode = inode; last->seq = seq; return 1; } /* * Do we need to follow links? We _really_ want to be able * to do this check without having to look at inode->i_op, * so we keep a cache of "no, this doesn't need follow_link" * for the common case. */ static inline int should_follow_link(struct nameidata *nd, struct path *link, int follow, struct inode *inode, unsigned seq) { if (likely(!d_is_symlink(link->dentry))) return 0; if (!follow) return 0; return pick_link(nd, link, inode, seq); } enum {WALK_GET = 1, WALK_PUT = 2}; static int walk_component(struct nameidata *nd, int flags) { struct path path; struct inode *inode; unsigned seq; int err; /* * "." and ".." are special - ".." especially so because it has * to be able to know about the current root directory and * parent relationships. */ if (unlikely(nd->last_type != LAST_NORM)) { err = handle_dots(nd, nd->last_type); if (flags & WALK_PUT) put_link(nd); return err; } err = lookup_fast(nd, &path, &inode, &seq); if (unlikely(err)) { if (err < 0) return err; err = lookup_slow(nd, &path); if (err < 0) return err; inode = d_backing_inode(path.dentry); seq = 0; /* we are already out of RCU mode */ err = -ENOENT; if (d_is_negative(path.dentry)) goto out_path_put; } if (flags & WALK_PUT) put_link(nd); err = should_follow_link(nd, &path, flags & WALK_GET, inode, seq); if (unlikely(err)) return err; path_to_nameidata(&path, nd); nd->inode = inode; nd->seq = seq; return 0; out_path_put: path_to_nameidata(&path, nd); return err; } /* * We can do the critical dentry name comparison and hashing * operations one word at a time, but we are limited to: * * - Architectures with fast unaligned word accesses. We could * do a "get_unaligned()" if this helps and is sufficiently * fast. * * - non-CONFIG_DEBUG_PAGEALLOC configurations (so that we * do not trap on the (extremely unlikely) case of a page * crossing operation. * * - Furthermore, we need an efficient 64-bit compile for the * 64-bit case in order to generate the "number of bytes in * the final mask". Again, that could be replaced with a * efficient population count instruction or similar. */ #ifdef CONFIG_DCACHE_WORD_ACCESS #include <asm/word-at-a-time.h> #ifdef CONFIG_64BIT static inline unsigned int fold_hash(unsigned long hash) { return hash_64(hash, 32); } #else /* 32-bit case */ #define fold_hash(x) (x) #endif unsigned int full_name_hash(const unsigned char *name, unsigned int len) { unsigned long a, mask; unsigned long hash = 0; for (;;) { a = load_unaligned_zeropad(name); if (len < sizeof(unsigned long)) break; hash += a; hash *= 9; name += sizeof(unsigned long); len -= sizeof(unsigned long); if (!len) goto done; } mask = bytemask_from_count(len); hash += mask & a; done: return fold_hash(hash); } EXPORT_SYMBOL(full_name_hash); /* * Calculate the length and hash of the path component, and * return the "hash_len" as the result. */ static inline u64 hash_name(const char *name) { unsigned long a, b, adata, bdata, mask, hash, len; const struct word_at_a_time constants = WORD_AT_A_TIME_CONSTANTS; hash = a = 0; len = -sizeof(unsigned long); do { hash = (hash + a) * 9; len += sizeof(unsigned long); a = load_unaligned_zeropad(name+len); b = a ^ REPEAT_BYTE('/'); } while (!(has_zero(a, &adata, &constants) | has_zero(b, &bdata, &constants))); adata = prep_zero_mask(a, adata, &constants); bdata = prep_zero_mask(b, bdata, &constants); mask = create_zero_mask(adata | bdata); hash += a & zero_bytemask(mask); len += find_zero(mask); return hashlen_create(fold_hash(hash), len); } #else unsigned int full_name_hash(const unsigned char *name, unsigned int len) { unsigned long hash = init_name_hash(); while (len--) hash = partial_name_hash(*name++, hash); return end_name_hash(hash); } EXPORT_SYMBOL(full_name_hash); /* * We know there's a real path component here of at least * one character. */ static inline u64 hash_name(const char *name) { unsigned long hash = init_name_hash(); unsigned long len = 0, c; c = (unsigned char)*name; do { len++; hash = partial_name_hash(c, hash); c = (unsigned char)name[len]; } while (c && c != '/'); return hashlen_create(end_name_hash(hash), len); } #endif /* * Name resolution. * This is the basic name resolution function, turning a pathname into * the final dentry. We expect 'base' to be positive and a directory. * * Returns 0 and nd will have valid dentry and mnt on success. * Returns error and drops reference to input namei data on failure. */ static int link_path_walk(const char *name, struct nameidata *nd) { int err; while (*name=='/') name++; if (!*name) return 0; /* At this point we know we have a real path component. */ for(;;) { u64 hash_len; int type; err = may_lookup(nd); if (err) return err; hash_len = hash_name(name); type = LAST_NORM; if (name[0] == '.') switch (hashlen_len(hash_len)) { case 2: if (name[1] == '.') { type = LAST_DOTDOT; nd->flags |= LOOKUP_JUMPED; } break; case 1: type = LAST_DOT; } if (likely(type == LAST_NORM)) { struct dentry *parent = nd->path.dentry; nd->flags &= ~LOOKUP_JUMPED; if (unlikely(parent->d_flags & DCACHE_OP_HASH)) { struct qstr this = { { .hash_len = hash_len }, .name = name }; err = parent->d_op->d_hash(parent, &this); if (err < 0) return err; hash_len = this.hash_len; name = this.name; } } nd->last.hash_len = hash_len; nd->last.name = name; nd->last_type = type; name += hashlen_len(hash_len); if (!*name) goto OK; /* * If it wasn't NUL, we know it was '/'. Skip that * slash, and continue until no more slashes. */ do { name++; } while (unlikely(*name == '/')); if (unlikely(!*name)) { OK: /* pathname body, done */ if (!nd->depth) return 0; name = nd->stack[nd->depth - 1].name; /* trailing symlink, done */ if (!name) return 0; /* last component of nested symlink */ err = walk_component(nd, WALK_GET | WALK_PUT); } else { err = walk_component(nd, WALK_GET); } if (err < 0) return err; if (err) { const char *s = get_link(nd); if (unlikely(IS_ERR(s))) return PTR_ERR(s); err = 0; if (unlikely(!s)) { /* jumped */ put_link(nd); } else { nd->stack[nd->depth - 1].name = name; name = s; continue; } } if (unlikely(!d_can_lookup(nd->path.dentry))) { if (nd->flags & LOOKUP_RCU) { if (unlazy_walk(nd, NULL, 0)) return -ECHILD; } return -ENOTDIR; } } } static const char *path_init(struct nameidata *nd, unsigned flags) { int retval = 0; const char *s = nd->name->name; nd->last_type = LAST_ROOT; /* if there are only slashes... */ nd->flags = flags | LOOKUP_JUMPED | LOOKUP_PARENT; nd->depth = 0; nd->total_link_count = 0; if (flags & LOOKUP_ROOT) { struct dentry *root = nd->root.dentry; struct inode *inode = root->d_inode; if (*s) { if (!d_can_lookup(root)) return ERR_PTR(-ENOTDIR); retval = inode_permission(inode, MAY_EXEC); if (retval) return ERR_PTR(retval); } nd->path = nd->root; nd->inode = inode; if (flags & LOOKUP_RCU) { rcu_read_lock(); nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); nd->root_seq = nd->seq; nd->m_seq = read_seqbegin(&mount_lock); } else { path_get(&nd->path); } return s; } nd->root.mnt = NULL; nd->m_seq = read_seqbegin(&mount_lock); if (*s == '/') { if (flags & LOOKUP_RCU) { rcu_read_lock(); set_root_rcu(nd); nd->seq = nd->root_seq; } else { set_root(nd); path_get(&nd->root); } nd->path = nd->root; } else if (nd->dfd == AT_FDCWD) { if (flags & LOOKUP_RCU) { struct fs_struct *fs = current->fs; unsigned seq; rcu_read_lock(); do { seq = read_seqcount_begin(&fs->seq); nd->path = fs->pwd; nd->seq = __read_seqcount_begin(&nd->path.dentry->d_seq); } while (read_seqcount_retry(&fs->seq, seq)); } else { get_fs_pwd(current->fs, &nd->path); } } else { /* Caller must check execute permissions on the starting path component */ struct fd f = fdget_raw(nd->dfd); struct dentry *dentry; if (!f.file) return ERR_PTR(-EBADF); dentry = f.file->f_path.dentry; if (*s) { if (!d_can_lookup(dentry)) { fdput(f); return ERR_PTR(-ENOTDIR); } } nd->path = f.file->f_path; if (flags & LOOKUP_RCU) { rcu_read_lock(); nd->inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } else { path_get(&nd->path); nd->inode = nd->path.dentry->d_inode; } fdput(f); return s; } nd->inode = nd->path.dentry->d_inode; if (!(flags & LOOKUP_RCU)) return s; if (likely(!read_seqcount_retry(&nd->path.dentry->d_seq, nd->seq))) return s; if (!(nd->flags & LOOKUP_ROOT)) nd->root.mnt = NULL; rcu_read_unlock(); return ERR_PTR(-ECHILD); } static const char *trailing_symlink(struct nameidata *nd) { const char *s; int error = may_follow_link(nd); if (unlikely(error)) return ERR_PTR(error); nd->flags |= LOOKUP_PARENT; nd->stack[0].name = NULL; s = get_link(nd); return s ? s : ""; } static inline int lookup_last(struct nameidata *nd) { if (nd->last_type == LAST_NORM && nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; nd->flags &= ~LOOKUP_PARENT; return walk_component(nd, nd->flags & LOOKUP_FOLLOW ? nd->depth ? WALK_PUT | WALK_GET : WALK_GET : 0); } /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */ static int path_lookupat(struct nameidata *nd, unsigned flags, struct path *path) { const char *s = path_init(nd, flags); int err; if (IS_ERR(s)) return PTR_ERR(s); while (!(err = link_path_walk(s, nd)) && ((err = lookup_last(nd)) > 0)) { s = trailing_symlink(nd); if (IS_ERR(s)) { err = PTR_ERR(s); break; } } if (!err) err = complete_walk(nd); if (!err && nd->flags & LOOKUP_DIRECTORY) if (!d_can_lookup(nd->path.dentry)) err = -ENOTDIR; if (!err) { *path = nd->path; nd->path.mnt = NULL; nd->path.dentry = NULL; } terminate_walk(nd); return err; } static int filename_lookup(int dfd, struct filename *name, unsigned flags, struct path *path, struct path *root) { int retval; struct nameidata nd; if (IS_ERR(name)) return PTR_ERR(name); if (unlikely(root)) { nd.root = *root; flags |= LOOKUP_ROOT; } set_nameidata(&nd, dfd, name); retval = path_lookupat(&nd, flags | LOOKUP_RCU, path); if (unlikely(retval == -ECHILD)) retval = path_lookupat(&nd, flags, path); if (unlikely(retval == -ESTALE)) retval = path_lookupat(&nd, flags | LOOKUP_REVAL, path); if (likely(!retval)) audit_inode(name, path->dentry, flags & LOOKUP_PARENT); restore_nameidata(); putname(name); return retval; } /* Returns 0 and nd will be valid on success; Retuns error, otherwise. */ static int path_parentat(struct nameidata *nd, unsigned flags, struct path *parent) { const char *s = path_init(nd, flags); int err; if (IS_ERR(s)) return PTR_ERR(s); err = link_path_walk(s, nd); if (!err) err = complete_walk(nd); if (!err) { *parent = nd->path; nd->path.mnt = NULL; nd->path.dentry = NULL; } terminate_walk(nd); return err; } static struct filename *filename_parentat(int dfd, struct filename *name, unsigned int flags, struct path *parent, struct qstr *last, int *type) { int retval; struct nameidata nd; if (IS_ERR(name)) return name; set_nameidata(&nd, dfd, name); retval = path_parentat(&nd, flags | LOOKUP_RCU, parent); if (unlikely(retval == -ECHILD)) retval = path_parentat(&nd, flags, parent); if (unlikely(retval == -ESTALE)) retval = path_parentat(&nd, flags | LOOKUP_REVAL, parent); if (likely(!retval)) { *last = nd.last; *type = nd.last_type; audit_inode(name, parent->dentry, LOOKUP_PARENT); } else { putname(name); name = ERR_PTR(retval); } restore_nameidata(); return name; } /* does lookup, returns the object with parent locked */ struct dentry *kern_path_locked(const char *name, struct path *path) { struct filename *filename; struct dentry *d; struct qstr last; int type; filename = filename_parentat(AT_FDCWD, getname_kernel(name), 0, path, &last, &type); if (IS_ERR(filename)) return ERR_CAST(filename); if (unlikely(type != LAST_NORM)) { path_put(path); putname(filename); return ERR_PTR(-EINVAL); } mutex_lock_nested(&path->dentry->d_inode->i_mutex, I_MUTEX_PARENT); d = __lookup_hash(&last, path->dentry, 0); if (IS_ERR(d)) { mutex_unlock(&path->dentry->d_inode->i_mutex); path_put(path); } putname(filename); return d; } int kern_path(const char *name, unsigned int flags, struct path *path) { return filename_lookup(AT_FDCWD, getname_kernel(name), flags, path, NULL); } EXPORT_SYMBOL(kern_path); /** * vfs_path_lookup - lookup a file path relative to a dentry-vfsmount pair * @dentry: pointer to dentry of the base directory * @mnt: pointer to vfs mount of the base directory * @name: pointer to file name * @flags: lookup flags * @path: pointer to struct path to fill */ int vfs_path_lookup(struct dentry *dentry, struct vfsmount *mnt, const char *name, unsigned int flags, struct path *path) { struct path root = {.mnt = mnt, .dentry = dentry}; /* the first argument of filename_lookup() is ignored with root */ return filename_lookup(AT_FDCWD, getname_kernel(name), flags , path, &root); } EXPORT_SYMBOL(vfs_path_lookup); /** * lookup_one_len - filesystem helper to lookup single pathname component * @name: pathname component to lookup * @base: base directory to lookup from * @len: maximum length @len should be interpreted to * * Note that this routine is purely a helper for filesystem usage and should * not be called by generic code. */ struct dentry *lookup_one_len(const char *name, struct dentry *base, int len) { struct qstr this; unsigned int c; int err; WARN_ON_ONCE(!mutex_is_locked(&base->d_inode->i_mutex)); this.name = name; this.len = len; this.hash = full_name_hash(name, len); if (!len) return ERR_PTR(-EACCES); if (unlikely(name[0] == '.')) { if (len < 2 || (len == 2 && name[1] == '.')) return ERR_PTR(-EACCES); } while (len--) { c = *(const unsigned char *)name++; if (c == '/' || c == '\0') return ERR_PTR(-EACCES); } /* * See if the low-level filesystem might want * to use its own hash.. */ if (base->d_flags & DCACHE_OP_HASH) { int err = base->d_op->d_hash(base, &this); if (err < 0) return ERR_PTR(err); } err = inode_permission(base->d_inode, MAY_EXEC); if (err) return ERR_PTR(err); return __lookup_hash(&this, base, 0); } EXPORT_SYMBOL(lookup_one_len); int user_path_at_empty(int dfd, const char __user *name, unsigned flags, struct path *path, int *empty) { return filename_lookup(dfd, getname_flags(name, flags, empty), flags, path, NULL); } EXPORT_SYMBOL(user_path_at_empty); /* * NB: most callers don't do anything directly with the reference to the * to struct filename, but the nd->last pointer points into the name string * allocated by getname. So we must hold the reference to it until all * path-walking is complete. */ static inline struct filename * user_path_parent(int dfd, const char __user *path, struct path *parent, struct qstr *last, int *type, unsigned int flags) { /* only LOOKUP_REVAL is allowed in extra flags */ return filename_parentat(dfd, getname(path), flags & LOOKUP_REVAL, parent, last, type); } /** * mountpoint_last - look up last component for umount * @nd: pathwalk nameidata - currently pointing at parent directory of "last" * @path: pointer to container for result * * This is a special lookup_last function just for umount. In this case, we * need to resolve the path without doing any revalidation. * * The nameidata should be the result of doing a LOOKUP_PARENT pathwalk. Since * mountpoints are always pinned in the dcache, their ancestors are too. Thus, * in almost all cases, this lookup will be served out of the dcache. The only * cases where it won't are if nd->last refers to a symlink or the path is * bogus and it doesn't exist. * * Returns: * -error: if there was an error during lookup. This includes -ENOENT if the * lookup found a negative dentry. The nd->path reference will also be * put in this case. * * 0: if we successfully resolved nd->path and found it to not to be a * symlink that needs to be followed. "path" will also be populated. * The nd->path reference will also be put. * * 1: if we successfully resolved nd->last and found it to be a symlink * that needs to be followed. "path" will be populated with the path * to the link, and nd->path will *not* be put. */ static int mountpoint_last(struct nameidata *nd, struct path *path) { int error = 0; struct dentry *dentry; struct dentry *dir = nd->path.dentry; /* If we're in rcuwalk, drop out of it to handle last component */ if (nd->flags & LOOKUP_RCU) { if (unlazy_walk(nd, NULL, 0)) return -ECHILD; } nd->flags &= ~LOOKUP_PARENT; if (unlikely(nd->last_type != LAST_NORM)) { error = handle_dots(nd, nd->last_type); if (error) return error; dentry = dget(nd->path.dentry); goto done; } mutex_lock(&dir->d_inode->i_mutex); dentry = d_lookup(dir, &nd->last); if (!dentry) { /* * No cached dentry. Mounted dentries are pinned in the cache, * so that means that this dentry is probably a symlink or the * path doesn't actually point to a mounted dentry. */ dentry = d_alloc(dir, &nd->last); if (!dentry) { mutex_unlock(&dir->d_inode->i_mutex); return -ENOMEM; } dentry = lookup_real(dir->d_inode, dentry, nd->flags); if (IS_ERR(dentry)) { mutex_unlock(&dir->d_inode->i_mutex); return PTR_ERR(dentry); } } mutex_unlock(&dir->d_inode->i_mutex); done: if (d_is_negative(dentry)) { dput(dentry); return -ENOENT; } if (nd->depth) put_link(nd); path->dentry = dentry; path->mnt = nd->path.mnt; error = should_follow_link(nd, path, nd->flags & LOOKUP_FOLLOW, d_backing_inode(dentry), 0); if (unlikely(error)) return error; mntget(path->mnt); follow_mount(path); return 0; } /** * path_mountpoint - look up a path to be umounted * @nameidata: lookup context * @flags: lookup flags * @path: pointer to container for result * * Look up the given name, but don't attempt to revalidate the last component. * Returns 0 and "path" will be valid on success; Returns error otherwise. */ static int path_mountpoint(struct nameidata *nd, unsigned flags, struct path *path) { const char *s = path_init(nd, flags); int err; if (IS_ERR(s)) return PTR_ERR(s); while (!(err = link_path_walk(s, nd)) && (err = mountpoint_last(nd, path)) > 0) { s = trailing_symlink(nd); if (IS_ERR(s)) { err = PTR_ERR(s); break; } } terminate_walk(nd); return err; } static int filename_mountpoint(int dfd, struct filename *name, struct path *path, unsigned int flags) { struct nameidata nd; int error; if (IS_ERR(name)) return PTR_ERR(name); set_nameidata(&nd, dfd, name); error = path_mountpoint(&nd, flags | LOOKUP_RCU, path); if (unlikely(error == -ECHILD)) error = path_mountpoint(&nd, flags, path); if (unlikely(error == -ESTALE)) error = path_mountpoint(&nd, flags | LOOKUP_REVAL, path); if (likely(!error)) audit_inode(name, path->dentry, 0); restore_nameidata(); putname(name); return error; } /** * user_path_mountpoint_at - lookup a path from userland in order to umount it * @dfd: directory file descriptor * @name: pathname from userland * @flags: lookup flags * @path: pointer to container to hold result * * A umount is a special case for path walking. We're not actually interested * in the inode in this situation, and ESTALE errors can be a problem. We * simply want track down the dentry and vfsmount attached at the mountpoint * and avoid revalidating the last component. * * Returns 0 and populates "path" on success. */ int user_path_mountpoint_at(int dfd, const char __user *name, unsigned int flags, struct path *path) { return filename_mountpoint(dfd, getname(name), path, flags); } int kern_path_mountpoint(int dfd, const char *name, struct path *path, unsigned int flags) { return filename_mountpoint(dfd, getname_kernel(name), path, flags); } EXPORT_SYMBOL(kern_path_mountpoint); int __check_sticky(struct inode *dir, struct inode *inode) { kuid_t fsuid = current_fsuid(); if (uid_eq(inode->i_uid, fsuid)) return 0; if (uid_eq(dir->i_uid, fsuid)) return 0; return !capable_wrt_inode_uidgid(inode, CAP_FOWNER); } EXPORT_SYMBOL(__check_sticky); /* * Check whether we can remove a link victim from directory dir, check * whether the type of victim is right. * 1. We can't do it if dir is read-only (done in permission()) * 2. We should have write and exec permissions on dir * 3. We can't remove anything from append-only dir * 4. We can't do anything with immutable dir (done in permission()) * 5. If the sticky bit on dir is set we should either * a. be owner of dir, or * b. be owner of victim, or * c. have CAP_FOWNER capability * 6. If the victim is append-only or immutable we can't do antyhing with * links pointing to it. * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR. * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR. * 9. We can't remove a root or mountpoint. * 10. We don't allow removal of NFS sillyrenamed files; it's handled by * nfs_async_unlink(). */ static int may_delete(struct inode *dir, struct dentry *victim, bool isdir) { struct inode *inode = d_backing_inode(victim); int error; if (d_is_negative(victim)) return -ENOENT; BUG_ON(!inode); BUG_ON(victim->d_parent->d_inode != dir); audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE); error = inode_permission(dir, MAY_WRITE | MAY_EXEC); if (error) return error; if (IS_APPEND(dir)) return -EPERM; if (check_sticky(dir, inode) || IS_APPEND(inode) || IS_IMMUTABLE(inode) || IS_SWAPFILE(inode)) return -EPERM; if (isdir) { if (!d_is_dir(victim)) return -ENOTDIR; if (IS_ROOT(victim)) return -EBUSY; } else if (d_is_dir(victim)) return -EISDIR; if (IS_DEADDIR(dir)) return -ENOENT; if (victim->d_flags & DCACHE_NFSFS_RENAMED) return -EBUSY; return 0; } /* Check whether we can create an object with dentry child in directory * dir. * 1. We can't do it if child already exists (open has special treatment for * this case, but since we are inlined it's OK) * 2. We can't do it if dir is read-only (done in permission()) * 3. We should have write and exec permissions on dir * 4. We can't do it if dir is immutable (done in permission()) */ static inline int may_create(struct inode *dir, struct dentry *child) { audit_inode_child(dir, child, AUDIT_TYPE_CHILD_CREATE); if (child->d_inode) return -EEXIST; if (IS_DEADDIR(dir)) return -ENOENT; return inode_permission(dir, MAY_WRITE | MAY_EXEC); } /* * p1 and p2 should be directories on the same fs. */ struct dentry *lock_rename(struct dentry *p1, struct dentry *p2) { struct dentry *p; if (p1 == p2) { mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); return NULL; } mutex_lock(&p1->d_inode->i_sb->s_vfs_rename_mutex); p = d_ancestor(p2, p1); if (p) { mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_CHILD); return p; } p = d_ancestor(p1, p2); if (p) { mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_CHILD); return p; } mutex_lock_nested(&p1->d_inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&p2->d_inode->i_mutex, I_MUTEX_PARENT2); return NULL; } EXPORT_SYMBOL(lock_rename); void unlock_rename(struct dentry *p1, struct dentry *p2) { mutex_unlock(&p1->d_inode->i_mutex); if (p1 != p2) { mutex_unlock(&p2->d_inode->i_mutex); mutex_unlock(&p1->d_inode->i_sb->s_vfs_rename_mutex); } } EXPORT_SYMBOL(unlock_rename); int vfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool want_excl) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->create) return -EACCES; /* shouldn't it be ENOSYS? */ mode &= S_IALLUGO; mode |= S_IFREG; error = security_inode_create(dir, dentry, mode); if (error) return error; error = dir->i_op->create(dir, dentry, mode, want_excl); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_create); static int may_open(struct path *path, int acc_mode, int flag) { struct dentry *dentry = path->dentry; struct inode *inode = dentry->d_inode; int error; /* O_PATH? */ if (!acc_mode) return 0; if (!inode) return -ENOENT; switch (inode->i_mode & S_IFMT) { case S_IFLNK: return -ELOOP; case S_IFDIR: if (acc_mode & MAY_WRITE) return -EISDIR; break; case S_IFBLK: case S_IFCHR: if (path->mnt->mnt_flags & MNT_NODEV) return -EACCES; /*FALLTHRU*/ case S_IFIFO: case S_IFSOCK: flag &= ~O_TRUNC; break; } error = inode_permission(inode, acc_mode); if (error) return error; /* * An append-only file must be opened in append mode for writing. */ if (IS_APPEND(inode)) { if ((flag & O_ACCMODE) != O_RDONLY && !(flag & O_APPEND)) return -EPERM; if (flag & O_TRUNC) return -EPERM; } /* O_NOATIME can only be set by the owner or superuser */ if (flag & O_NOATIME && !inode_owner_or_capable(inode)) return -EPERM; return 0; } static int handle_truncate(struct file *filp) { struct path *path = &filp->f_path; struct inode *inode = path->dentry->d_inode; int error = get_write_access(inode); if (error) return error; /* * Refuse to truncate files with mandatory locks held on them. */ error = locks_verify_locked(filp); if (!error) error = security_path_truncate(path); if (!error) { error = do_truncate(path->dentry, 0, ATTR_MTIME|ATTR_CTIME|ATTR_OPEN, filp); } put_write_access(inode); return error; } static inline int open_to_namei_flags(int flag) { if ((flag & O_ACCMODE) == 3) flag--; return flag; } static int may_o_create(struct path *dir, struct dentry *dentry, umode_t mode) { int error = security_path_mknod(dir, dentry, mode, 0); if (error) return error; error = inode_permission(dir->dentry->d_inode, MAY_WRITE | MAY_EXEC); if (error) return error; return security_inode_create(dir->dentry->d_inode, dentry, mode); } /* * Attempt to atomically look up, create and open a file from a negative * dentry. * * Returns 0 if successful. The file will have been created and attached to * @file by the filesystem calling finish_open(). * * Returns 1 if the file was looked up only or didn't need creating. The * caller will need to perform the open themselves. @path will have been * updated to point to the new dentry. This may be negative. * * Returns an error code otherwise. */ static int atomic_open(struct nameidata *nd, struct dentry *dentry, struct path *path, struct file *file, const struct open_flags *op, bool got_write, bool need_lookup, int *opened) { struct inode *dir = nd->path.dentry->d_inode; unsigned open_flag = open_to_namei_flags(op->open_flag); umode_t mode; int error; int acc_mode; int create_error = 0; struct dentry *const DENTRY_NOT_SET = (void *) -1UL; bool excl; BUG_ON(dentry->d_inode); /* Don't create child dentry for a dead directory. */ if (unlikely(IS_DEADDIR(dir))) { error = -ENOENT; goto out; } mode = op->mode; if ((open_flag & O_CREAT) && !IS_POSIXACL(dir)) mode &= ~current_umask(); excl = (open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT); if (excl) open_flag &= ~O_TRUNC; /* * Checking write permission is tricky, bacuse we don't know if we are * going to actually need it: O_CREAT opens should work as long as the * file exists. But checking existence breaks atomicity. The trick is * to check access and if not granted clear O_CREAT from the flags. * * Another problem is returing the "right" error value (e.g. for an * O_EXCL open we want to return EEXIST not EROFS). */ if (((open_flag & (O_CREAT | O_TRUNC)) || (open_flag & O_ACCMODE) != O_RDONLY) && unlikely(!got_write)) { if (!(open_flag & O_CREAT)) { /* * No O_CREATE -> atomicity not a requirement -> fall * back to lookup + open */ goto no_open; } else if (open_flag & (O_EXCL | O_TRUNC)) { /* Fall back and fail with the right error */ create_error = -EROFS; goto no_open; } else { /* No side effects, safe to clear O_CREAT */ create_error = -EROFS; open_flag &= ~O_CREAT; } } if (open_flag & O_CREAT) { error = may_o_create(&nd->path, dentry, mode); if (error) { create_error = error; if (open_flag & O_EXCL) goto no_open; open_flag &= ~O_CREAT; } } if (nd->flags & LOOKUP_DIRECTORY) open_flag |= O_DIRECTORY; file->f_path.dentry = DENTRY_NOT_SET; file->f_path.mnt = nd->path.mnt; error = dir->i_op->atomic_open(dir, dentry, file, open_flag, mode, opened); if (error < 0) { if (create_error && error == -ENOENT) error = create_error; goto out; } if (error) { /* returned 1, that is */ if (WARN_ON(file->f_path.dentry == DENTRY_NOT_SET)) { error = -EIO; goto out; } if (file->f_path.dentry) { dput(dentry); dentry = file->f_path.dentry; } if (*opened & FILE_CREATED) fsnotify_create(dir, dentry); if (!dentry->d_inode) { WARN_ON(*opened & FILE_CREATED); if (create_error) { error = create_error; goto out; } } else { if (excl && !(*opened & FILE_CREATED)) { error = -EEXIST; goto out; } } goto looked_up; } /* * We didn't have the inode before the open, so check open permission * here. */ acc_mode = op->acc_mode; if (*opened & FILE_CREATED) { WARN_ON(!(open_flag & O_CREAT)); fsnotify_create(dir, dentry); acc_mode = MAY_OPEN; } error = may_open(&file->f_path, acc_mode, open_flag); if (error) fput(file); out: dput(dentry); return error; no_open: if (need_lookup) { dentry = lookup_real(dir, dentry, nd->flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (create_error) { int open_flag = op->open_flag; error = create_error; if ((open_flag & O_EXCL)) { if (!dentry->d_inode) goto out; } else if (!dentry->d_inode) { goto out; } else if ((open_flag & O_TRUNC) && d_is_reg(dentry)) { goto out; } /* will fail later, go on to get the right error */ } } looked_up: path->dentry = dentry; path->mnt = nd->path.mnt; return 1; } /* * Look up and maybe create and open the last component. * * Must be called with i_mutex held on parent. * * Returns 0 if the file was successfully atomically created (if necessary) and * opened. In this case the file will be returned attached to @file. * * Returns 1 if the file was not completely opened at this time, though lookups * and creations will have been performed and the dentry returned in @path will * be positive upon return if O_CREAT was specified. If O_CREAT wasn't * specified then a negative dentry may be returned. * * An error code is returned otherwise. * * FILE_CREATE will be set in @*opened if the dentry was created and will be * cleared otherwise prior to returning. */ static int lookup_open(struct nameidata *nd, struct path *path, struct file *file, const struct open_flags *op, bool got_write, int *opened) { struct dentry *dir = nd->path.dentry; struct inode *dir_inode = dir->d_inode; struct dentry *dentry; int error; bool need_lookup; *opened &= ~FILE_CREATED; dentry = lookup_dcache(&nd->last, dir, nd->flags, &need_lookup); if (IS_ERR(dentry)) return PTR_ERR(dentry); /* Cached positive dentry: will open in f_op->open */ if (!need_lookup && dentry->d_inode) goto out_no_open; if ((nd->flags & LOOKUP_OPEN) && dir_inode->i_op->atomic_open) { return atomic_open(nd, dentry, path, file, op, got_write, need_lookup, opened); } if (need_lookup) { BUG_ON(dentry->d_inode); dentry = lookup_real(dir_inode, dentry, nd->flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); } /* Negative dentry, just create the file */ if (!dentry->d_inode && (op->open_flag & O_CREAT)) { umode_t mode = op->mode; if (!IS_POSIXACL(dir->d_inode)) mode &= ~current_umask(); /* * This write is needed to ensure that a * rw->ro transition does not occur between * the time when the file is created and when * a permanent write count is taken through * the 'struct file' in finish_open(). */ if (!got_write) { error = -EROFS; goto out_dput; } *opened |= FILE_CREATED; error = security_path_mknod(&nd->path, dentry, mode, 0); if (error) goto out_dput; error = vfs_create(dir->d_inode, dentry, mode, nd->flags & LOOKUP_EXCL); if (error) goto out_dput; } out_no_open: path->dentry = dentry; path->mnt = nd->path.mnt; return 1; out_dput: dput(dentry); return error; } /* * Handle the last step of open() */ static int do_last(struct nameidata *nd, struct file *file, const struct open_flags *op, int *opened) { struct dentry *dir = nd->path.dentry; int open_flag = op->open_flag; bool will_truncate = (open_flag & O_TRUNC) != 0; bool got_write = false; int acc_mode = op->acc_mode; unsigned seq; struct inode *inode; struct path save_parent = { .dentry = NULL, .mnt = NULL }; struct path path; bool retried = false; int error; nd->flags &= ~LOOKUP_PARENT; nd->flags |= op->intent; if (nd->last_type != LAST_NORM) { error = handle_dots(nd, nd->last_type); if (unlikely(error)) return error; goto finish_open; } if (!(open_flag & O_CREAT)) { if (nd->last.name[nd->last.len]) nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; /* we _can_ be in RCU mode here */ error = lookup_fast(nd, &path, &inode, &seq); if (likely(!error)) goto finish_lookup; if (error < 0) return error; BUG_ON(nd->inode != dir->d_inode); } else { /* create side of things */ /* * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED * has been cleared when we got to the last component we are * about to look up */ error = complete_walk(nd); if (error) return error; audit_inode(nd->name, dir, LOOKUP_PARENT); /* trailing slashes? */ if (unlikely(nd->last.name[nd->last.len])) return -EISDIR; } retry_lookup: if (op->open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) { error = mnt_want_write(nd->path.mnt); if (!error) got_write = true; /* * do _not_ fail yet - we might not need that or fail with * a different error; let lookup_open() decide; we'll be * dropping this one anyway. */ } mutex_lock(&dir->d_inode->i_mutex); error = lookup_open(nd, &path, file, op, got_write, opened); mutex_unlock(&dir->d_inode->i_mutex); if (error <= 0) { if (error) goto out; if ((*opened & FILE_CREATED) || !S_ISREG(file_inode(file)->i_mode)) will_truncate = false; audit_inode(nd->name, file->f_path.dentry, 0); goto opened; } if (*opened & FILE_CREATED) { /* Don't check for write permission, don't truncate */ open_flag &= ~O_TRUNC; will_truncate = false; acc_mode = MAY_OPEN; path_to_nameidata(&path, nd); goto finish_open_created; } /* * create/update audit record if it already exists. */ if (d_is_positive(path.dentry)) audit_inode(nd->name, path.dentry, 0); /* * If atomic_open() acquired write access it is dropped now due to * possible mount and symlink following (this might be optimized away if * necessary...) */ if (got_write) { mnt_drop_write(nd->path.mnt); got_write = false; } if (unlikely((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT))) { path_to_nameidata(&path, nd); return -EEXIST; } error = follow_managed(&path, nd); if (unlikely(error < 0)) return error; BUG_ON(nd->flags & LOOKUP_RCU); inode = d_backing_inode(path.dentry); seq = 0; /* out of RCU mode, so the value doesn't matter */ if (unlikely(d_is_negative(path.dentry))) { path_to_nameidata(&path, nd); return -ENOENT; } finish_lookup: if (nd->depth) put_link(nd); error = should_follow_link(nd, &path, nd->flags & LOOKUP_FOLLOW, inode, seq); if (unlikely(error)) return error; if (unlikely(d_is_symlink(path.dentry)) && !(open_flag & O_PATH)) { path_to_nameidata(&path, nd); return -ELOOP; } if ((nd->flags & LOOKUP_RCU) || nd->path.mnt != path.mnt) { path_to_nameidata(&path, nd); } else { save_parent.dentry = nd->path.dentry; save_parent.mnt = mntget(path.mnt); nd->path.dentry = path.dentry; } nd->inode = inode; nd->seq = seq; /* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */ finish_open: error = complete_walk(nd); if (error) { path_put(&save_parent); return error; } audit_inode(nd->name, nd->path.dentry, 0); error = -EISDIR; if ((open_flag & O_CREAT) && d_is_dir(nd->path.dentry)) goto out; error = -ENOTDIR; if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry)) goto out; if (!d_is_reg(nd->path.dentry)) will_truncate = false; if (will_truncate) { error = mnt_want_write(nd->path.mnt); if (error) goto out; got_write = true; } finish_open_created: error = may_open(&nd->path, acc_mode, open_flag); if (error) goto out; BUG_ON(*opened & FILE_OPENED); /* once it's opened, it's opened */ error = vfs_open(&nd->path, file, current_cred()); if (!error) { *opened |= FILE_OPENED; } else { if (error == -EOPENSTALE) goto stale_open; goto out; } opened: error = open_check_o_direct(file); if (error) goto exit_fput; error = ima_file_check(file, op->acc_mode, *opened); if (error) goto exit_fput; if (will_truncate) { error = handle_truncate(file); if (error) goto exit_fput; } out: if (got_write) mnt_drop_write(nd->path.mnt); path_put(&save_parent); return error; exit_fput: fput(file); goto out; stale_open: /* If no saved parent or already retried then can't retry */ if (!save_parent.dentry || retried) goto out; BUG_ON(save_parent.dentry != dir); path_put(&nd->path); nd->path = save_parent; nd->inode = dir->d_inode; save_parent.mnt = NULL; save_parent.dentry = NULL; if (got_write) { mnt_drop_write(nd->path.mnt); got_write = false; } retried = true; goto retry_lookup; } static int do_tmpfile(struct nameidata *nd, unsigned flags, const struct open_flags *op, struct file *file, int *opened) { static const struct qstr name = QSTR_INIT("/", 1); struct dentry *child; struct inode *dir; struct path path; int error = path_lookupat(nd, flags | LOOKUP_DIRECTORY, &path); if (unlikely(error)) return error; error = mnt_want_write(path.mnt); if (unlikely(error)) goto out; dir = path.dentry->d_inode; /* we want directory to be writable */ error = inode_permission(dir, MAY_WRITE | MAY_EXEC); if (error) goto out2; if (!dir->i_op->tmpfile) { error = -EOPNOTSUPP; goto out2; } child = d_alloc(path.dentry, &name); if (unlikely(!child)) { error = -ENOMEM; goto out2; } dput(path.dentry); path.dentry = child; error = dir->i_op->tmpfile(dir, child, op->mode); if (error) goto out2; audit_inode(nd->name, child, 0); /* Don't check for other permissions, the inode was just created */ error = may_open(&path, MAY_OPEN, op->open_flag); if (error) goto out2; file->f_path.mnt = path.mnt; error = finish_open(file, child, NULL, opened); if (error) goto out2; error = open_check_o_direct(file); if (error) { fput(file); } else if (!(op->open_flag & O_EXCL)) { struct inode *inode = file_inode(file); spin_lock(&inode->i_lock); inode->i_state |= I_LINKABLE; spin_unlock(&inode->i_lock); } out2: mnt_drop_write(path.mnt); out: path_put(&path); return error; } static struct file *path_openat(struct nameidata *nd, const struct open_flags *op, unsigned flags) { const char *s; struct file *file; int opened = 0; int error; file = get_empty_filp(); if (IS_ERR(file)) return file; file->f_flags = op->open_flag; if (unlikely(file->f_flags & __O_TMPFILE)) { error = do_tmpfile(nd, flags, op, file, &opened); goto out2; } s = path_init(nd, flags); if (IS_ERR(s)) { put_filp(file); return ERR_CAST(s); } while (!(error = link_path_walk(s, nd)) && (error = do_last(nd, file, op, &opened)) > 0) { nd->flags &= ~(LOOKUP_OPEN|LOOKUP_CREATE|LOOKUP_EXCL); s = trailing_symlink(nd); if (IS_ERR(s)) { error = PTR_ERR(s); break; } } terminate_walk(nd); out2: if (!(opened & FILE_OPENED)) { BUG_ON(!error); put_filp(file); } if (unlikely(error)) { if (error == -EOPENSTALE) { if (flags & LOOKUP_RCU) error = -ECHILD; else error = -ESTALE; } file = ERR_PTR(error); } return file; } struct file *do_filp_open(int dfd, struct filename *pathname, const struct open_flags *op) { struct nameidata nd; int flags = op->lookup_flags; struct file *filp; set_nameidata(&nd, dfd, pathname); filp = path_openat(&nd, op, flags | LOOKUP_RCU); if (unlikely(filp == ERR_PTR(-ECHILD))) filp = path_openat(&nd, op, flags); if (unlikely(filp == ERR_PTR(-ESTALE))) filp = path_openat(&nd, op, flags | LOOKUP_REVAL); restore_nameidata(); return filp; } struct file *do_file_open_root(struct dentry *dentry, struct vfsmount *mnt, const char *name, const struct open_flags *op) { struct nameidata nd; struct file *file; struct filename *filename; int flags = op->lookup_flags | LOOKUP_ROOT; nd.root.mnt = mnt; nd.root.dentry = dentry; if (d_is_symlink(dentry) && op->intent & LOOKUP_OPEN) return ERR_PTR(-ELOOP); filename = getname_kernel(name); if (unlikely(IS_ERR(filename))) return ERR_CAST(filename); set_nameidata(&nd, -1, filename); file = path_openat(&nd, op, flags | LOOKUP_RCU); if (unlikely(file == ERR_PTR(-ECHILD))) file = path_openat(&nd, op, flags); if (unlikely(file == ERR_PTR(-ESTALE))) file = path_openat(&nd, op, flags | LOOKUP_REVAL); restore_nameidata(); putname(filename); return file; } static struct dentry *filename_create(int dfd, struct filename *name, struct path *path, unsigned int lookup_flags) { struct dentry *dentry = ERR_PTR(-EEXIST); struct qstr last; int type; int err2; int error; bool is_dir = (lookup_flags & LOOKUP_DIRECTORY); /* * Note that only LOOKUP_REVAL and LOOKUP_DIRECTORY matter here. Any * other flags passed in are ignored! */ lookup_flags &= LOOKUP_REVAL; name = filename_parentat(dfd, name, lookup_flags, path, &last, &type); if (IS_ERR(name)) return ERR_CAST(name); /* * Yucky last component or no last component at all? * (foo/., foo/.., /////) */ if (unlikely(type != LAST_NORM)) goto out; /* don't fail immediately if it's r/o, at least try to report other errors */ err2 = mnt_want_write(path->mnt); /* * Do the final lookup. */ lookup_flags |= LOOKUP_CREATE | LOOKUP_EXCL; mutex_lock_nested(&path->dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = __lookup_hash(&last, path->dentry, lookup_flags); if (IS_ERR(dentry)) goto unlock; error = -EEXIST; if (d_is_positive(dentry)) goto fail; /* * Special case - lookup gave negative, but... we had foo/bar/ * From the vfs_mknod() POV we just have a negative dentry - * all is fine. Let's be bastards - you had / on the end, you've * been asking for (non-existent) directory. -ENOENT for you. */ if (unlikely(!is_dir && last.name[last.len])) { error = -ENOENT; goto fail; } if (unlikely(err2)) { error = err2; goto fail; } putname(name); return dentry; fail: dput(dentry); dentry = ERR_PTR(error); unlock: mutex_unlock(&path->dentry->d_inode->i_mutex); if (!err2) mnt_drop_write(path->mnt); out: path_put(path); putname(name); return dentry; } struct dentry *kern_path_create(int dfd, const char *pathname, struct path *path, unsigned int lookup_flags) { return filename_create(dfd, getname_kernel(pathname), path, lookup_flags); } EXPORT_SYMBOL(kern_path_create); void done_path_create(struct path *path, struct dentry *dentry) { dput(dentry); mutex_unlock(&path->dentry->d_inode->i_mutex); mnt_drop_write(path->mnt); path_put(path); } EXPORT_SYMBOL(done_path_create); inline struct dentry *user_path_create(int dfd, const char __user *pathname, struct path *path, unsigned int lookup_flags) { return filename_create(dfd, getname(pathname), path, lookup_flags); } EXPORT_SYMBOL(user_path_create); int vfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev) { int error = may_create(dir, dentry); if (error) return error; if ((S_ISCHR(mode) || S_ISBLK(mode)) && !capable(CAP_MKNOD)) return -EPERM; if (!dir->i_op->mknod) return -EPERM; error = devcgroup_inode_mknod(mode, dev); if (error) return error; error = security_inode_mknod(dir, dentry, mode, dev); if (error) return error; error = dir->i_op->mknod(dir, dentry, mode, dev); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_mknod); static int may_mknod(umode_t mode) { switch (mode & S_IFMT) { case S_IFREG: case S_IFCHR: case S_IFBLK: case S_IFIFO: case S_IFSOCK: case 0: /* zero mode translates to S_IFREG */ return 0; case S_IFDIR: return -EPERM; default: return -EINVAL; } } SYSCALL_DEFINE4(mknodat, int, dfd, const char __user *, filename, umode_t, mode, unsigned, dev) { struct dentry *dentry; struct path path; int error; unsigned int lookup_flags = 0; error = may_mknod(mode); if (error) return error; retry: dentry = user_path_create(dfd, filename, &path, lookup_flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (!IS_POSIXACL(path.dentry->d_inode)) mode &= ~current_umask(); error = security_path_mknod(&path, dentry, mode, dev); if (error) goto out; switch (mode & S_IFMT) { case 0: case S_IFREG: error = vfs_create(path.dentry->d_inode,dentry,mode,true); break; case S_IFCHR: case S_IFBLK: error = vfs_mknod(path.dentry->d_inode,dentry,mode, new_decode_dev(dev)); break; case S_IFIFO: case S_IFSOCK: error = vfs_mknod(path.dentry->d_inode,dentry,mode,0); break; } out: done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE3(mknod, const char __user *, filename, umode_t, mode, unsigned, dev) { return sys_mknodat(AT_FDCWD, filename, mode, dev); } int vfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { int error = may_create(dir, dentry); unsigned max_links = dir->i_sb->s_max_links; if (error) return error; if (!dir->i_op->mkdir) return -EPERM; mode &= (S_IRWXUGO|S_ISVTX); error = security_inode_mkdir(dir, dentry, mode); if (error) return error; if (max_links && dir->i_nlink >= max_links) return -EMLINK; error = dir->i_op->mkdir(dir, dentry, mode); if (!error) fsnotify_mkdir(dir, dentry); return error; } EXPORT_SYMBOL(vfs_mkdir); SYSCALL_DEFINE3(mkdirat, int, dfd, const char __user *, pathname, umode_t, mode) { struct dentry *dentry; struct path path; int error; unsigned int lookup_flags = LOOKUP_DIRECTORY; retry: dentry = user_path_create(dfd, pathname, &path, lookup_flags); if (IS_ERR(dentry)) return PTR_ERR(dentry); if (!IS_POSIXACL(path.dentry->d_inode)) mode &= ~current_umask(); error = security_path_mkdir(&path, dentry, mode); if (!error) error = vfs_mkdir(path.dentry->d_inode, dentry, mode); done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE2(mkdir, const char __user *, pathname, umode_t, mode) { return sys_mkdirat(AT_FDCWD, pathname, mode); } /* * The dentry_unhash() helper will try to drop the dentry early: we * should have a usage count of 1 if we're the only user of this * dentry, and if that is true (possibly after pruning the dcache), * then we drop the dentry now. * * A low-level filesystem can, if it choses, legally * do a * * if (!d_unhashed(dentry)) * return -EBUSY; * * if it cannot handle the case of removing a directory * that is still in use by something else.. */ void dentry_unhash(struct dentry *dentry) { shrink_dcache_parent(dentry); spin_lock(&dentry->d_lock); if (dentry->d_lockref.count == 1) __d_drop(dentry); spin_unlock(&dentry->d_lock); } EXPORT_SYMBOL(dentry_unhash); int vfs_rmdir(struct inode *dir, struct dentry *dentry) { int error = may_delete(dir, dentry, 1); if (error) return error; if (!dir->i_op->rmdir) return -EPERM; dget(dentry); mutex_lock(&dentry->d_inode->i_mutex); error = -EBUSY; if (is_local_mountpoint(dentry)) goto out; error = security_inode_rmdir(dir, dentry); if (error) goto out; shrink_dcache_parent(dentry); error = dir->i_op->rmdir(dir, dentry); if (error) goto out; dentry->d_inode->i_flags |= S_DEAD; dont_mount(dentry); detach_mounts(dentry); out: mutex_unlock(&dentry->d_inode->i_mutex); dput(dentry); if (!error) d_delete(dentry); return error; } EXPORT_SYMBOL(vfs_rmdir); static long do_rmdir(int dfd, const char __user *pathname) { int error = 0; struct filename *name; struct dentry *dentry; struct path path; struct qstr last; int type; unsigned int lookup_flags = 0; retry: name = user_path_parent(dfd, pathname, &path, &last, &type, lookup_flags); if (IS_ERR(name)) return PTR_ERR(name); switch (type) { case LAST_DOTDOT: error = -ENOTEMPTY; goto exit1; case LAST_DOT: error = -EINVAL; goto exit1; case LAST_ROOT: error = -EBUSY; goto exit1; } error = mnt_want_write(path.mnt); if (error) goto exit1; mutex_lock_nested(&path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = __lookup_hash(&last, path.dentry, lookup_flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto exit2; if (!dentry->d_inode) { error = -ENOENT; goto exit3; } error = security_path_rmdir(&path, dentry); if (error) goto exit3; error = vfs_rmdir(path.dentry->d_inode, dentry); exit3: dput(dentry); exit2: mutex_unlock(&path.dentry->d_inode->i_mutex); mnt_drop_write(path.mnt); exit1: path_put(&path); putname(name); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } return error; } SYSCALL_DEFINE1(rmdir, const char __user *, pathname) { return do_rmdir(AT_FDCWD, pathname); } /** * vfs_unlink - unlink a filesystem object * @dir: parent directory * @dentry: victim * @delegated_inode: returns victim inode, if the inode is delegated. * * The caller must hold dir->i_mutex. * * If vfs_unlink discovers a delegation, it will return -EWOULDBLOCK and * return a reference to the inode in delegated_inode. The caller * should then break the delegation on that inode and retry. Because * breaking a delegation may take a long time, the caller should drop * dir->i_mutex before doing so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. */ int vfs_unlink(struct inode *dir, struct dentry *dentry, struct inode **delegated_inode) { struct inode *target = dentry->d_inode; int error = may_delete(dir, dentry, 0); if (error) return error; if (!dir->i_op->unlink) return -EPERM; mutex_lock(&target->i_mutex); if (is_local_mountpoint(dentry)) error = -EBUSY; else { error = security_inode_unlink(dir, dentry); if (!error) { error = try_break_deleg(target, delegated_inode); if (error) goto out; error = dir->i_op->unlink(dir, dentry); if (!error) { dont_mount(dentry); detach_mounts(dentry); } } } out: mutex_unlock(&target->i_mutex); /* We don't d_delete() NFS sillyrenamed files--they still exist. */ if (!error && !(dentry->d_flags & DCACHE_NFSFS_RENAMED)) { fsnotify_link_count(target); d_delete(dentry); } return error; } EXPORT_SYMBOL(vfs_unlink); /* * Make sure that the actual truncation of the file will occur outside its * directory's i_mutex. Truncate can take a long time if there is a lot of * writeout happening, and we don't want to prevent access to the directory * while waiting on the I/O. */ static long do_unlinkat(int dfd, const char __user *pathname) { int error; struct filename *name; struct dentry *dentry; struct path path; struct qstr last; int type; struct inode *inode = NULL; struct inode *delegated_inode = NULL; unsigned int lookup_flags = 0; retry: name = user_path_parent(dfd, pathname, &path, &last, &type, lookup_flags); if (IS_ERR(name)) return PTR_ERR(name); error = -EISDIR; if (type != LAST_NORM) goto exit1; error = mnt_want_write(path.mnt); if (error) goto exit1; retry_deleg: mutex_lock_nested(&path.dentry->d_inode->i_mutex, I_MUTEX_PARENT); dentry = __lookup_hash(&last, path.dentry, lookup_flags); error = PTR_ERR(dentry); if (!IS_ERR(dentry)) { /* Why not before? Because we want correct error value */ if (last.name[last.len]) goto slashes; inode = dentry->d_inode; if (d_is_negative(dentry)) goto slashes; ihold(inode); error = security_path_unlink(&path, dentry); if (error) goto exit2; error = vfs_unlink(path.dentry->d_inode, dentry, &delegated_inode); exit2: dput(dentry); } mutex_unlock(&path.dentry->d_inode->i_mutex); if (inode) iput(inode); /* truncate the inode here */ inode = NULL; if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) goto retry_deleg; } mnt_drop_write(path.mnt); exit1: path_put(&path); putname(name); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; inode = NULL; goto retry; } return error; slashes: if (d_is_negative(dentry)) error = -ENOENT; else if (d_is_dir(dentry)) error = -EISDIR; else error = -ENOTDIR; goto exit2; } SYSCALL_DEFINE3(unlinkat, int, dfd, const char __user *, pathname, int, flag) { if ((flag & ~AT_REMOVEDIR) != 0) return -EINVAL; if (flag & AT_REMOVEDIR) return do_rmdir(dfd, pathname); return do_unlinkat(dfd, pathname); } SYSCALL_DEFINE1(unlink, const char __user *, pathname) { return do_unlinkat(AT_FDCWD, pathname); } int vfs_symlink(struct inode *dir, struct dentry *dentry, const char *oldname) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->symlink) return -EPERM; error = security_inode_symlink(dir, dentry, oldname); if (error) return error; error = dir->i_op->symlink(dir, dentry, oldname); if (!error) fsnotify_create(dir, dentry); return error; } EXPORT_SYMBOL(vfs_symlink); SYSCALL_DEFINE3(symlinkat, const char __user *, oldname, int, newdfd, const char __user *, newname) { int error; struct filename *from; struct dentry *dentry; struct path path; unsigned int lookup_flags = 0; from = getname(oldname); if (IS_ERR(from)) return PTR_ERR(from); retry: dentry = user_path_create(newdfd, newname, &path, lookup_flags); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto out_putname; error = security_path_symlink(&path, dentry, from->name); if (!error) error = vfs_symlink(path.dentry->d_inode, dentry, from->name); done_path_create(&path, dentry); if (retry_estale(error, lookup_flags)) { lookup_flags |= LOOKUP_REVAL; goto retry; } out_putname: putname(from); return error; } SYSCALL_DEFINE2(symlink, const char __user *, oldname, const char __user *, newname) { return sys_symlinkat(oldname, AT_FDCWD, newname); } /** * vfs_link - create a new link * @old_dentry: object to be linked * @dir: new parent * @new_dentry: where to create the new link * @delegated_inode: returns inode needing a delegation break * * The caller must hold dir->i_mutex * * If vfs_link discovers a delegation on the to-be-linked file in need * of breaking, it will return -EWOULDBLOCK and return a reference to the * inode in delegated_inode. The caller should then break the delegation * and retry. Because breaking a delegation may take a long time, the * caller should drop the i_mutex before doing so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. */ int vfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry, struct inode **delegated_inode) { struct inode *inode = old_dentry->d_inode; unsigned max_links = dir->i_sb->s_max_links; int error; if (!inode) return -ENOENT; error = may_create(dir, new_dentry); if (error) return error; if (dir->i_sb != inode->i_sb) return -EXDEV; /* * A link to an append-only or immutable file cannot be created. */ if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) return -EPERM; if (!dir->i_op->link) return -EPERM; if (S_ISDIR(inode->i_mode)) return -EPERM; error = security_inode_link(old_dentry, dir, new_dentry); if (error) return error; mutex_lock(&inode->i_mutex); /* Make sure we don't allow creating hardlink to an unlinked file */ if (inode->i_nlink == 0 && !(inode->i_state & I_LINKABLE)) error = -ENOENT; else if (max_links && inode->i_nlink >= max_links) error = -EMLINK; else { error = try_break_deleg(inode, delegated_inode); if (!error) error = dir->i_op->link(old_dentry, dir, new_dentry); } if (!error && (inode->i_state & I_LINKABLE)) { spin_lock(&inode->i_lock); inode->i_state &= ~I_LINKABLE; spin_unlock(&inode->i_lock); } mutex_unlock(&inode->i_mutex); if (!error) fsnotify_link(dir, inode, new_dentry); return error; } EXPORT_SYMBOL(vfs_link); /* * Hardlinks are often used in delicate situations. We avoid * security-related surprises by not following symlinks on the * newname. --KAB * * We don't follow them on the oldname either to be compatible * with linux 2.0, and to avoid hard-linking to directories * and other special files. --ADM */ SYSCALL_DEFINE5(linkat, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname, int, flags) { struct dentry *new_dentry; struct path old_path, new_path; struct inode *delegated_inode = NULL; int how = 0; int error; if ((flags & ~(AT_SYMLINK_FOLLOW | AT_EMPTY_PATH)) != 0) return -EINVAL; /* * To use null names we require CAP_DAC_READ_SEARCH * This ensures that not everyone will be able to create * handlink using the passed filedescriptor. */ if (flags & AT_EMPTY_PATH) { if (!capable(CAP_DAC_READ_SEARCH)) return -ENOENT; how = LOOKUP_EMPTY; } if (flags & AT_SYMLINK_FOLLOW) how |= LOOKUP_FOLLOW; retry: error = user_path_at(olddfd, oldname, how, &old_path); if (error) return error; new_dentry = user_path_create(newdfd, newname, &new_path, (how & LOOKUP_REVAL)); error = PTR_ERR(new_dentry); if (IS_ERR(new_dentry)) goto out; error = -EXDEV; if (old_path.mnt != new_path.mnt) goto out_dput; error = may_linkat(&old_path); if (unlikely(error)) goto out_dput; error = security_path_link(old_path.dentry, &new_path, new_dentry); if (error) goto out_dput; error = vfs_link(old_path.dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode); out_dput: done_path_create(&new_path, new_dentry); if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) { path_put(&old_path); goto retry; } } if (retry_estale(error, how)) { path_put(&old_path); how |= LOOKUP_REVAL; goto retry; } out: path_put(&old_path); return error; } SYSCALL_DEFINE2(link, const char __user *, oldname, const char __user *, newname) { return sys_linkat(AT_FDCWD, oldname, AT_FDCWD, newname, 0); } /** * vfs_rename - rename a filesystem object * @old_dir: parent of source * @old_dentry: source * @new_dir: parent of destination * @new_dentry: destination * @delegated_inode: returns an inode needing a delegation break * @flags: rename flags * * The caller must hold multiple mutexes--see lock_rename()). * * If vfs_rename discovers a delegation in need of breaking at either * the source or destination, it will return -EWOULDBLOCK and return a * reference to the inode in delegated_inode. The caller should then * break the delegation and retry. Because breaking a delegation may * take a long time, the caller should drop all locks before doing * so. * * Alternatively, a caller may pass NULL for delegated_inode. This may * be appropriate for callers that expect the underlying filesystem not * to be NFS exported. * * The worst of all namespace operations - renaming directory. "Perverted" * doesn't even start to describe it. Somebody in UCB had a heck of a trip... * Problems: * a) we can get into loop creation. * b) race potential - two innocent renames can create a loop together. * That's where 4.4 screws up. Current fix: serialization on * sb->s_vfs_rename_mutex. We might be more accurate, but that's another * story. * c) we have to lock _four_ objects - parents and victim (if it exists), * and source (if it is not a directory). * And that - after we got ->i_mutex on parents (until then we don't know * whether the target exists). Solution: try to be smart with locking * order for inodes. We rely on the fact that tree topology may change * only under ->s_vfs_rename_mutex _and_ that parent of the object we * move will be locked. Thus we can rank directories by the tree * (ancestors first) and rank all non-directories after them. * That works since everybody except rename does "lock parent, lookup, * lock child" and rename is under ->s_vfs_rename_mutex. * HOWEVER, it relies on the assumption that any object with ->lookup() * has no more than 1 dentry. If "hybrid" objects will ever appear, * we'd better make sure that there's no link(2) for them. * d) conversion from fhandle to dentry may come in the wrong moment - when * we are removing the target. Solution: we will have to grab ->i_mutex * in the fhandle_to_dentry code. [FIXME - current nfsfh.c relies on * ->i_mutex on parents, which works but leads to some truly excessive * locking]. */ int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, struct inode **delegated_inode, unsigned int flags) { int error; bool is_dir = d_is_dir(old_dentry); const unsigned char *old_name; struct inode *source = old_dentry->d_inode; struct inode *target = new_dentry->d_inode; bool new_is_dir = false; unsigned max_links = new_dir->i_sb->s_max_links; if (source == target) return 0; error = may_delete(old_dir, old_dentry, is_dir); if (error) return error; if (!target) { error = may_create(new_dir, new_dentry); } else { new_is_dir = d_is_dir(new_dentry); if (!(flags & RENAME_EXCHANGE)) error = may_delete(new_dir, new_dentry, is_dir); else error = may_delete(new_dir, new_dentry, new_is_dir); } if (error) return error; if (!old_dir->i_op->rename && !old_dir->i_op->rename2) return -EPERM; if (flags && !old_dir->i_op->rename2) return -EINVAL; /* * If we are going to change the parent - check write permissions, * we'll need to flip '..'. */ if (new_dir != old_dir) { if (is_dir) { error = inode_permission(source, MAY_WRITE); if (error) return error; } if ((flags & RENAME_EXCHANGE) && new_is_dir) { error = inode_permission(target, MAY_WRITE); if (error) return error; } } error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry, flags); if (error) return error; old_name = fsnotify_oldname_init(old_dentry->d_name.name); dget(new_dentry); if (!is_dir || (flags & RENAME_EXCHANGE)) lock_two_nondirectories(source, target); else if (target) mutex_lock(&target->i_mutex); error = -EBUSY; if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry)) goto out; if (max_links && new_dir != old_dir) { error = -EMLINK; if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links) goto out; if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir && old_dir->i_nlink >= max_links) goto out; } if (is_dir && !(flags & RENAME_EXCHANGE) && target) shrink_dcache_parent(new_dentry); if (!is_dir) { error = try_break_deleg(source, delegated_inode); if (error) goto out; } if (target && !new_is_dir) { error = try_break_deleg(target, delegated_inode); if (error) goto out; } if (!old_dir->i_op->rename2) { error = old_dir->i_op->rename(old_dir, old_dentry, new_dir, new_dentry); } else { WARN_ON(old_dir->i_op->rename != NULL); error = old_dir->i_op->rename2(old_dir, old_dentry, new_dir, new_dentry, flags); } if (error) goto out; if (!(flags & RENAME_EXCHANGE) && target) { if (is_dir) target->i_flags |= S_DEAD; dont_mount(new_dentry); detach_mounts(new_dentry); } if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) { if (!(flags & RENAME_EXCHANGE)) d_move(old_dentry, new_dentry); else d_exchange(old_dentry, new_dentry); } out: if (!is_dir || (flags & RENAME_EXCHANGE)) unlock_two_nondirectories(source, target); else if (target) mutex_unlock(&target->i_mutex); dput(new_dentry); if (!error) { fsnotify_move(old_dir, new_dir, old_name, is_dir, !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry); if (flags & RENAME_EXCHANGE) { fsnotify_move(new_dir, old_dir, old_dentry->d_name.name, new_is_dir, NULL, new_dentry); } } fsnotify_oldname_free(old_name); return error; } EXPORT_SYMBOL(vfs_rename); SYSCALL_DEFINE5(renameat2, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname, unsigned int, flags) { struct dentry *old_dentry, *new_dentry; struct dentry *trap; struct path old_path, new_path; struct qstr old_last, new_last; int old_type, new_type; struct inode *delegated_inode = NULL; struct filename *from; struct filename *to; unsigned int lookup_flags = 0, target_flags = LOOKUP_RENAME_TARGET; bool should_retry = false; int error; if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT)) return -EINVAL; if ((flags & (RENAME_NOREPLACE | RENAME_WHITEOUT)) && (flags & RENAME_EXCHANGE)) return -EINVAL; if ((flags & RENAME_WHITEOUT) && !capable(CAP_MKNOD)) return -EPERM; if (flags & RENAME_EXCHANGE) target_flags = 0; retry: from = user_path_parent(olddfd, oldname, &old_path, &old_last, &old_type, lookup_flags); if (IS_ERR(from)) { error = PTR_ERR(from); goto exit; } to = user_path_parent(newdfd, newname, &new_path, &new_last, &new_type, lookup_flags); if (IS_ERR(to)) { error = PTR_ERR(to); goto exit1; } error = -EXDEV; if (old_path.mnt != new_path.mnt) goto exit2; error = -EBUSY; if (old_type != LAST_NORM) goto exit2; if (flags & RENAME_NOREPLACE) error = -EEXIST; if (new_type != LAST_NORM) goto exit2; error = mnt_want_write(old_path.mnt); if (error) goto exit2; retry_deleg: trap = lock_rename(new_path.dentry, old_path.dentry); old_dentry = __lookup_hash(&old_last, old_path.dentry, lookup_flags); error = PTR_ERR(old_dentry); if (IS_ERR(old_dentry)) goto exit3; /* source must exist */ error = -ENOENT; if (d_is_negative(old_dentry)) goto exit4; new_dentry = __lookup_hash(&new_last, new_path.dentry, lookup_flags | target_flags); error = PTR_ERR(new_dentry); if (IS_ERR(new_dentry)) goto exit4; error = -EEXIST; if ((flags & RENAME_NOREPLACE) && d_is_positive(new_dentry)) goto exit5; if (flags & RENAME_EXCHANGE) { error = -ENOENT; if (d_is_negative(new_dentry)) goto exit5; if (!d_is_dir(new_dentry)) { error = -ENOTDIR; if (new_last.name[new_last.len]) goto exit5; } } /* unless the source is a directory trailing slashes give -ENOTDIR */ if (!d_is_dir(old_dentry)) { error = -ENOTDIR; if (old_last.name[old_last.len]) goto exit5; if (!(flags & RENAME_EXCHANGE) && new_last.name[new_last.len]) goto exit5; } /* source should not be ancestor of target */ error = -EINVAL; if (old_dentry == trap) goto exit5; /* target should not be an ancestor of source */ if (!(flags & RENAME_EXCHANGE)) error = -ENOTEMPTY; if (new_dentry == trap) goto exit5; error = security_path_rename(&old_path, old_dentry, &new_path, new_dentry, flags); if (error) goto exit5; error = vfs_rename(old_path.dentry->d_inode, old_dentry, new_path.dentry->d_inode, new_dentry, &delegated_inode, flags); exit5: dput(new_dentry); exit4: dput(old_dentry); exit3: unlock_rename(new_path.dentry, old_path.dentry); if (delegated_inode) { error = break_deleg_wait(&delegated_inode); if (!error) goto retry_deleg; } mnt_drop_write(old_path.mnt); exit2: if (retry_estale(error, lookup_flags)) should_retry = true; path_put(&new_path); putname(to); exit1: path_put(&old_path); putname(from); if (should_retry) { should_retry = false; lookup_flags |= LOOKUP_REVAL; goto retry; } exit: return error; } SYSCALL_DEFINE4(renameat, int, olddfd, const char __user *, oldname, int, newdfd, const char __user *, newname) { return sys_renameat2(olddfd, oldname, newdfd, newname, 0); } SYSCALL_DEFINE2(rename, const char __user *, oldname, const char __user *, newname) { return sys_renameat2(AT_FDCWD, oldname, AT_FDCWD, newname, 0); } int vfs_whiteout(struct inode *dir, struct dentry *dentry) { int error = may_create(dir, dentry); if (error) return error; if (!dir->i_op->mknod) return -EPERM; return dir->i_op->mknod(dir, dentry, S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV); } EXPORT_SYMBOL(vfs_whiteout); int readlink_copy(char __user *buffer, int buflen, const char *link) { int len = PTR_ERR(link); if (IS_ERR(link)) goto out; len = strlen(link); if (len > (unsigned) buflen) len = buflen; if (copy_to_user(buffer, link, len)) len = -EFAULT; out: return len; } EXPORT_SYMBOL(readlink_copy); /* * A helper for ->readlink(). This should be used *ONLY* for symlinks that * have ->follow_link() touching nd only in nd_set_link(). Using (or not * using) it for any given inode is up to filesystem. */ int generic_readlink(struct dentry *dentry, char __user *buffer, int buflen) { void *cookie; struct inode *inode = d_inode(dentry); const char *link = inode->i_link; int res; if (!link) { link = inode->i_op->follow_link(dentry, &cookie); if (IS_ERR(link)) return PTR_ERR(link); } res = readlink_copy(buffer, buflen, link); if (inode->i_op->put_link) inode->i_op->put_link(inode, cookie); return res; } EXPORT_SYMBOL(generic_readlink); /* get the link contents into pagecache */ static char *page_getlink(struct dentry * dentry, struct page **ppage) { char *kaddr; struct page *page; struct address_space *mapping = dentry->d_inode->i_mapping; page = read_mapping_page(mapping, 0, NULL); if (IS_ERR(page)) return (char*)page; *ppage = page; kaddr = kmap(page); nd_terminate_link(kaddr, dentry->d_inode->i_size, PAGE_SIZE - 1); return kaddr; } int page_readlink(struct dentry *dentry, char __user *buffer, int buflen) { struct page *page = NULL; int res = readlink_copy(buffer, buflen, page_getlink(dentry, &page)); if (page) { kunmap(page); page_cache_release(page); } return res; } EXPORT_SYMBOL(page_readlink); const char *page_follow_link_light(struct dentry *dentry, void **cookie) { struct page *page = NULL; char *res = page_getlink(dentry, &page); if (!IS_ERR(res)) *cookie = page; return res; } EXPORT_SYMBOL(page_follow_link_light); void page_put_link(struct inode *unused, void *cookie) { struct page *page = cookie; kunmap(page); page_cache_release(page); } EXPORT_SYMBOL(page_put_link); /* * The nofs argument instructs pagecache_write_begin to pass AOP_FLAG_NOFS */ int __page_symlink(struct inode *inode, const char *symname, int len, int nofs) { struct address_space *mapping = inode->i_mapping; struct page *page; void *fsdata; int err; char *kaddr; unsigned int flags = AOP_FLAG_UNINTERRUPTIBLE; if (nofs) flags |= AOP_FLAG_NOFS; retry: err = pagecache_write_begin(NULL, mapping, 0, len-1, flags, &page, &fsdata); if (err) goto fail; kaddr = kmap_atomic(page); memcpy(kaddr, symname, len-1); kunmap_atomic(kaddr); err = pagecache_write_end(NULL, mapping, 0, len-1, len-1, page, fsdata); if (err < 0) goto fail; if (err < len-1) goto retry; mark_inode_dirty(inode); return 0; fail: return err; } EXPORT_SYMBOL(__page_symlink); int page_symlink(struct inode *inode, const char *symname, int len) { return __page_symlink(inode, symname, len, !(mapping_gfp_mask(inode->i_mapping) & __GFP_FS)); } EXPORT_SYMBOL(page_symlink); const struct inode_operations page_symlink_inode_operations = { .readlink = generic_readlink, .follow_link = page_follow_link_light, .put_link = page_put_link, }; EXPORT_SYMBOL(page_symlink_inode_operations);
./CrossVul/dataset_final_sorted/CWE-254/c/good_1547_0
crossvul-cpp_data_good_5205_2
/** @file bzrtpParserTests.c @brief Test parsing and building ZRTP packet. @author Johan Pascal @copyright Copyright (C) 2014 Belledonne Communications, Grenoble, France 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdio.h> #include <stdlib.h> #include <errno.h> #include "CUnit/Basic.h" #ifndef _WIN32 #include <time.h> #else #include <windows.h> #endif #include "bzrtp/bzrtp.h" #include "typedef.h" #include "packetParser.h" #include "cryptoUtils.h" #include "zidCache.h" #include "testUtils.h" /** * Test pattern : the packet data in the patternZRTPPackets, length, sequence number and SSRC in patternZRTPMetaData * Pattern generated from wireshark trace * */ #define TEST_PACKET_NUMBER 9 /* meta data: length, sequence number, SSRC */ static uint32_t patternZRTPMetaData[TEST_PACKET_NUMBER][3] = { {136, 0x09f1, 0x12345678}, /* hello */ {136, 0x02ce, 0x87654321}, /* hello */ {28, 0x09f2, 0x12345678}, /* hello ack */ {132, 0x02d0, 0x87654321}, /* commit */ {484, 0x09f5, 0x12345678}, /* dhpart1 */ {484, 0x02d1, 0x87654321}, /* dhpart2 */ {92, 0x09f6, 0x12345678}, /* confirm 1 */ {92, 0x02d2, 0x87654321}, /* confirm 2 */ {28, 0x09f7, 0x12345678} /* conf2ACK*/ }; static const uint8_t patternZRTPPackets[TEST_PACKET_NUMBER][512] = { /* This is a Hello packet, sequence number is 0x09f1, SSRC 0x12345678 */ {0x10, 0x00, 0x09, 0xf1, 0x5a, 0x52, 0x54, 0x50, 0x12, 0x34, 0x56, 0x78, 0x50, 0x5a, 0x00, 0x1e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x20, 0x20, 0x31, 0x2e, 0x31, 0x30, 0x4c, 0x49, 0x4e, 0x50, 0x48, 0x4f, 0x4e, 0x45, 0x2d, 0x5a, 0x52, 0x54, 0x50, 0x43, 0x50, 0x50, 0xe8, 0xd5, 0x26, 0xc1, 0x3a, 0x0c, 0x4c, 0x6a, 0xce, 0x18, 0xaa, 0xc7, 0xc4, 0xa4, 0x07, 0x0e, 0x65, 0x7a, 0x4d, 0xca, 0x78, 0xf2, 0xcc, 0xcd, 0x20, 0x50, 0x38, 0x73, 0xe9, 0x7e, 0x08, 0x29, 0x7e, 0xb0, 0x04, 0x97, 0xc0, 0xfe, 0xb2, 0xc9, 0x24, 0x31, 0x49, 0x7f, 0x00, 0x01, 0x12, 0x31, 0x53, 0x32, 0x35, 0x36, 0x41, 0x45, 0x53, 0x31, 0x48, 0x53, 0x33, 0x32, 0x48, 0x53, 0x38, 0x30, 0x44, 0x48, 0x33, 0x6b, 0x44, 0x48, 0x32, 0x6b, 0x4d, 0x75, 0x6c, 0x74, 0x42, 0x33, 0x32, 0x20, 0xa0, 0xfd, 0x0f, 0xad, 0xeb, 0xe0, 0x86, 0x56, 0xe3, 0x65, 0x81, 0x02}, /* This is a Hello packet, sequence number is 0x02ce, SSRC 0x87654321 */ {0x10, 0x00, 0x02, 0xce, 0x5a, 0x52, 0x54, 0x50, 0x87, 0x65, 0x43, 0x21, 0x50, 0x5a, 0x00, 0x1e, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x20, 0x20, 0x31, 0x2e, 0x31, 0x30, 0x4c, 0x49, 0x4e, 0x50, 0x48, 0x4f, 0x4e, 0x45, 0x2d, 0x5a, 0x52, 0x54, 0x50, 0x43, 0x50, 0x50, 0x8d, 0x0f, 0x5a, 0x20, 0x79, 0x97, 0x42, 0x01, 0x99, 0x45, 0x45, 0xf7, 0x0e, 0x31, 0x06, 0xe1, 0x05, 0xc0, 0xb9, 0x24, 0xe9, 0xc9, 0x78, 0xc7, 0x38, 0xf5, 0x97, 0x48, 0xef, 0x42, 0x6a, 0x3e, 0x92, 0x42, 0xc2, 0xcf, 0x44, 0xee, 0x9c, 0x65, 0xca, 0x58, 0x78, 0xf1, 0x00, 0x01, 0x12, 0x31, 0x53, 0x32, 0x35, 0x36, 0x41, 0x45, 0x53, 0x31, 0x48, 0x53, 0x33, 0x32, 0x48, 0x53, 0x38, 0x30, 0x44, 0x48, 0x33, 0x6b, 0x44, 0x48, 0x32, 0x6b, 0x4d, 0x75, 0x6c, 0x74, 0x42, 0x33, 0x32, 0x20, 0xb3, 0x90, 0x91, 0x95, 0xe4, 0x67, 0xa3, 0x21, 0xe3, 0x5f, 0x9c, 0x92}, /* This is a Hello ack packet, sequence number is 0x09f2, SSRC 0x12345678*/ {0x10, 0x00, 0x09, 0xf2, 0x5a, 0x52, 0x54, 0x50, 0x12, 0x34, 0x56, 0x78, 0x50, 0x5a, 0x00, 0x03, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x41, 0x43, 0x4b, 0x77, 0x0e, 0x44, 0x07}, /* This is a Commit packet, sequence number is 0x02d0, SSRC 0x87654321 */ {0x10, 0x00, 0x02, 0xd0, 0x5a, 0x52, 0x54, 0x50, 0x87, 0x65, 0x43, 0x21, 0x50, 0x5a, 0x00, 0x1d, 0x43, 0x6f, 0x6d, 0x6d, 0x69, 0x74, 0x20, 0x20, 0xd9, 0xff, 0x14, 0x8b, 0x34, 0xaa, 0x69, 0xe9, 0x33, 0xc1, 0x62, 0xe6, 0x6b, 0xe8, 0xcd, 0x9d, 0xe3, 0x0f, 0xb7, 0x6a, 0xe8, 0x6a, 0x62, 0x2b, 0xcb, 0xe4, 0x6b, 0x91, 0x05, 0xc7, 0xc8, 0x7e, 0x92, 0x42, 0xc2, 0xcf, 0x44, 0xee, 0x9c, 0x65, 0xca, 0x58, 0x78, 0xf1, 0x53, 0x32, 0x35, 0x36, 0x41, 0x45, 0x53, 0x31, 0x48, 0x53, 0x33, 0x32, 0x44, 0x48, 0x33, 0x6b, 0x42, 0x33, 0x32, 0x20, 0x1e, 0xc0, 0xfe, 0x2e, 0x72, 0x06, 0x4d, 0xfb, 0xfc, 0x92, 0x02, 0x8c, 0x03, 0x0f, 0xb8, 0xf8, 0x91, 0xb4, 0xe7, 0x96, 0xac, 0x25, 0xfd, 0xf9, 0x68, 0xc6, 0xe9, 0x67, 0xa9, 0x42, 0xb1, 0x5b, 0xbb, 0x6d, 0x9c, 0xd2, 0x4b, 0x13, 0xa9, 0xae, 0x25, 0x5c, 0xa9, 0xc1}, /* This is a DHPart1 packet, sequence number is 0x09f5, SSRC 0x12345678 */ {0x10, 0x00, 0x09, 0xf5, 0x5a, 0x52, 0x54, 0x50, 0x12, 0x34, 0x56, 0x78, 0x50, 0x5a, 0x00, 0x75, 0x44, 0x48, 0x50, 0x61, 0x72, 0x74, 0x31, 0x20, 0x28, 0x7c, 0x28, 0xe4, 0xd7, 0x3d, 0x14, 0x39, 0xb5, 0x6d, 0x1c, 0x47, 0x9d, 0x59, 0x0a, 0xf2, 0x10, 0x33, 0xde, 0x6b, 0xd5, 0x2b, 0xfb, 0x26, 0xa5, 0x87, 0x4d, 0xe9, 0x20, 0x6b, 0x9f, 0xdd, 0xab, 0xbc, 0xc6, 0x8d, 0xbd, 0x5d, 0xe6, 0x67, 0x00, 0x69, 0x44, 0xb1, 0x84, 0x2c, 0x27, 0x10, 0x8c, 0x4e, 0x58, 0x8a, 0xed, 0x7e, 0x8b, 0x44, 0x2c, 0x3a, 0x13, 0x02, 0xdf, 0x58, 0xb6, 0xda, 0x80, 0x55, 0xec, 0xb0, 0x20, 0xc7, 0x76, 0x50, 0xc4, 0x1b, 0xa8, 0x26, 0x11, 0x5c, 0xf5, 0x71, 0x7e, 0xb4, 0x86, 0x22, 0x17, 0xde, 0x14, 0x08, 0x46, 0x5c, 0xac, 0x88, 0x8c, 0x41, 0x6b, 0x95, 0x22, 0xba, 0xf8, 0x3e, 0x67, 0x20, 0x94, 0xa0, 0x84, 0xa3, 0x93, 0x41, 0x9a, 0x1a, 0x7c, 0x2f, 0x04, 0xf4, 0x14, 0x3f, 0x11, 0x54, 0x02, 0xba, 0xee, 0xc2, 0x20, 0xfa, 0x38, 0xf7, 0xba, 0xa4, 0xbf, 0x4a, 0x70, 0x02, 0x68, 0xdc, 0xb2, 0xe9, 0x1a, 0x8a, 0x87, 0xa5, 0xe4, 0x9c, 0x42, 0x07, 0x82, 0x26, 0xb4, 0xda, 0xe3, 0x1b, 0xdc, 0x78, 0xc7, 0xd8, 0xa8, 0x00, 0x5c, 0x00, 0x14, 0xe4, 0x00, 0xfe, 0x6c, 0x2d, 0xce, 0x62, 0xc9, 0x71, 0x5d, 0xed, 0x4e, 0x66, 0x9f, 0xf5, 0x30, 0xc0, 0x04, 0x53, 0xf6, 0x15, 0x2f, 0xe1, 0x85, 0x3b, 0xd9, 0x40, 0x9b, 0x50, 0x07, 0x43, 0x7c, 0x36, 0x01, 0xa1, 0xda, 0x66, 0xc4, 0x20, 0x2f, 0x45, 0xc0, 0xcc, 0xb2, 0x64, 0x63, 0x9c, 0x07, 0x9d, 0x23, 0x27, 0x80, 0xa1, 0x7f, 0xc2, 0xe0, 0xa0, 0xfd, 0xc3, 0x98, 0x83, 0xa3, 0xaa, 0x6b, 0xdc, 0x9f, 0x6a, 0xc3, 0x32, 0x94, 0xf0, 0x80, 0xa0, 0xd9, 0xf1, 0x83, 0x41, 0x48, 0xa9, 0xb5, 0xed, 0x62, 0x50, 0x88, 0xec, 0x33, 0x32, 0xd2, 0x5f, 0xdc, 0xcc, 0xae, 0xc9, 0x74, 0xca, 0x0a, 0xab, 0x82, 0x06, 0x01, 0x46, 0x35, 0x30, 0xcd, 0x68, 0xec, 0x09, 0xab, 0x8c, 0xb0, 0x39, 0xe5, 0xd8, 0x5c, 0xa2, 0xe4, 0x82, 0xfe, 0x46, 0x01, 0xbd, 0xe7, 0x7f, 0x60, 0x1b, 0x50, 0x62, 0xfb, 0x6f, 0xee, 0x6c, 0xf1, 0xf7, 0x9b, 0xb7, 0x1c, 0x76, 0x48, 0xb5, 0xbe, 0xa5, 0x83, 0x73, 0x07, 0xa2, 0xe2, 0x73, 0xc7, 0x68, 0x34, 0xc8, 0xef, 0x12, 0xc4, 0x32, 0xdf, 0x37, 0x3d, 0xdc, 0x07, 0x0e, 0xa6, 0x92, 0x82, 0xbd, 0xba, 0x20, 0xc4, 0xb4, 0x8d, 0x1f, 0x19, 0x1c, 0x15, 0x0f, 0x5f, 0x01, 0xdf, 0x67, 0x1f, 0x59, 0xd1, 0x5e, 0x99, 0x60, 0xf6, 0xb8, 0x67, 0xe2, 0x46, 0x62, 0x11, 0x30, 0xfb, 0x81, 0x9d, 0x0b, 0xec, 0x36, 0xe9, 0x8d, 0x43, 0xfe, 0x55, 0xd9, 0x61, 0x98, 0x3f, 0x2e, 0x39, 0x6a, 0x26, 0x43, 0xb0, 0x6d, 0x08, 0xec, 0x2e, 0x42, 0x7e, 0x23, 0x82, 0x6f, 0xd9, 0xbb, 0xfd, 0x0a, 0xcd, 0x48, 0xe7, 0xd5, 0x8b, 0xa5, 0x80, 0x34, 0xca, 0x96, 0x4f, 0x58, 0x25, 0xba, 0x43, 0x5e, 0x3d, 0x1c, 0xee, 0x72, 0xb8, 0x35, 0x8c, 0x5d, 0xd9, 0x69, 0x24, 0x58, 0x36, 0x21, 0xb0, 0x45, 0xa4, 0xad, 0x40, 0xda, 0x94, 0x98, 0x0f, 0xb1, 0xed, 0x6c, 0xad, 0x26, 0x03, 0x04, 0x82, 0xff, 0x15, 0x00, 0x41, 0x87, 0x06, 0x93, 0xd4, 0x86, 0xa9, 0x7e, 0xb8, 0xd9, 0x70, 0x34, 0x6d, 0x8e, 0x6a, 0x16, 0xe2, 0x46, 0x52, 0xb0, 0x78, 0x54, 0x53, 0xaf}, /* This is a DHPart2 packet, sequence number is 0x02d1, SSRC 0x87654321 */ {0x10, 0x00, 0x02, 0xd1, 0x5a, 0x52, 0x54, 0x50, 0x87, 0x65, 0x43, 0x21, 0x50, 0x5a, 0x00, 0x75, 0x44, 0x48, 0x50, 0x61, 0x72, 0x74, 0x32, 0x20, 0x9e, 0xb2, 0xa5, 0x8b, 0xe8, 0x96, 0x37, 0xf5, 0x5a, 0x41, 0x34, 0xb2, 0xec, 0xda, 0x84, 0x95, 0xf0, 0xf8, 0x9b, 0xab, 0x61, 0x4f, 0x7c, 0x9e, 0x56, 0xb7, 0x3b, 0xd3, 0x46, 0xba, 0xbe, 0x9a, 0xae, 0x97, 0x97, 0xda, 0x5f, 0x9f, 0x89, 0xba, 0xfe, 0x61, 0x66, 0x5f, 0x9e, 0xa4, 0x5b, 0xcb, 0xd5, 0x69, 0xcf, 0xfb, 0xfd, 0xdc, 0xac, 0x79, 0xac, 0x1d, 0x0b, 0xe5, 0x15, 0x75, 0x39, 0x2e, 0xe5, 0xa9, 0x2a, 0x60, 0xd7, 0xe3, 0x48, 0xd0, 0x1f, 0xd8, 0x61, 0x65, 0xfd, 0x2e, 0x5c, 0xef, 0x43, 0xf5, 0x63, 0x99, 0xb3, 0x45, 0x25, 0xe3, 0xbc, 0xf0, 0xe1, 0xad, 0xf7, 0x84, 0xcd, 0x82, 0x20, 0xe3, 0x6f, 0x2c, 0x77, 0x51, 0xf1, 0x11, 0x2e, 0x4a, 0x2c, 0xfd, 0x2f, 0x5e, 0x74, 0xa9, 0x37, 0x99, 0xff, 0xf7, 0x4c, 0x2d, 0xa8, 0xcf, 0x51, 0xfd, 0x5b, 0xe7, 0x51, 0x14, 0x6d, 0xbc, 0x2f, 0x5b, 0xb9, 0x77, 0x85, 0xad, 0xb4, 0x72, 0x99, 0xad, 0x7b, 0x6c, 0x6a, 0xdf, 0x4d, 0xca, 0x2f, 0xef, 0x8b, 0x5e, 0x4b, 0xf3, 0xd9, 0xfd, 0xbd, 0x47, 0x1a, 0x72, 0xe2, 0x41, 0xd8, 0xfa, 0xa1, 0x25, 0x00, 0xa3, 0xfe, 0x12, 0xda, 0xf6, 0x16, 0xb3, 0xb3, 0x08, 0x02, 0xfd, 0x0a, 0x6a, 0xab, 0x85, 0x17, 0xd7, 0x0f, 0xf4, 0x6b, 0xdf, 0x8f, 0xe2, 0x05, 0xf4, 0x5b, 0x13, 0x26, 0xa9, 0xe2, 0x57, 0xb6, 0xda, 0x76, 0x17, 0x3c, 0x52, 0x13, 0x8d, 0x83, 0xc0, 0x2b, 0xe7, 0x2e, 0xbd, 0xb0, 0xde, 0x98, 0x4f, 0x7a, 0x95, 0xa1, 0x75, 0x19, 0x6e, 0xda, 0x19, 0xff, 0x7f, 0xdd, 0x70, 0x01, 0x12, 0x3c, 0x9e, 0xd7, 0xfe, 0xc3, 0x22, 0x39, 0xce, 0x4f, 0x86, 0xd8, 0x85, 0x40, 0x75, 0xd4, 0xfe, 0x93, 0x57, 0xbc, 0x9b, 0x01, 0xa4, 0x71, 0x35, 0x70, 0x9d, 0x62, 0x91, 0x47, 0x4e, 0x32, 0xa2, 0x76, 0x16, 0x06, 0xaf, 0xc7, 0xe3, 0xe5, 0xdc, 0x25, 0xac, 0xe7, 0x68, 0x25, 0x69, 0x0f, 0x97, 0x8d, 0x91, 0x32, 0x81, 0x23, 0xb1, 0x08, 0xf3, 0xa3, 0x2b, 0x3d, 0xfb, 0xcf, 0x99, 0x12, 0x0a, 0x59, 0xb9, 0xbb, 0x76, 0x16, 0x71, 0xa2, 0x0b, 0x0a, 0x5a, 0x6c, 0x37, 0x99, 0x9d, 0xe6, 0x3a, 0x05, 0x89, 0xf7, 0xc6, 0xfc, 0xf3, 0xfe, 0x36, 0x97, 0x77, 0x86, 0xe4, 0x7c, 0x48, 0x93, 0x0b, 0x26, 0x8e, 0x31, 0xe9, 0x22, 0xcc, 0xd3, 0xe0, 0x56, 0x29, 0xc8, 0x26, 0xe6, 0x1f, 0xa8, 0xb8, 0x93, 0x98, 0xec, 0xd9, 0x7c, 0x4a, 0x45, 0xd3, 0x71, 0x35, 0x9f, 0x14, 0xc1, 0x99, 0xd5, 0x21, 0x0b, 0xfa, 0x0f, 0xfb, 0x31, 0x7a, 0xa0, 0x70, 0x35, 0xb3, 0x9b, 0x1b, 0xe7, 0x65, 0xfd, 0xe3, 0x7d, 0x0b, 0xcc, 0x34, 0x4b, 0xf1, 0x5a, 0x9f, 0x19, 0xa4, 0x8f, 0xc8, 0x30, 0xf1, 0x87, 0x99, 0xc2, 0x75, 0x55, 0x2a, 0x34, 0xd7, 0x81, 0x9c, 0x54, 0x12, 0x82, 0x69, 0x5f, 0x8b, 0x01, 0xc1, 0x45, 0x95, 0xf5, 0xb1, 0x2d, 0x27, 0x0d, 0xa9, 0xc3, 0x93, 0x54, 0x2f, 0x57, 0x04, 0x7b, 0x20, 0xb7, 0xac, 0x33, 0x68, 0xb3, 0xef, 0x9a, 0x33, 0x95, 0x82, 0x9d, 0xfa, 0x2a, 0xb9, 0x88, 0x06, 0x04, 0x88, 0x51, 0x2c, 0x46, 0xdb, 0x83, 0xd7, 0x2f, 0xea, 0x1f, 0x0f, 0x24, 0xab, 0x03, 0xef, 0xb0, 0x61, 0xc7, 0x90, 0xdc, 0x78, 0x17, 0xf2, 0x9a, 0xab}, /* This is a confirm1 packet, sequence number is 0x09f6, SSRC 0x12345678 */ {0x10, 0x00, 0x09, 0xf6, 0x5a, 0x52, 0x54, 0x50, 0x12, 0x34, 0x56, 0x78, 0x50, 0x5a, 0x00, 0x13, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x31, 0xb1, 0x21, 0xee, 0xe2, 0x67, 0xa4, 0xfd, 0xa6, 0x94, 0x24, 0x9a, 0x60, 0xf0, 0x2e, 0x5e, 0xd9, 0x33, 0xe1, 0xd8, 0x41, 0x54, 0xa3, 0x7c, 0xea, 0xe9, 0x61, 0xae, 0xf9, 0x19, 0x0d, 0xb3, 0x68, 0x68, 0x9e, 0xf8, 0x1a, 0x18, 0x91, 0x87, 0xc5, 0x6e, 0x5e, 0x2d, 0x5e, 0x32, 0xa2, 0xb2, 0x66, 0x31, 0xb8, 0xe5, 0x59, 0xc9, 0x10, 0xbb, 0xa0, 0x00, 0x6c, 0xee, 0x0c, 0x6d, 0xfb, 0xeb, 0x32, 0x85, 0xb6, 0x6e, 0x93}, /* This is a confirm2 packet, sequence number is 0x02d2, SSRC 0x87654321 */ {0x10, 0x00, 0x02, 0xd2, 0x5a, 0x52, 0x54, 0x50, 0x87, 0x65, 0x43, 0x21, 0x50, 0x5a, 0x00, 0x13, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x32, 0x0f, 0xec, 0xfa, 0x4b, 0x45, 0x17, 0x9d, 0xb3, 0x92, 0x7d, 0x1c, 0x53, 0x86, 0x01, 0x12, 0xd9, 0x25, 0x48, 0xca, 0x18, 0xb9, 0x10, 0x95, 0x04, 0xb7, 0xc8, 0xee, 0x87, 0x2b, 0xec, 0x59, 0x39, 0x92, 0x96, 0x11, 0x73, 0xa6, 0x69, 0x2b, 0x11, 0xcd, 0x1d, 0xa1, 0x73, 0xb2, 0xc9, 0x29, 0x6f, 0x82, 0x32, 0x6a, 0x0a, 0x56, 0x40, 0x57, 0xfb, 0xac, 0xab, 0x20, 0xb8, 0xe2, 0xa9, 0x2c, 0x61, 0x6a, 0x05, 0xe8, 0xb5}, /* This is a conf2ACK packet, sequence number 0x09f7, SSRC 0x12345678 */ {0x10, 0x00, 0x09, 0xf7, 0x5a, 0x52, 0x54, 0x50, 0x12, 0x34, 0x56, 0x78, 0x50, 0x5a, 0x00, 0x03, 0x43, 0x6f, 0x6e, 0x66, 0x32, 0x41, 0x43, 0x4b, 0x23, 0xc1, 0x1b, 0x45}, }; /* Hash images for both sides */ uint8_t H12345678[4][32] = { {0xbb, 0xbf, 0x7e, 0xb1, 0x14, 0xd5, 0xd4, 0x0c, 0x6b, 0xb0, 0x79, 0x58, 0x19, 0xc1, 0xd0, 0x83, 0xc9, 0xe1, 0xf4, 0x2e, 0x11, 0xcd, 0x7e, 0xc3, 0xaa, 0xd8, 0xb9, 0x17, 0xe6, 0xb5, 0x9e, 0x86}, {0x28, 0x7c, 0x28, 0xe4, 0xd7, 0x3d, 0x14, 0x39, 0xb5, 0x6d, 0x1c, 0x47, 0x9d, 0x59, 0x0a, 0xf2, 0x10, 0x33, 0xde, 0x6b, 0xd5, 0x2b, 0xfb, 0x26, 0xa5, 0x87, 0x4d, 0xe9, 0x20, 0x6b, 0x9f, 0xdd}, {0x70, 0x12, 0xef, 0x2e, 0x85, 0x2f, 0xfc, 0x84, 0xb8, 0x8d, 0xcc, 0x03, 0xd7, 0x8f, 0x53, 0x01, 0x63, 0xfb, 0xd3, 0xb0, 0x2d, 0xbb, 0x9e, 0x98, 0x22, 0x0d, 0xe3, 0xe3, 0x64, 0x25, 0x04, 0x0f}, {0xe8, 0xd5, 0x26, 0xc1, 0x3a, 0x0c, 0x4c, 0x6a, 0xce, 0x18, 0xaa, 0xc7, 0xc4, 0xa4, 0x07, 0x0e, 0x65, 0x7a, 0x4d, 0xca, 0x78, 0xf2, 0xcc, 0xcd, 0x20, 0x50, 0x38, 0x73, 0xe9, 0x7e, 0x08, 0x29} }; uint8_t H87654321[4][32] = { {0x09, 0x02, 0xcc, 0x13, 0xc4, 0x84, 0x03, 0x31, 0x68, 0x91, 0x05, 0x4d, 0xe0, 0x6d, 0xf4, 0xc9, 0x6a, 0xb5, 0xbe, 0x82, 0xe8, 0x37, 0x33, 0xb7, 0xa9, 0xce, 0xbe, 0xb5, 0x42, 0xaa, 0x54, 0xba}, {0x9e, 0xb2, 0xa5, 0x8b, 0xe8, 0x96, 0x37, 0xf5, 0x5a, 0x41, 0x34, 0xb2, 0xec, 0xda, 0x84, 0x95, 0xf0, 0xf8, 0x9b, 0xab, 0x61, 0x4f, 0x7c, 0x9e, 0x56, 0xb7, 0x3b, 0xd3, 0x46, 0xba, 0xbe, 0x9a}, {0xd9, 0xff, 0x14, 0x8b, 0x34, 0xaa, 0x69, 0xe9, 0x33, 0xc1, 0x62, 0xe6, 0x6b, 0xe8, 0xcd, 0x9d, 0xe3, 0x0f, 0xb7, 0x6a, 0xe8, 0x6a, 0x62, 0x2b, 0xcb, 0xe4, 0x6b, 0x91, 0x05, 0xc7, 0xc8, 0x7e}, {0x8d, 0x0f, 0x5a, 0x20, 0x79, 0x97, 0x42, 0x01, 0x99, 0x45, 0x45, 0xf7, 0x0e, 0x31, 0x06, 0xe1, 0x05, 0xc0, 0xb9, 0x24, 0xe9, 0xc9, 0x78, 0xc7, 0x38, 0xf5, 0x97, 0x48, 0xef, 0x42, 0x6a, 0x3e} }; /* mac and zrtp keys */ uint8_t mackeyi[32] = {0xdc, 0x47, 0xe1, 0xc7, 0x48, 0x11, 0xb1, 0x54, 0x14, 0x2a, 0x91, 0x29, 0x9f, 0xa4, 0x8b, 0x45, 0x87, 0x16, 0x8d, 0x3a, 0xe6, 0xb0, 0x0c, 0x08, 0x4f, 0xa5, 0x48, 0xd5, 0x96, 0x67, 0x1a, 0x1b}; uint8_t mackeyr[32] = {0x3a, 0xa5, 0x22, 0x43, 0x26, 0x13, 0x8f, 0xd6, 0x54, 0x59, 0x40, 0xb8, 0x5c, 0xf4, 0x0f, 0x0c, 0xbc, 0x9c, 0x4f, 0x7d, 0x55, 0xeb, 0x4b, 0xa5, 0x1e, 0x1c, 0x42, 0xd0, 0x5e, 0xac, 0x12, 0x06}; uint8_t zrtpkeyi[16] = {0x22, 0xf6, 0xea, 0xaa, 0xa4, 0xad, 0x53, 0x30, 0x71, 0x97, 0xcc, 0x68, 0x6b, 0xb0, 0xcb, 0x55}; uint8_t zrtpkeyr[16] = {0x09, 0x50, 0xcd, 0x9e, 0xc2, 0x78, 0x54, 0x31, 0x93, 0x2e, 0x99, 0x31, 0x15, 0x58, 0xd0, 0x2a}; void test_parser_param(uint8_t hvi_trick) { int i, retval; bzrtpPacket_t *zrtpPacket; /* Create zrtp Context to use H0-H3 chains and others */ bzrtpContext_t *context87654321 = bzrtp_createBzrtpContext(0x87654321); bzrtpContext_t *context12345678 = bzrtp_createBzrtpContext(0x12345678); /* replace created H by the patterns one to be able to generate the correct packet */ memcpy (context12345678->channelContext[0]->selfH[0], H12345678[0], 32); memcpy (context12345678->channelContext[0]->selfH[1], H12345678[1], 32); memcpy (context12345678->channelContext[0]->selfH[2], H12345678[2], 32); memcpy (context12345678->channelContext[0]->selfH[3], H12345678[3], 32); memcpy (context87654321->channelContext[0]->selfH[0], H87654321[0], 32); memcpy (context87654321->channelContext[0]->selfH[1], H87654321[1], 32); memcpy (context87654321->channelContext[0]->selfH[2], H87654321[2], 32); memcpy (context87654321->channelContext[0]->selfH[3], H87654321[3], 32); /* preset the key agreement algo in the contexts */ context87654321->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context12345678->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context87654321->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context12345678->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context87654321->channelContext[0]->hashAlgo = ZRTP_HASH_S256; context12345678->channelContext[0]->hashAlgo = ZRTP_HASH_S256; updateCryptoFunctionPointers(context87654321->channelContext[0]); updateCryptoFunctionPointers(context12345678->channelContext[0]); /* set the zrtp and mac keys */ context87654321->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context87654321->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context87654321->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context87654321->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); memcpy(context12345678->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context12345678->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context12345678->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context12345678->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); memcpy(context87654321->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context87654321->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context87654321->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context87654321->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); /* set the role: 87654321 is initiator in our exchange pattern */ context12345678->channelContext[0]->role = RESPONDER; for (i=0; i<TEST_PACKET_NUMBER; i++) { uint8_t freePacketFlag = 1; /* parse a packet string from patterns */ zrtpPacket = bzrtp_packetCheck(patternZRTPPackets[i], patternZRTPMetaData[i][0], (patternZRTPMetaData[i][1])-1, &retval); retval += bzrtp_packetParser((patternZRTPMetaData[i][2]==0x87654321)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x87654321)?context12345678->channelContext[0]:context87654321->channelContext[0], patternZRTPPackets[i], patternZRTPMetaData[i][0], zrtpPacket); if (hvi_trick==0) { CU_ASSERT_EQUAL_FATAL(retval,0); } else { /* when hvi trick is enable, the DH2 parsing shall fail and return BZRTP_PARSER_ERROR_UNMATCHINGHVI */ if (zrtpPacket->messageType==MSGTYPE_DHPART2) { CU_ASSERT_EQUAL_FATAL(retval, BZRTP_PARSER_ERROR_UNMATCHINGHVI); /* We shall then anyway skip the end of the test */ /* reset pointers to selfHello packet in order to avoid double free */ context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); return; } else { CU_ASSERT_EQUAL_FATAL(retval,0); } } bzrtp_message("parsing Ret val is %x index is %d\n", retval, i); /* We must store some packets in the context if we want to be able to parse further packets */ if (zrtpPacket->messageType==MSGTYPE_HELLO) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_DHPART1 || zrtpPacket->messageType==MSGTYPE_DHPART2) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } /* free the packet string as will be created again by the packetBuild function and might have been copied by packetParser */ free(zrtpPacket->packetString); /* build a packet string from the parser packet*/ retval = bzrtp_packetBuild((patternZRTPMetaData[i][2]==0x12345678)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x12345678)?context12345678->channelContext[0]:context87654321->channelContext[0], zrtpPacket, patternZRTPMetaData[i][1]); /* if (retval ==0) { packetDump(zrtpPacket, 1); } else { bzrtp_message("Ret val is %x index is %d\n", retval, i); }*/ /* check they are the same */ if (zrtpPacket->packetString != NULL) { CU_ASSERT_TRUE(memcmp(zrtpPacket->packetString, patternZRTPPackets[i], patternZRTPMetaData[i][0]) == 0); } else { CU_FAIL("Unable to build packet"); } if (freePacketFlag == 1) { bzrtp_freeZrtpPacket(zrtpPacket); } /* modify the hvi stored in the peerPackets, this shall result in parsing failure on DH2 packet */ if (hvi_trick == 1) { if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { bzrtpCommitMessage_t *peerCommitMessageData; peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpPacket->messageData; peerCommitMessageData->hvi[0]=0xFF; } } } } /* reset pointers to selfHello packet in order to avoid double free */ context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); } void test_parser(void) { test_parser_param(0); } void test_parser_hvi(void) { test_parser_param(1); } /* context structure mainly used by statemachine test, but also needed by parserComplete to get the zid Filename */ typedef struct my_Context_struct { unsigned char nom[30]; /* nom du contexte */ bzrtpContext_t *peerContext; bzrtpChannelContext_t *peerChannelContext; char zidFilename[80]; /* nom du fichier de cache */ } my_Context_t; static void freeBuf(void* p){ free(p); } int floadAlice(void *clientData, uint8_t **output, uint32_t *size, zrtpFreeBuffer_callback *cb) { /* get filename from ClientData */ my_Context_t *clientContext = (my_Context_t *)clientData; char *filename = clientContext->zidFilename; FILE *ALICECACHE = fopen(filename, "r+"); fseek(ALICECACHE, 0L, SEEK_END); /* Position to end of file */ *size = ftell(ALICECACHE); /* Get file length */ rewind(ALICECACHE); /* Back to start of file */ *output = (uint8_t *)malloc(*size*sizeof(uint8_t)+1); if (fread(*output, 1, *size, ALICECACHE)==0){ fprintf(stderr,"floadAlice() fread() error\n"); } *(*output+*size) = '\0'; *size += 1; fclose(ALICECACHE); *cb=freeBuf; return *size; } int fwriteAlice(void *clientData, const uint8_t *input, uint32_t size) { /* get filename from ClientData */ my_Context_t *clientContext = (my_Context_t *)clientData; char *filename = clientContext->zidFilename; FILE *ALICECACHE = fopen(filename, "w+"); int retval = fwrite(input, 1, size, ALICECACHE); fclose(ALICECACHE); return retval; } int floadBob(void *clientData, uint8_t **output, uint32_t *size, zrtpFreeBuffer_callback *cb) { /* get filename from ClientData */ my_Context_t *clientContext = (my_Context_t *)clientData; char *filename = clientContext->zidFilename; FILE *BOBCACHE = fopen(filename, "r+"); fseek(BOBCACHE, 0L, SEEK_END); /* Position to end of file */ *size = ftell(BOBCACHE); /* Get file length */ rewind(BOBCACHE); /* Back to start of file */ *output = (uint8_t *)malloc(*size*sizeof(uint8_t)+1); if (fread(*output, 1, *size, BOBCACHE)==0){ fprintf(stderr,"floadBob(): fread error.\n"); return -1; } *(*output+*size) = '\0'; *size += 1; fclose(BOBCACHE); *cb=freeBuf; return *size; } int fwriteBob(void *clientData, const uint8_t *input, uint32_t size) { /* get filename from ClientData */ my_Context_t *clientContext = (my_Context_t *)clientData; char *filename = clientContext->zidFilename; FILE *BOBCACHE = fopen(filename, "w+"); int retval = fwrite(input, 1, size, BOBCACHE); fclose(BOBCACHE); return retval; } void test_parserComplete() { int retval; /* alice's maintained packet */ bzrtpPacket_t *alice_Hello, *alice_HelloFromBob, *alice_HelloACK, *alice_HelloACKFromBob; /* bob's maintained packet */ bzrtpPacket_t *bob_Hello, *bob_HelloFromAlice, *bob_HelloACK, *bob_HelloACKFromAlice; /* Create zrtp Context */ bzrtpContext_t *contextAlice = bzrtp_createBzrtpContext(0x12345678); /* Alice's SSRC of main channel is 12345678 */ bzrtpContext_t *contextBob = bzrtp_createBzrtpContext(0x87654321); /* Bob's SSRC of main channel is 87654321 */ bzrtpHelloMessage_t *alice_HelloFromBob_message; bzrtpHelloMessage_t *bob_HelloFromAlice_message; bzrtpPacket_t *alice_selfDHPart; bzrtpPacket_t *bob_selfDHPart; bzrtpPacket_t *alice_Commit; bzrtpPacket_t *bob_Commit; bzrtpPacket_t *bob_CommitFromAlice; bzrtpPacket_t *alice_CommitFromBob; uint8_t tmpBuffer[8]; bzrtpDHPartMessage_t *bob_DHPart1; bzrtpPacket_t *alice_DHPart1FromBob; bzrtpDHPartMessage_t *alice_DHPart1FromBob_message=NULL; bzrtpPacket_t *bob_DHPart2FromAlice; bzrtpDHPartMessage_t *bob_DHPart2FromAlice_message=NULL; uint16_t secretLength; uint16_t totalHashDataLength; uint8_t *dataToHash; uint16_t hashDataIndex = 0; uint8_t alice_totalHash[32]; /* Note : actual length of hash depends on the choosen algo */ uint8_t bob_totalHash[32]; /* Note : actual length of hash depends on the choosen algo */ uint8_t *s1=NULL; uint32_t s1Length=0; uint8_t *s2=NULL; uint32_t s2Length=0; uint8_t *s3=NULL; uint32_t s3Length=0; uint8_t alice_sasHash[32]; uint8_t bob_sasHash[32]; uint32_t sasValue; char sas[32]; bzrtpPacket_t *bob_Confirm1; bzrtpPacket_t *alice_Confirm1FromBob; bzrtpConfirmMessage_t *alice_Confirm1FromBob_message=NULL; bzrtpPacket_t *alice_Confirm2; bzrtpPacket_t *bob_Confirm2FromAlice; bzrtpConfirmMessage_t *bob_Confirm2FromAlice_message=NULL; bzrtpPacket_t *bob_Conf2ACK; bzrtpPacket_t *alice_Conf2ACKFromBob; bzrtpPacket_t *alice_Confirm1; bzrtpPacket_t *bob_Confirm1FromAlice; bzrtpConfirmMessage_t *bob_Confirm1FromAlice_message=NULL; bzrtpPacket_t *bob_Confirm2; bzrtpPacket_t *alice_Confirm2FromBob; bzrtpConfirmMessage_t *alice_Confirm2FromBob_message=NULL; bzrtpPacket_t *alice_Conf2ACK; bzrtpPacket_t *bob_Conf2ACKFromAlice; bzrtpCallbacks_t cbs={0}; /* Create the client context, used for zidFilename only */ my_Context_t clientContextAlice; my_Context_t clientContextBob; strcpy(clientContextAlice.zidFilename, "./ZIDAlice.txt"); strcpy(clientContextBob.zidFilename, "./ZIDBob.txt"); /* attach the clientContext to the bzrtp Context */ retval = bzrtp_setClientData(contextAlice, 0x12345678, (void *)&clientContextAlice); retval += bzrtp_setClientData(contextBob, 0x87654321, (void *)&clientContextBob); /* set the cache related callback functions */ cbs.bzrtp_loadCache=floadAlice; cbs.bzrtp_writeCache=fwriteAlice; bzrtp_setCallbacks(contextAlice, &cbs); cbs.bzrtp_loadCache=floadBob; cbs.bzrtp_writeCache=fwriteBob; bzrtp_setCallbacks(contextBob, &cbs); bzrtp_message ("Init the contexts\n"); /* end the context init */ bzrtp_initBzrtpContext(contextAlice); bzrtp_initBzrtpContext(contextBob); /* now create Alice and BOB Hello packet */ alice_Hello = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[0], MSGTYPE_HELLO, &retval); if (bzrtp_packetBuild(contextAlice, contextAlice->channelContext[0], alice_Hello, contextAlice->channelContext[0]->selfSequenceNumber) ==0) { contextAlice->channelContext[0]->selfSequenceNumber++; contextAlice->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = alice_Hello; } bob_Hello = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_HELLO, &retval); if (bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_Hello, contextBob->channelContext[0]->selfSequenceNumber) ==0) { contextBob->channelContext[0]->selfSequenceNumber++; contextBob->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = bob_Hello; } /* now send Alice Hello's to Bob and vice-versa, so they parse them */ alice_HelloFromBob = bzrtp_packetCheck(bob_Hello->packetString, bob_Hello->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_Hello->packetString, bob_Hello->messageLength+16, alice_HelloFromBob); bzrtp_message ("Alice parsing returns %x\n", retval); if (retval==0) { bzrtpHelloMessage_t *alice_HelloFromBob_message; int i; contextAlice->channelContext[0]->peerSequenceNumber = alice_HelloFromBob->sequenceNumber; /* save bob's Hello packet in Alice's context */ contextAlice->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = alice_HelloFromBob; /* determine crypto Algo to use */ alice_HelloFromBob_message = (bzrtpHelloMessage_t *)alice_HelloFromBob->messageData; retval = crypoAlgoAgreement(contextAlice, contextAlice->channelContext[0], contextAlice->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData); if (retval == 0) { bzrtp_message ("Alice selected algo %x\n", contextAlice->channelContext[0]->keyAgreementAlgo); memcpy(contextAlice->peerZID, alice_HelloFromBob_message->ZID, 12); } /* check if the peer accept MultiChannel */ for (i=0; i<alice_HelloFromBob_message->kc; i++) { if (alice_HelloFromBob_message->supportedKeyAgreement[i] == ZRTP_KEYAGREEMENT_Mult) { contextAlice->peerSupportMultiChannel = 1; } } } bob_HelloFromAlice = bzrtp_packetCheck(alice_Hello->packetString, alice_Hello->messageLength+16, contextBob->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[0], alice_Hello->packetString, alice_Hello->messageLength+16, bob_HelloFromAlice); bzrtp_message ("Bob parsing returns %x\n", retval); if (retval==0) { bzrtpHelloMessage_t *bob_HelloFromAlice_message; int i; contextBob->channelContext[0]->peerSequenceNumber = bob_HelloFromAlice->sequenceNumber; /* save alice's Hello packet in bob's context */ contextBob->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = bob_HelloFromAlice; /* determine crypto Algo to use */ bob_HelloFromAlice_message = (bzrtpHelloMessage_t *)bob_HelloFromAlice->messageData; retval = crypoAlgoAgreement(contextBob, contextBob->channelContext[0], contextBob->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData); if (retval == 0) { bzrtp_message ("Bob selected algo %x\n", contextBob->channelContext[0]->keyAgreementAlgo); memcpy(contextBob->peerZID, bob_HelloFromAlice_message->ZID, 12); } /* check if the peer accept MultiChannel */ for (i=0; i<bob_HelloFromAlice_message->kc; i++) { if (bob_HelloFromAlice_message->supportedKeyAgreement[i] == ZRTP_KEYAGREEMENT_Mult) { contextBob->peerSupportMultiChannel = 1; } } } /* update context with hello message information : H3 and compute initiator and responder's shared secret Hashs */ alice_HelloFromBob_message = (bzrtpHelloMessage_t *)alice_HelloFromBob->messageData; memcpy(contextAlice->channelContext[0]->peerH[3], alice_HelloFromBob_message->H3, 32); bob_HelloFromAlice_message = (bzrtpHelloMessage_t *)bob_HelloFromAlice->messageData; memcpy(contextBob->channelContext[0]->peerH[3], bob_HelloFromAlice_message->H3, 32); /* get the secrets associated to peer ZID */ bzrtp_getPeerAssociatedSecretsHash(contextAlice, alice_HelloFromBob_message->ZID); bzrtp_getPeerAssociatedSecretsHash(contextBob, bob_HelloFromAlice_message->ZID); /* compute the initiator hashed secret as in rfc section 4.3.1 */ if (contextAlice->cachedSecret.rs1!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.rs1, contextAlice->cachedSecret.rs1Length, (uint8_t *)"Initiator", 9, 8, contextAlice->initiatorCachedSecretHash.rs1ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->initiatorCachedSecretHash.rs1ID, 8); } if (contextAlice->cachedSecret.rs2!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.rs2, contextAlice->cachedSecret.rs2Length, (uint8_t *)"Initiator", 9, 8, contextAlice->initiatorCachedSecretHash.rs2ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->initiatorCachedSecretHash.rs2ID, 8); } if (contextAlice->cachedSecret.auxsecret!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.auxsecret, contextAlice->cachedSecret.auxsecretLength, contextAlice->channelContext[0]->selfH[3], 32, 8, contextAlice->channelContext[0]->initiatorAuxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->channelContext[0]->initiatorAuxsecretID, 8); } if (contextAlice->cachedSecret.pbxsecret!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.pbxsecret, contextAlice->cachedSecret.pbxsecretLength, (uint8_t *)"Initiator", 9, 8, contextAlice->initiatorCachedSecretHash.pbxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->initiatorCachedSecretHash.pbxsecretID, 8); } if (contextAlice->cachedSecret.rs1!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.rs1, contextAlice->cachedSecret.rs1Length, (uint8_t *)"Responder", 9, 8, contextAlice->responderCachedSecretHash.rs1ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->responderCachedSecretHash.rs1ID, 8); } if (contextAlice->cachedSecret.rs2!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.rs2, contextAlice->cachedSecret.rs2Length, (uint8_t *)"Responder", 9, 8, contextAlice->responderCachedSecretHash.rs2ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->responderCachedSecretHash.rs2ID, 8); } if (contextAlice->cachedSecret.auxsecret!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.auxsecret, contextAlice->cachedSecret.auxsecretLength, contextAlice->channelContext[0]->peerH[3], 32, 8, contextAlice->channelContext[0]->responderAuxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->channelContext[0]->responderAuxsecretID, 8); } if (contextAlice->cachedSecret.pbxsecret!=NULL) { contextAlice->channelContext[0]->hmacFunction(contextAlice->cachedSecret.pbxsecret, contextAlice->cachedSecret.pbxsecretLength, (uint8_t *)"Responder", 9, 8, contextAlice->responderCachedSecretHash.pbxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextAlice->RNGContext, contextAlice->responderCachedSecretHash.pbxsecretID, 8); } /* Bob hashes*/ if (contextBob->cachedSecret.rs1!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.rs1, contextBob->cachedSecret.rs1Length, (uint8_t *)"Initiator", 9, 8, contextBob->initiatorCachedSecretHash.rs1ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->initiatorCachedSecretHash.rs1ID, 8); } if (contextBob->cachedSecret.rs2!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.rs2, contextBob->cachedSecret.rs2Length, (uint8_t *)"Initiator", 9, 8, contextBob->initiatorCachedSecretHash.rs2ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->initiatorCachedSecretHash.rs2ID, 8); } if (contextBob->cachedSecret.auxsecret!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.auxsecret, contextBob->cachedSecret.auxsecretLength, contextBob->channelContext[0]->selfH[3], 32, 8, contextBob->channelContext[0]->initiatorAuxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->channelContext[0]->initiatorAuxsecretID, 8); } if (contextBob->cachedSecret.pbxsecret!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.pbxsecret, contextBob->cachedSecret.pbxsecretLength, (uint8_t *)"Initiator", 9, 8, contextBob->initiatorCachedSecretHash.pbxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->initiatorCachedSecretHash.pbxsecretID, 8); } if (contextBob->cachedSecret.rs1!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.rs1, contextBob->cachedSecret.rs1Length, (uint8_t *)"Responder", 9, 8, contextBob->responderCachedSecretHash.rs1ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->responderCachedSecretHash.rs1ID, 8); } if (contextBob->cachedSecret.rs2!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.rs2, contextBob->cachedSecret.rs2Length, (uint8_t *)"Responder", 9, 8, contextBob->responderCachedSecretHash.rs2ID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->responderCachedSecretHash.rs2ID, 8); } if (contextBob->cachedSecret.auxsecret!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.auxsecret, contextBob->cachedSecret.auxsecretLength, contextBob->channelContext[0]->peerH[3], 32, 8, contextBob->channelContext[0]->responderAuxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->channelContext[0]->responderAuxsecretID, 8); } if (contextBob->cachedSecret.pbxsecret!=NULL) { contextBob->channelContext[0]->hmacFunction(contextBob->cachedSecret.pbxsecret, contextBob->cachedSecret.pbxsecretLength, (uint8_t *)"Responder", 9, 8, contextBob->responderCachedSecretHash.pbxsecretID); } else { /* we have no secret, generate a random */ bctoolbox_rng_get(contextBob->RNGContext, contextBob->responderCachedSecretHash.pbxsecretID, 8); } /* dump alice's packet on both sides */ bzrtp_message ("\nAlice original Packet is \n"); packetDump(alice_Hello, 1); bzrtp_message ("\nBob's parsed Alice Packet is \n"); packetDump(bob_HelloFromAlice, 0); /* Create the DHPart2 packet (that we then may change to DHPart1 if we ended to be the responder) */ alice_selfDHPart = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[0], MSGTYPE_DHPART2, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[0], alice_selfDHPart, 0); /* we don't care now about sequence number as we just need to build the message to be able to insert a hash of it into the commit packet */ if (retval == 0) { /* ok, insert it in context as we need it to build the commit packet */ contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID] = alice_selfDHPart; } else { bzrtp_message ("Alice building DHPart packet returns %x\n", retval); } bob_selfDHPart = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_DHPART2, &retval); retval +=bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_selfDHPart, 0); /* we don't care now about sequence number as we just need to build the message to be able to insert a hash of it into the commit packet */ if (retval == 0) { /* ok, insert it in context as we need it to build the commit packet */ contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID] = bob_selfDHPart; } else { bzrtp_message ("Bob building DHPart packet returns %x\n", retval); } bzrtp_message("Alice DHPart packet:\n"); packetDump(alice_selfDHPart,0); bzrtp_message("Bob DHPart packet:\n"); packetDump(bob_selfDHPart,0); /* respond to HELLO packet with an HelloACK - 1 create packets */ alice_HelloACK = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[0], MSGTYPE_HELLOACK, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[0], alice_HelloACK, contextAlice->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextAlice->channelContext[0]->selfSequenceNumber++; } else { bzrtp_message("Alice building HelloACK return %x\n", retval); } bob_HelloACK = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_HELLOACK, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_HelloACK, contextBob->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[0]->selfSequenceNumber++; } else { bzrtp_message("Bob building HelloACK return %x\n", retval); } /* exchange the HelloACK */ alice_HelloACKFromBob = bzrtp_packetCheck(bob_HelloACK->packetString, bob_HelloACK->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_HelloACK->packetString, bob_HelloACK->messageLength+16, alice_HelloACKFromBob); bzrtp_message ("Alice parsing Hello ACK returns %x\n", retval); if (retval==0) { contextAlice->channelContext[0]->peerSequenceNumber = alice_HelloACKFromBob->sequenceNumber; } bob_HelloACKFromAlice = bzrtp_packetCheck(alice_HelloACK->packetString, alice_HelloACK->messageLength+16, contextBob->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[0], alice_HelloACK->packetString, alice_HelloACK->messageLength+16, bob_HelloACKFromAlice); bzrtp_message ("Bob parsing Hello ACK returns %x\n", retval); if (retval==0) { contextBob->channelContext[0]->peerSequenceNumber = bob_HelloACKFromAlice->sequenceNumber; } bzrtp_freeZrtpPacket(alice_HelloACK); bzrtp_freeZrtpPacket(bob_HelloACK); bzrtp_freeZrtpPacket(alice_HelloACKFromBob); bzrtp_freeZrtpPacket(bob_HelloACKFromAlice); /* now build the commit message (both Alice and Bob will send it, then use the mechanism of rfc section 4.2 to determine who will be the initiator)*/ alice_Commit = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[0], MSGTYPE_COMMIT, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[0], alice_Commit, contextAlice->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextAlice->channelContext[0]->selfSequenceNumber++; contextAlice->channelContext[0]->selfPackets[COMMIT_MESSAGE_STORE_ID] = alice_Commit; } bzrtp_message("Alice building Commit return %x\n", retval); bob_Commit = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_COMMIT, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_Commit, contextBob->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[0]->selfSequenceNumber++; contextBob->channelContext[0]->selfPackets[COMMIT_MESSAGE_STORE_ID] = bob_Commit; } bzrtp_message("Bob building Commit return %x\n", retval); /* and exchange the commits */ bob_CommitFromAlice = bzrtp_packetCheck(alice_Commit->packetString, alice_Commit->messageLength+16, contextBob->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[0], alice_Commit->packetString, alice_Commit->messageLength+16, bob_CommitFromAlice); bzrtp_message ("Bob parsing Commit returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ bzrtpCommitMessage_t *bob_CommitFromAlice_message = (bzrtpCommitMessage_t *)bob_CommitFromAlice->messageData; contextBob->channelContext[0]->peerSequenceNumber = bob_CommitFromAlice->sequenceNumber; memcpy(contextBob->channelContext[0]->peerH[2], bob_CommitFromAlice_message->H2, 32); contextBob->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = bob_CommitFromAlice; } packetDump(bob_CommitFromAlice, 0); alice_CommitFromBob = bzrtp_packetCheck(bob_Commit->packetString, bob_Commit->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_Commit->packetString, bob_Commit->messageLength+16, alice_CommitFromBob); bzrtp_message ("Alice parsing Commit returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextAlice->channelContext[0]->peerSequenceNumber = alice_CommitFromBob->sequenceNumber; /* Alice will be the initiator (commit contention not implemented in this test) so just discard bob's commit */ /*bzrtpCommirMessage_t *alice_CommitFromBob_message = (bzrtpCommitMessage_t *)alice_CommitFromBob->messageData; memcpy(contextAlice->channelContext[0]->peerH[2], alice_CommitFromBob_message->H2, 32); contextAlice->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = alice_CommitFromBob;*/ } packetDump(alice_CommitFromBob, 0); bzrtp_freeZrtpPacket(alice_CommitFromBob); /* Now determine who shall be the initiator : rfc section 4.2 */ /* select the one with the lowest value of hvi */ /* for test purpose, we will set Alice as the initiator */ contextBob->channelContext[0]->role = RESPONDER; /* Bob (responder) shall update his selected algo list to match Alice selection */ /* no need to do this here as we have the same selection */ /* Bob is the responder, rebuild his DHPart packet to be responder and not initiator : */ /* as responder, bob must also swap his aux shared secret between responder and initiator as they are computed using the H3 and not a constant string */ memcpy(tmpBuffer, contextBob->channelContext[0]->initiatorAuxsecretID, 8); memcpy(contextBob->channelContext[0]->initiatorAuxsecretID, contextBob->channelContext[0]->responderAuxsecretID, 8); memcpy(contextBob->channelContext[0]->responderAuxsecretID, tmpBuffer, 8); contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageType = MSGTYPE_DHPART1; /* we are now part 1*/ bob_DHPart1 = (bzrtpDHPartMessage_t *)contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageData; /* change the shared secret ID to the responder one (we set them by default to the initiator's one) */ memcpy(bob_DHPart1->rs1ID, contextBob->responderCachedSecretHash.rs1ID, 8); memcpy(bob_DHPart1->rs2ID, contextBob->responderCachedSecretHash.rs2ID, 8); memcpy(bob_DHPart1->auxsecretID, contextBob->channelContext[0]->responderAuxsecretID, 8); memcpy(bob_DHPart1->pbxsecretID, contextBob->responderCachedSecretHash.pbxsecretID, 8); retval +=bzrtp_packetBuild(contextBob, contextBob->channelContext[0], contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID],contextBob->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[0]->selfSequenceNumber++; } bzrtp_message("Bob building DHPart1 return %x\n", retval); /* Alice parse bob's DHPart1 message */ alice_DHPart1FromBob = bzrtp_packetCheck(contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+16, alice_DHPart1FromBob); bzrtp_message ("Alice parsing DHPart1 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextAlice->channelContext[0]->peerSequenceNumber = alice_DHPart1FromBob->sequenceNumber; alice_DHPart1FromBob_message = (bzrtpDHPartMessage_t *)alice_DHPart1FromBob->messageData; memcpy(contextAlice->channelContext[0]->peerH[1], alice_DHPart1FromBob_message->H1, 32); contextAlice->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = alice_DHPart1FromBob; } packetDump(alice_DHPart1FromBob, 1); /* Now Alice may check which shared secret she expected and if they are valid in bob's DHPart1 */ if (contextAlice->cachedSecret.rs1!=NULL) { if (memcmp(contextAlice->responderCachedSecretHash.rs1ID, alice_DHPart1FromBob_message->rs1ID,8) != 0) { bzrtp_message ("Alice found that requested shared secret rs1 ID differs!\n"); } else { bzrtp_message("Alice validate rs1ID from bob DHPart1\n"); } } if (contextAlice->cachedSecret.rs2!=NULL) { if (memcmp(contextAlice->responderCachedSecretHash.rs2ID, alice_DHPart1FromBob_message->rs2ID,8) != 0) { bzrtp_message ("Alice found that requested shared secret rs2 ID differs!\n"); } else { bzrtp_message("Alice validate rs2ID from bob DHPart1\n"); } } if (contextAlice->cachedSecret.auxsecret!=NULL) { if (memcmp(contextAlice->channelContext[0]->responderAuxsecretID, alice_DHPart1FromBob_message->auxsecretID,8) != 0) { bzrtp_message ("Alice found that requested shared secret aux secret ID differs!\n"); } else { bzrtp_message("Alice validate aux secret ID from bob DHPart1\n"); } } if (contextAlice->cachedSecret.pbxsecret!=NULL) { if (memcmp(contextAlice->responderCachedSecretHash.pbxsecretID, alice_DHPart1FromBob_message->pbxsecretID,8) != 0) { bzrtp_message ("Alice found that requested shared secret pbx secret ID differs!\n"); } else { bzrtp_message("Alice validate pbxsecretID from bob DHPart1\n"); } } /* Now Alice shall check that the PV from bob is not 1 or Prime-1 TODO*/ /* Compute the shared DH secret */ contextAlice->DHMContext->peer = (uint8_t *)malloc(contextAlice->channelContext[0]->keyAgreementLength*sizeof(uint8_t)); memcpy (contextAlice->DHMContext->peer, alice_DHPart1FromBob_message->pv, contextAlice->channelContext[0]->keyAgreementLength); bctoolbox_DHMComputeSecret(contextAlice->DHMContext, (int (*)(void *, uint8_t *, size_t))bctoolbox_rng_get, (void *)contextAlice->RNGContext); /* So Alice send bob her DHPart2 message which is already prepared and stored (we just need to update the sequence number) */ bzrtp_packetUpdateSequenceNumber(contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID], contextAlice->channelContext[0]->selfSequenceNumber); contextAlice->channelContext[0]->selfSequenceNumber++; /* Bob parse Alice's DHPart2 message */ bob_DHPart2FromAlice = bzrtp_packetCheck(contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+16, contextBob->channelContext[0]->peerSequenceNumber, &retval); bzrtp_message ("Bob checking DHPart2 returns %x\n", retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[0], contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString, contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength+16, bob_DHPart2FromAlice); bzrtp_message ("Bob parsing DHPart2 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextBob->channelContext[0]->peerSequenceNumber = bob_DHPart2FromAlice->sequenceNumber; bob_DHPart2FromAlice_message = (bzrtpDHPartMessage_t *)bob_DHPart2FromAlice->messageData; memcpy(contextBob->channelContext[0]->peerH[1], bob_DHPart2FromAlice_message->H1, 32); contextBob->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = bob_DHPart2FromAlice; } packetDump(bob_DHPart2FromAlice, 0); /* Now Bob may check which shared secret she expected and if they are valid in bob's DHPart1 */ if (contextBob->cachedSecret.rs1!=NULL) { if (memcmp(contextBob->initiatorCachedSecretHash.rs1ID, bob_DHPart2FromAlice_message->rs1ID,8) != 0) { bzrtp_message ("Bob found that requested shared secret rs1 ID differs!\n"); } else { bzrtp_message("Bob validate rs1ID from Alice DHPart2\n"); } } if (contextBob->cachedSecret.rs2!=NULL) { if (memcmp(contextBob->initiatorCachedSecretHash.rs2ID, bob_DHPart2FromAlice_message->rs2ID,8) != 0) { bzrtp_message ("Bob found that requested shared secret rs2 ID differs!\n"); } else { bzrtp_message("Bob validate rs2ID from Alice DHPart2\n"); } } if (contextBob->cachedSecret.auxsecret!=NULL) { if (memcmp(contextBob->channelContext[0]->initiatorAuxsecretID, bob_DHPart2FromAlice_message->auxsecretID,8) != 0) { bzrtp_message ("Bob found that requested shared secret aux secret ID differs!\n"); } else { bzrtp_message("Bob validate aux secret ID from Alice DHPart2\n"); } } if (contextBob->cachedSecret.pbxsecret!=NULL) { if (memcmp(contextBob->initiatorCachedSecretHash.pbxsecretID, bob_DHPart2FromAlice_message->pbxsecretID,8) != 0) { bzrtp_message ("Bob found that requested shared secret pbx secret ID differs!\n"); } else { bzrtp_message("Bob validate pbxsecretID from Alice DHPart2\n"); } } /* Now Bob shall check that the PV from Alice is not 1 or Prime-1 TODO*/ /* Compute the shared DH secret */ contextBob->DHMContext->peer = (uint8_t *)malloc(contextBob->channelContext[0]->keyAgreementLength*sizeof(uint8_t)); memcpy (contextBob->DHMContext->peer, bob_DHPart2FromAlice_message->pv, contextBob->channelContext[0]->keyAgreementLength); bctoolbox_DHMComputeSecret(contextBob->DHMContext, (int (*)(void *, uint8_t *, size_t))bctoolbox_rng_get, (void *)contextAlice->RNGContext); /* JUST FOR TEST: check that the generated secrets are the same */ secretLength = bob_DHPart2FromAlice->messageLength-84; /* length of generated secret is the same than public value */ if (memcmp(contextBob->DHMContext->key, contextAlice->DHMContext->key, secretLength)==0) { bzrtp_message("Secret Key correctly exchanged \n"); CU_PASS("Secret Key exchange OK"); } else { CU_FAIL("Secret Key exchange failed"); bzrtp_message("ERROR : secretKey exchange failed!!\n"); } /* now compute the total_hash as in rfc section 4.4.1.4 * total_hash = hash(Hello of responder || Commit || DHPart1 || DHPart2) */ totalHashDataLength = bob_Hello->messageLength + alice_Commit->messageLength + contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength + alice_selfDHPart->messageLength; dataToHash = (uint8_t *)malloc(totalHashDataLength*sizeof(uint8_t)); /* get all data from Alice */ memcpy(dataToHash, contextAlice->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextAlice->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextAlice->channelContext[0]->selfPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[0]->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextAlice->channelContext[0]->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextAlice->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextAlice->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength); contextAlice->channelContext[0]->hashFunction(dataToHash, totalHashDataLength, 32, alice_totalHash); /* get all data from Bob */ hashDataIndex = 0; memcpy(dataToHash, contextBob->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextBob->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextBob->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextBob->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextBob->channelContext[0]->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextBob->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength); contextBob->channelContext[0]->hashFunction(dataToHash, totalHashDataLength, 32, bob_totalHash); if (memcmp(bob_totalHash, alice_totalHash, 32) == 0) { bzrtp_message("Got the same total hash\n"); CU_PASS("Total Hash match"); } else { bzrtp_message("AARGG!! total hash mismatch"); CU_FAIL("Total Hash mismatch"); } /* now compute s0 and KDF_context as in rfc section 4.4.1.4 s0 = hash(counter || DHResult || "ZRTP-HMAC-KDF" || ZIDi || ZIDr || total_hash || len(s1) || s1 || len(s2) || s2 || len(s3) || s3) counter is a fixed 32 bits integer in big endian set to 1 : 0x00000001 */ free(dataToHash); contextAlice->channelContext[0]->KDFContextLength = 24+32;/* actual depends on selected hash length*/ contextAlice->channelContext[0]->KDFContext = (uint8_t *)malloc(contextAlice->channelContext[0]->KDFContextLength*sizeof(uint8_t)); memcpy(contextAlice->channelContext[0]->KDFContext, contextAlice->selfZID, 12); /* ZIDi*/ memcpy(contextAlice->channelContext[0]->KDFContext+12, contextAlice->peerZID, 12); /* ZIDr */ memcpy(contextAlice->channelContext[0]->KDFContext+24, alice_totalHash, 32); /* total Hash*/ /* get s1 from rs1 or rs2 */ if (contextAlice->cachedSecret.rs1 != NULL) { /* if there is a s1 (already validated when received the DHpacket) */ s1 = contextAlice->cachedSecret.rs1; s1Length = contextAlice->cachedSecret.rs1Length; } else if (contextAlice->cachedSecret.rs2 != NULL) { /* otherwise if there is a s2 (already validated when received the DHpacket) */ s1 = contextAlice->cachedSecret.rs2; s1Length = contextAlice->cachedSecret.rs2Length; } /* s2 is the auxsecret */ s2 = contextAlice->cachedSecret.auxsecret; /* this may be null if no match or no aux secret where found */ s2Length = contextAlice->cachedSecret.auxsecretLength; /* this may be 0 if no match or no aux secret where found */ /* s3 is the pbxsecret */ s3 = contextAlice->cachedSecret.pbxsecret; /* this may be null if no match or no pbx secret where found */ s3Length = contextAlice->cachedSecret.pbxsecretLength; /* this may be 0 if no match or no pbx secret where found */ totalHashDataLength = 4+secretLength+13/*ZRTP-HMAC-KDF string*/ + 12 + 12 + 32 + 4 +s1Length + 4 +s2Length + 4 + s3Length; /* secret length was computed before as the length of DH secret data */ dataToHash = (uint8_t *)malloc(totalHashDataLength*sizeof(uint8_t)); dataToHash[0] = 0x00; dataToHash[1] = 0x00; dataToHash[2] = 0x00; dataToHash[3] = 0x01; hashDataIndex = 4; memcpy(dataToHash+hashDataIndex, contextAlice->DHMContext->key, secretLength); hashDataIndex += secretLength; memcpy(dataToHash+hashDataIndex, "ZRTP-HMAC-KDF", 13); hashDataIndex += 13; memcpy(dataToHash+hashDataIndex, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength); hashDataIndex += 56; dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s1Length&0xFF); if (s1!=NULL) { memcpy(dataToHash+hashDataIndex, s1, s1Length); hashDataIndex += s1Length; } dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s2Length&0xFF); if (s2!=NULL) { memcpy(dataToHash+hashDataIndex, s2, s2Length); hashDataIndex += s2Length; } dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s3Length&0xFF); if (s3!=NULL) { memcpy(dataToHash+hashDataIndex, s3, s3Length); hashDataIndex += s3Length; } contextAlice->channelContext[0]->s0 = (uint8_t *)malloc(32*sizeof(uint8_t)); contextAlice->channelContext[0]->hashFunction(dataToHash, totalHashDataLength, 32, contextAlice->channelContext[0]->s0); /* destroy all cached keys in context */ if (contextAlice->cachedSecret.rs1!=NULL) { bzrtp_DestroyKey(contextAlice->cachedSecret.rs1, contextAlice->cachedSecret.rs1Length, contextAlice->RNGContext); free(contextAlice->cachedSecret.rs1); contextAlice->cachedSecret.rs1 = NULL; } if (contextAlice->cachedSecret.rs2!=NULL) { bzrtp_DestroyKey(contextAlice->cachedSecret.rs2, contextAlice->cachedSecret.rs2Length, contextAlice->RNGContext); free(contextAlice->cachedSecret.rs2); contextAlice->cachedSecret.rs2 = NULL; } if (contextAlice->cachedSecret.auxsecret!=NULL) { bzrtp_DestroyKey(contextAlice->cachedSecret.auxsecret, contextAlice->cachedSecret.auxsecretLength, contextAlice->RNGContext); free(contextAlice->cachedSecret.auxsecret); contextAlice->cachedSecret.auxsecret = NULL; } if (contextAlice->cachedSecret.pbxsecret!=NULL) { bzrtp_DestroyKey(contextAlice->cachedSecret.pbxsecret, contextAlice->cachedSecret.pbxsecretLength, contextAlice->RNGContext); free(contextAlice->cachedSecret.pbxsecret); contextAlice->cachedSecret.pbxsecret = NULL; } /*** Do the same for bob ***/ /* get s1 from rs1 or rs2 */ s1=NULL; s2=NULL; s3=NULL; contextBob->channelContext[0]->KDFContextLength = 24+32;/* actual depends on selected hash length*/ contextBob->channelContext[0]->KDFContext = (uint8_t *)malloc(contextBob->channelContext[0]->KDFContextLength*sizeof(uint8_t)); memcpy(contextBob->channelContext[0]->KDFContext, contextBob->peerZID, 12); /* ZIDi*/ memcpy(contextBob->channelContext[0]->KDFContext+12, contextBob->selfZID, 12); /* ZIDr */ memcpy(contextBob->channelContext[0]->KDFContext+24, bob_totalHash, 32); /* total Hash*/ if (contextBob->cachedSecret.rs1 != NULL) { /* if there is a s1 (already validated when received the DHpacket) */ s1 = contextBob->cachedSecret.rs1; s1Length = contextBob->cachedSecret.rs1Length; } else if (contextBob->cachedSecret.rs2 != NULL) { /* otherwise if there is a s2 (already validated when received the DHpacket) */ s1 = contextBob->cachedSecret.rs2; s1Length = contextBob->cachedSecret.rs2Length; } /* s2 is the auxsecret */ s2 = contextBob->cachedSecret.auxsecret; /* this may be null if no match or no aux secret where found */ s2Length = contextBob->cachedSecret.auxsecretLength; /* this may be 0 if no match or no aux secret where found */ /* s3 is the pbxsecret */ s3 = contextBob->cachedSecret.pbxsecret; /* this may be null if no match or no pbx secret where found */ s3Length = contextBob->cachedSecret.pbxsecretLength; /* this may be 0 if no match or no pbx secret where found */ free(dataToHash); dataToHash = (uint8_t *)malloc(totalHashDataLength*sizeof(uint8_t)); dataToHash[0] = 0x00; dataToHash[1] = 0x00; dataToHash[2] = 0x00; dataToHash[3] = 0x01; hashDataIndex = 4; memcpy(dataToHash+hashDataIndex, contextBob->DHMContext->key, secretLength); hashDataIndex += secretLength; memcpy(dataToHash+hashDataIndex, "ZRTP-HMAC-KDF", 13); hashDataIndex += 13; memcpy(dataToHash+hashDataIndex, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength); hashDataIndex += 56; dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s1Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s1Length&0xFF); if (s1!=NULL) { memcpy(dataToHash+hashDataIndex, s1, s1Length); hashDataIndex += s1Length; } dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s2Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s2Length&0xFF); if (s2!=NULL) { memcpy(dataToHash+hashDataIndex, s2, s2Length); hashDataIndex += s2Length; } dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>24)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>16)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)((s3Length>>8)&0xFF); dataToHash[hashDataIndex++] = (uint8_t)(s3Length&0xFF); if (s3!=NULL) { memcpy(dataToHash+hashDataIndex, s3, s3Length); hashDataIndex += s3Length; } contextBob->channelContext[0]->s0 = (uint8_t *)malloc(32*sizeof(uint8_t)); contextBob->channelContext[0]->hashFunction(dataToHash, totalHashDataLength, 32, contextBob->channelContext[0]->s0); free(dataToHash); /* destroy all cached keys in context */ if (contextBob->cachedSecret.rs1!=NULL) { bzrtp_DestroyKey(contextBob->cachedSecret.rs1, contextBob->cachedSecret.rs1Length, contextBob->RNGContext); free(contextBob->cachedSecret.rs1); contextBob->cachedSecret.rs1 = NULL; } if (contextBob->cachedSecret.rs2!=NULL) { bzrtp_DestroyKey(contextBob->cachedSecret.rs2, contextBob->cachedSecret.rs2Length, contextBob->RNGContext); free(contextBob->cachedSecret.rs2); contextBob->cachedSecret.rs2 = NULL; } if (contextBob->cachedSecret.auxsecret!=NULL) { bzrtp_DestroyKey(contextBob->cachedSecret.auxsecret, contextBob->cachedSecret.auxsecretLength, contextBob->RNGContext); free(contextBob->cachedSecret.auxsecret); contextBob->cachedSecret.auxsecret = NULL; } if (contextBob->cachedSecret.pbxsecret!=NULL) { bzrtp_DestroyKey(contextBob->cachedSecret.pbxsecret, contextBob->cachedSecret.pbxsecretLength, contextBob->RNGContext); free(contextBob->cachedSecret.pbxsecret); contextBob->cachedSecret.pbxsecret = NULL; } /* DEBUG compare s0 */ if (memcmp(contextBob->channelContext[0]->s0, contextAlice->channelContext[0]->s0, 32)==0) { bzrtp_message("Got the same s0\n"); CU_PASS("s0 match"); } else { bzrtp_message("ERROR s0 differs\n"); CU_PASS("s0 mismatch"); } /* now compute the ZRTPSession key : section 4.5.2 * ZRTPSess = KDF(s0, "ZRTP Session Key", KDF_Context, negotiated hash length)*/ contextAlice->ZRTPSessLength=32; /* must be set to the length of negotiated hash */ contextAlice->ZRTPSess = (uint8_t *)malloc(contextAlice->ZRTPSessLength*sizeof(uint8_t)); retval = bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"ZRTP Session Key", 16, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, /* this one too depends on selected hash */ contextAlice->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, contextAlice->ZRTPSess); contextBob->ZRTPSessLength=32; /* must be set to the length of negotiated hash */ contextBob->ZRTPSess = (uint8_t *)malloc(contextBob->ZRTPSessLength*sizeof(uint8_t)); retval = bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"ZRTP Session Key", 16, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, /* this one too depends on selected hash */ contextBob->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, contextBob->ZRTPSess); /* DEBUG compare ZRTPSess Key */ if (memcmp(contextBob->ZRTPSess, contextAlice->ZRTPSess, 32)==0) { bzrtp_message("Got the same ZRTPSess\n"); CU_PASS("ZRTPSess match"); } else { bzrtp_message("ERROR ZRTPSess differs\n"); CU_PASS("ZRTPSess mismatch"); } /* compute the sas according to rfc section 4.5.2 sashash = KDF(s0, "SAS", KDF_Context, 256) */ retval = bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"SAS", 3, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, /* this one too depends on selected hash */ 256/8, /* function gets L in bytes */ (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, alice_sasHash); retval = bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"SAS", 3, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, /* this one too depends on selected hash */ 256/8, /* function gets L in bytes */ (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, bob_sasHash); /* DEBUG compare sasHash */ if (memcmp(alice_sasHash, bob_sasHash, 32)==0) { bzrtp_message("Got the same SAS Hash\n"); CU_PASS("SAS Hash match"); } else { bzrtp_message("ERROR SAS Hash differs\n"); CU_PASS("SAS Hash mismatch"); } /* display SAS (we shall not do this now but after the confirm message exchanges) */ sasValue = ((uint32_t)alice_sasHash[0]<<24) | ((uint32_t)alice_sasHash[1]<<16) | ((uint32_t)alice_sasHash[2]<<8) | ((uint32_t)(alice_sasHash[3])); contextAlice->channelContext[0]->sasFunction(sasValue, sas, 5); bzrtp_message("Alice SAS is %.4s\n", sas); sasValue = ((uint32_t)bob_sasHash[0]<<24) | ((uint32_t)bob_sasHash[1]<<16) | ((uint32_t)bob_sasHash[2]<<8) | ((uint32_t)(bob_sasHash[3])); contextBob->channelContext[0]->sasFunction(sasValue, sas, 5); bzrtp_message("Bob SAS is %.4s\n", sas); /* now derive the other keys (mackeyi, mackeyr, zrtpkeyi and zrtpkeyr, srtpkeys and salt) */ contextAlice->channelContext[0]->mackeyi = (uint8_t *)malloc(contextAlice->channelContext[0]->hashLength*(sizeof(uint8_t))); contextAlice->channelContext[0]->mackeyr = (uint8_t *)malloc(contextAlice->channelContext[0]->hashLength*(sizeof(uint8_t))); contextAlice->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(contextAlice->channelContext[0]->cipherKeyLength*(sizeof(uint8_t))); contextAlice->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(contextAlice->channelContext[0]->cipherKeyLength*(sizeof(uint8_t))); contextBob->channelContext[0]->mackeyi = (uint8_t *)malloc(contextBob->channelContext[0]->hashLength*(sizeof(uint8_t))); contextBob->channelContext[0]->mackeyr = (uint8_t *)malloc(contextBob->channelContext[0]->hashLength*(sizeof(uint8_t))); contextBob->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(contextBob->channelContext[0]->cipherKeyLength*(sizeof(uint8_t))); contextBob->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(contextBob->channelContext[0]->cipherKeyLength*(sizeof(uint8_t))); /* Alice */ retval = bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"Initiator HMAC key", 18, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, contextAlice->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, contextAlice->channelContext[0]->mackeyi); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"Responder HMAC key", 18, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, contextAlice->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, contextAlice->channelContext[0]->mackeyr); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"Initiator ZRTP key", 18, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, contextAlice->channelContext[0]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, contextAlice->channelContext[0]->zrtpkeyi); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[0]->s0, contextAlice->channelContext[0]->hashLength, (uint8_t *)"Responder ZRTP key", 18, contextAlice->channelContext[0]->KDFContext, contextAlice->channelContext[0]->KDFContextLength, contextAlice->channelContext[0]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[0]->hmacFunction, contextAlice->channelContext[0]->zrtpkeyr); /* Bob */ retval = bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"Initiator HMAC key", 18, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, contextBob->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, contextBob->channelContext[0]->mackeyi); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"Responder HMAC key", 18, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, contextBob->channelContext[0]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, contextBob->channelContext[0]->mackeyr); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"Initiator ZRTP key", 18, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, contextBob->channelContext[0]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, contextBob->channelContext[0]->zrtpkeyi); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[0]->s0, contextBob->channelContext[0]->hashLength, (uint8_t *)"Responder ZRTP key", 18, contextBob->channelContext[0]->KDFContext, contextBob->channelContext[0]->KDFContextLength, contextBob->channelContext[0]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[0]->hmacFunction, contextBob->channelContext[0]->zrtpkeyr); /* DEBUG compare keys */ if ((memcmp(contextAlice->channelContext[0]->mackeyi, contextBob->channelContext[0]->mackeyi, contextAlice->channelContext[0]->hashLength)==0) && (memcmp(contextAlice->channelContext[0]->mackeyr, contextBob->channelContext[0]->mackeyr, contextAlice->channelContext[0]->hashLength)==0) && (memcmp(contextAlice->channelContext[0]->zrtpkeyi, contextBob->channelContext[0]->zrtpkeyi, contextAlice->channelContext[0]->cipherKeyLength)==0) && (memcmp(contextAlice->channelContext[0]->zrtpkeyr, contextBob->channelContext[0]->zrtpkeyr, contextAlice->channelContext[0]->cipherKeyLength)==0)) { bzrtp_message("Got the same keys\n"); CU_PASS("keys match"); } else { bzrtp_message("ERROR keys differ\n"); CU_PASS("Keys mismatch"); } /* now Bob build the CONFIRM1 packet and send it to Alice */ bob_Confirm1 = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_CONFIRM1, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_Confirm1, contextBob->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[0]->selfSequenceNumber++; } bzrtp_message("Bob building Confirm1 return %x\n", retval); alice_Confirm1FromBob = bzrtp_packetCheck(bob_Confirm1->packetString, bob_Confirm1->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_Confirm1->packetString, bob_Confirm1->messageLength+16, alice_Confirm1FromBob); bzrtp_message ("Alice parsing confirm1 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextAlice->channelContext[0]->peerSequenceNumber = alice_Confirm1FromBob->sequenceNumber; alice_Confirm1FromBob_message = (bzrtpConfirmMessage_t *)alice_Confirm1FromBob->messageData; memcpy(contextAlice->channelContext[0]->peerH[0], alice_Confirm1FromBob_message->H0, 32); } packetDump(bob_Confirm1,1); packetDump(alice_Confirm1FromBob,0); bzrtp_freeZrtpPacket(alice_Confirm1FromBob); bzrtp_freeZrtpPacket(bob_Confirm1); /* now Alice build the CONFIRM2 packet and send it to Bob */ alice_Confirm2 = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[0], MSGTYPE_CONFIRM2, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[0], alice_Confirm2, contextAlice->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextAlice->channelContext[0]->selfSequenceNumber++; } bzrtp_message("Alice building Confirm2 return %x\n", retval); bob_Confirm2FromAlice = bzrtp_packetCheck(alice_Confirm2->packetString, alice_Confirm2->messageLength+16, contextBob->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[0], alice_Confirm2->packetString, alice_Confirm2->messageLength+16, bob_Confirm2FromAlice); bzrtp_message ("Bob parsing confirm2 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextBob->channelContext[0]->peerSequenceNumber = bob_Confirm2FromAlice->sequenceNumber; bob_Confirm2FromAlice_message = (bzrtpConfirmMessage_t *)bob_Confirm2FromAlice->messageData; memcpy(contextBob->channelContext[0]->peerH[0], bob_Confirm2FromAlice_message->H0, 32); /* set bob's status to secure */ contextBob->isSecure = 1; } packetDump(alice_Confirm2,1); packetDump(bob_Confirm2FromAlice,0); bzrtp_freeZrtpPacket(bob_Confirm2FromAlice); bzrtp_freeZrtpPacket(alice_Confirm2); /* Bob build the conf2Ack and send it to Alice */ bob_Conf2ACK = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[0], MSGTYPE_CONF2ACK, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[0], bob_Conf2ACK, contextBob->channelContext[0]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[0]->selfSequenceNumber++; } bzrtp_message("Bob building Conf2ACK return %x\n", retval); alice_Conf2ACKFromBob = bzrtp_packetCheck(bob_Conf2ACK->packetString, bob_Conf2ACK->messageLength+16, contextAlice->channelContext[0]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_Conf2ACK->packetString, bob_Conf2ACK->messageLength+16, alice_Conf2ACKFromBob); bzrtp_message ("Alice parsing conf2ACK returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextAlice->channelContext[0]->peerSequenceNumber = alice_Conf2ACKFromBob->sequenceNumber; /* set Alice's status to secure */ contextAlice->isSecure = 1; } bzrtp_freeZrtpPacket(bob_Conf2ACK); bzrtp_freeZrtpPacket(alice_Conf2ACKFromBob); dumpContext("Alice", contextAlice); dumpContext("Bob", contextBob); bzrtp_message("\n\n\n\n\n*************************************************************\n SECOND CHANNEL\n**********************************************\n\n"); /* Now create a second channel for Bob and Alice */ retval = bzrtp_addChannel(contextAlice, 0x45678901); bzrtp_message("Add channel to Alice's context returns %d\n", retval); retval = bzrtp_addChannel(contextBob, 0x54321098); bzrtp_message("Add channel to Bob's context returns %d\n", retval); /* create hello packets for this channel */ alice_Hello = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[1], MSGTYPE_HELLO, &retval); if (bzrtp_packetBuild(contextAlice, contextAlice->channelContext[1], alice_Hello, contextAlice->channelContext[1]->selfSequenceNumber) ==0) { contextAlice->channelContext[1]->selfSequenceNumber++; contextAlice->channelContext[1]->selfPackets[HELLO_MESSAGE_STORE_ID] = alice_Hello; } bob_Hello = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[1], MSGTYPE_HELLO, &retval); if (bzrtp_packetBuild(contextBob, contextBob->channelContext[1], bob_Hello, contextBob->channelContext[1]->selfSequenceNumber) ==0) { contextBob->channelContext[1]->selfSequenceNumber++; contextBob->channelContext[1]->selfPackets[HELLO_MESSAGE_STORE_ID] = bob_Hello; } /* now send Alice Hello's to Bob and vice-versa, so they parse them */ alice_HelloFromBob = bzrtp_packetCheck(bob_Hello->packetString, bob_Hello->messageLength+16, contextAlice->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[0], bob_Hello->packetString, bob_Hello->messageLength+16, alice_HelloFromBob); bzrtp_message ("Alice parsing returns %x\n", retval); if (retval==0) { bzrtpHelloMessage_t *alice_HelloFromBob_message; int i; uint8_t checkPeerSupportMultiChannel = 0; contextAlice->channelContext[1]->peerSequenceNumber = alice_HelloFromBob->sequenceNumber; /* save bob's Hello packet in Alice's context */ contextAlice->channelContext[1]->peerPackets[HELLO_MESSAGE_STORE_ID] = alice_HelloFromBob; /* we are already secured (shall check isSecure==1), so we just need to check that peer Hello have the Mult in his key agreement list of supported algo */ alice_HelloFromBob_message = (bzrtpHelloMessage_t *)alice_HelloFromBob->messageData; for (i=0; i<alice_HelloFromBob_message->kc; i++) { if (alice_HelloFromBob_message->supportedKeyAgreement[i] == ZRTP_KEYAGREEMENT_Mult) { checkPeerSupportMultiChannel = 1; } } /* ok multi channel is supported*/ if (checkPeerSupportMultiChannel == 1) { bzrtp_message("Alice found that Bob supports multi channel\n"); /* now set the choosen algos, they MUST be the same than main channel (channel 0) except for keyAgreement which is set to mult */ contextAlice->channelContext[1]->hashAlgo = contextAlice->channelContext[0]->hashAlgo; contextAlice->channelContext[1]->hashLength = contextAlice->channelContext[0]->hashLength; contextAlice->channelContext[1]->cipherAlgo = contextAlice->channelContext[0]->cipherAlgo; contextAlice->channelContext[1]->cipherKeyLength = contextAlice->channelContext[0]->cipherKeyLength; contextAlice->channelContext[1]->authTagAlgo = contextAlice->channelContext[0]->authTagAlgo; contextAlice->channelContext[1]->sasAlgo = contextAlice->channelContext[0]->sasAlgo; contextAlice->channelContext[1]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_Mult; contextAlice->channelContext[1]->keyAgreementLength = 0; /* no public values exchanged in Multi channel mode */ updateCryptoFunctionPointers(contextAlice->channelContext[1]); } else { bzrtp_message("ERROR : Alice found that Bob doesn't support multi channel\n"); } } bob_HelloFromAlice = bzrtp_packetCheck(alice_Hello->packetString, alice_Hello->messageLength+16, contextBob->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[1], alice_Hello->packetString, alice_Hello->messageLength+16, bob_HelloFromAlice); bzrtp_message ("Bob parsing returns %x\n", retval); if (retval==0) { bzrtpHelloMessage_t *bob_HelloFromAlice_message; int i; uint8_t checkPeerSupportMultiChannel = 0; contextBob->channelContext[1]->peerSequenceNumber = bob_HelloFromAlice->sequenceNumber; /* save alice's Hello packet in bob's context */ contextBob->channelContext[1]->peerPackets[HELLO_MESSAGE_STORE_ID] = bob_HelloFromAlice; /* we are already secured (shall check isSecure==1), so we just need to check that peer Hello have the Mult in his key agreement list of supported algo */ bob_HelloFromAlice_message = (bzrtpHelloMessage_t *)bob_HelloFromAlice->messageData; for (i=0; i<bob_HelloFromAlice_message->kc; i++) { if (bob_HelloFromAlice_message->supportedKeyAgreement[i] == ZRTP_KEYAGREEMENT_Mult) { checkPeerSupportMultiChannel = 1; } } /* ok multi channel is supported*/ if (checkPeerSupportMultiChannel == 1) { bzrtp_message("Bob found that Alice supports multi channel\n"); /* now set the choosen algos, they MUST be the same than main channel (channel 0) except for keyAgreement which is set to mult */ contextBob->channelContext[1]->hashAlgo = contextBob->channelContext[0]->hashAlgo; contextBob->channelContext[1]->hashLength = contextBob->channelContext[0]->hashLength; contextBob->channelContext[1]->cipherAlgo = contextBob->channelContext[0]->cipherAlgo; contextBob->channelContext[1]->cipherKeyLength = contextBob->channelContext[0]->cipherKeyLength; contextBob->channelContext[1]->authTagAlgo = contextBob->channelContext[0]->authTagAlgo; contextBob->channelContext[1]->sasAlgo = contextBob->channelContext[0]->sasAlgo; contextBob->channelContext[1]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_Mult; contextBob->channelContext[1]->keyAgreementLength = 0; /* no public values exchanged in Multi channel mode */ updateCryptoFunctionPointers(contextBob->channelContext[1]); } else { bzrtp_message("ERROR : Bob found that Alice doesn't support multi channel\n"); } } /* update context with hello message information : H3 and compute initiator and responder's shared secret Hashs */ alice_HelloFromBob_message = (bzrtpHelloMessage_t *)alice_HelloFromBob->messageData; memcpy(contextAlice->channelContext[1]->peerH[3], alice_HelloFromBob_message->H3, 32); bob_HelloFromAlice_message = (bzrtpHelloMessage_t *)bob_HelloFromAlice->messageData; memcpy(contextBob->channelContext[1]->peerH[3], bob_HelloFromAlice_message->H3, 32); /* here we shall exchange Hello ACK but it is just a test and was done already for channel 0, skip it as it is useless for the test */ /* Bob will be the initiator, so compute a commit for him */ bob_Commit = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[1], MSGTYPE_COMMIT, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[1], bob_Commit, contextBob->channelContext[1]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[1]->selfSequenceNumber++; contextBob->channelContext[1]->selfPackets[COMMIT_MESSAGE_STORE_ID] = bob_Commit; } bzrtp_message("Bob building Commit return %x\n", retval); /* and send it to Alice */ alice_CommitFromBob = bzrtp_packetCheck(bob_Commit->packetString, bob_Commit->messageLength+16, contextAlice->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[1], bob_Commit->packetString, bob_Commit->messageLength+16, alice_CommitFromBob); bzrtp_message ("Alice parsing Commit returns %x\n", retval); if (retval==0) { bzrtpCommitMessage_t *alice_CommitFromBob_message; /* update context with the information found in the packet */ contextAlice->channelContext[1]->peerSequenceNumber = alice_CommitFromBob->sequenceNumber; /* Alice will be the initiator (commit contention not implemented in this test) so just discard bob's commit */ alice_CommitFromBob_message = (bzrtpCommitMessage_t *)alice_CommitFromBob->messageData; memcpy(contextAlice->channelContext[1]->peerH[2], alice_CommitFromBob_message->H2, 32); contextAlice->channelContext[1]->peerPackets[COMMIT_MESSAGE_STORE_ID] = alice_CommitFromBob; } packetDump(alice_CommitFromBob, 0); /* for test purpose define Alice as the responder */ contextAlice->channelContext[1]->role = RESPONDER; /* compute the total hash as in rfc section 4.4.3.2 total_hash = hash(Hello of responder || Commit) */ totalHashDataLength = alice_Hello->messageLength + bob_Commit->messageLength; dataToHash = (uint8_t *)malloc(totalHashDataLength*sizeof(uint8_t)); hashDataIndex = 0; /* get all data from Alice */ memcpy(dataToHash, contextAlice->channelContext[1]->selfPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[1]->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextAlice->channelContext[1]->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextAlice->channelContext[1]->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextAlice->channelContext[1]->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength); contextAlice->channelContext[1]->hashFunction(dataToHash, totalHashDataLength, 32, alice_totalHash); /* get all data from Bob */ hashDataIndex = 0; memcpy(dataToHash, contextBob->channelContext[1]->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[1]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength); hashDataIndex += contextBob->channelContext[1]->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength; memcpy(dataToHash+hashDataIndex, contextBob->channelContext[1]->selfPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, contextBob->channelContext[1]->selfPackets[COMMIT_MESSAGE_STORE_ID]->messageLength); contextBob->channelContext[1]->hashFunction(dataToHash, totalHashDataLength, 32, bob_totalHash); if (memcmp(bob_totalHash, alice_totalHash, 32) == 0) { bzrtp_message("Got the same total hash\n"); CU_PASS("Total Hash match"); } else { bzrtp_message("AARGG!! total hash mismatch"); CU_FAIL("Total Hash mismatch"); } free(dataToHash); /* compute the KDF Context as in rfc section 4.4.3.2 KDF_Context = (ZIDi || ZIDr || total_hash) */ contextAlice->channelContext[1]->KDFContextLength = 24 + contextAlice->channelContext[1]->hashLength; contextAlice->channelContext[1]->KDFContext = (uint8_t *)malloc(contextAlice->channelContext[1]->KDFContextLength*sizeof(uint8_t)); memcpy(contextAlice->channelContext[1]->KDFContext, contextAlice->peerZID, 12); memcpy(contextAlice->channelContext[1]->KDFContext+12, contextAlice->selfZID, 12); memcpy(contextAlice->channelContext[1]->KDFContext+24, alice_totalHash, contextAlice->channelContext[1]->hashLength); contextBob->channelContext[1]->KDFContextLength = 24 + contextBob->channelContext[1]->hashLength; contextBob->channelContext[1]->KDFContext = (uint8_t *)malloc(contextBob->channelContext[1]->KDFContextLength*sizeof(uint8_t)); memcpy(contextBob->channelContext[1]->KDFContext, contextBob->selfZID, 12); memcpy(contextBob->channelContext[1]->KDFContext+12, contextBob->peerZID, 12); memcpy(contextBob->channelContext[1]->KDFContext+24, bob_totalHash, contextBob->channelContext[1]->hashLength); if (memcmp(contextBob->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContext, 56) == 0) { bzrtp_message("Got the same total KDF Context\n"); CU_PASS("KDFContext match"); } else { bzrtp_message("AARGG!! KDF Context mismatch"); CU_FAIL("KDF Context mismatch"); } /* compute s0 as in rfc section 4.4.3.2 s0 = KDF(ZRTPSess, "ZRTP MSK", KDF_Context, negotiated hash length) */ contextBob->channelContext[1]->s0 = (uint8_t *)malloc(contextBob->channelContext[1]->hashLength*sizeof(uint8_t)); contextAlice->channelContext[1]->s0 = (uint8_t *)malloc(contextAlice->channelContext[1]->hashLength*sizeof(uint8_t)); retval = bzrtp_keyDerivationFunction(contextBob->ZRTPSess, contextBob->ZRTPSessLength, (uint8_t *)"ZRTP MSK", 8, contextBob->channelContext[1]->KDFContext, contextBob->channelContext[1]->KDFContextLength, /* this one too depends on selected hash */ contextBob->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[1]->hmacFunction, contextBob->channelContext[1]->s0); retval = bzrtp_keyDerivationFunction(contextAlice->ZRTPSess, contextAlice->ZRTPSessLength, (uint8_t *)"ZRTP MSK", 8, contextAlice->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContextLength, /* this one too depends on selected hash */ contextAlice->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[1]->hmacFunction, contextAlice->channelContext[1]->s0); if (memcmp(contextBob->channelContext[1]->s0, contextAlice->channelContext[1]->s0, contextAlice->channelContext[1]->hashLength) == 0) { bzrtp_message("Got the same s0\n"); CU_PASS("s0 match"); } else { bzrtp_message("AARGG!! s0 mismatch"); CU_FAIL("s0 mismatch"); } /* the rest of key derivation is common to DH mode, no need to test it as it has been done before for channel 0 */ /* we must anyway derive zrtp and mac key for initiator and responder in order to be able to build the confirm packets */ contextAlice->channelContext[1]->mackeyi = (uint8_t *)malloc(contextAlice->channelContext[1]->hashLength*(sizeof(uint8_t))); contextAlice->channelContext[1]->mackeyr = (uint8_t *)malloc(contextAlice->channelContext[1]->hashLength*(sizeof(uint8_t))); contextAlice->channelContext[1]->zrtpkeyi = (uint8_t *)malloc(contextAlice->channelContext[1]->cipherKeyLength*(sizeof(uint8_t))); contextAlice->channelContext[1]->zrtpkeyr = (uint8_t *)malloc(contextAlice->channelContext[1]->cipherKeyLength*(sizeof(uint8_t))); contextBob->channelContext[1]->mackeyi = (uint8_t *)malloc(contextBob->channelContext[1]->hashLength*(sizeof(uint8_t))); contextBob->channelContext[1]->mackeyr = (uint8_t *)malloc(contextBob->channelContext[1]->hashLength*(sizeof(uint8_t))); contextBob->channelContext[1]->zrtpkeyi = (uint8_t *)malloc(contextBob->channelContext[1]->cipherKeyLength*(sizeof(uint8_t))); contextBob->channelContext[1]->zrtpkeyr = (uint8_t *)malloc(contextBob->channelContext[1]->cipherKeyLength*(sizeof(uint8_t))); /* Alice */ retval = bzrtp_keyDerivationFunction(contextAlice->channelContext[1]->s0, contextAlice->channelContext[1]->hashLength, (uint8_t *)"Initiator HMAC key", 18, contextAlice->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContextLength, contextAlice->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[1]->hmacFunction, contextAlice->channelContext[1]->mackeyi); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[1]->s0, contextAlice->channelContext[1]->hashLength, (uint8_t *)"Responder HMAC key", 18, contextAlice->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContextLength, contextAlice->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[1]->hmacFunction, contextAlice->channelContext[1]->mackeyr); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[1]->s0, contextAlice->channelContext[1]->hashLength, (uint8_t *)"Initiator ZRTP key", 18, contextAlice->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContextLength, contextAlice->channelContext[1]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[1]->hmacFunction, contextAlice->channelContext[1]->zrtpkeyi); retval += bzrtp_keyDerivationFunction(contextAlice->channelContext[1]->s0, contextAlice->channelContext[1]->hashLength, (uint8_t *)"Responder ZRTP key", 18, contextAlice->channelContext[1]->KDFContext, contextAlice->channelContext[1]->KDFContextLength, contextAlice->channelContext[1]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextAlice->channelContext[1]->hmacFunction, contextAlice->channelContext[1]->zrtpkeyr); /* Bob */ retval = bzrtp_keyDerivationFunction(contextBob->channelContext[1]->s0, contextBob->channelContext[1]->hashLength, (uint8_t *)"Initiator HMAC key", 18, contextBob->channelContext[1]->KDFContext, contextBob->channelContext[1]->KDFContextLength, contextBob->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[1]->hmacFunction, contextBob->channelContext[1]->mackeyi); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[1]->s0, contextBob->channelContext[1]->hashLength, (uint8_t *)"Responder HMAC key", 18, contextBob->channelContext[1]->KDFContext, contextBob->channelContext[1]->KDFContextLength, contextBob->channelContext[1]->hashLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[1]->hmacFunction, contextBob->channelContext[1]->mackeyr); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[1]->s0, contextBob->channelContext[1]->hashLength, (uint8_t *)"Initiator ZRTP key", 18, contextBob->channelContext[1]->KDFContext, contextBob->channelContext[1]->KDFContextLength, contextBob->channelContext[1]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[1]->hmacFunction, contextBob->channelContext[1]->zrtpkeyi); retval += bzrtp_keyDerivationFunction(contextBob->channelContext[1]->s0, contextBob->channelContext[1]->hashLength, (uint8_t *)"Responder ZRTP key", 18, contextBob->channelContext[1]->KDFContext, contextBob->channelContext[1]->KDFContextLength, contextBob->channelContext[1]->cipherKeyLength, (void (*)(uint8_t *, uint8_t, uint8_t *, uint32_t, uint8_t, uint8_t *))contextBob->channelContext[1]->hmacFunction, contextBob->channelContext[1]->zrtpkeyr); /* DEBUG compare keys */ if ((memcmp(contextAlice->channelContext[1]->mackeyi, contextBob->channelContext[1]->mackeyi, contextAlice->channelContext[1]->hashLength)==0) && (memcmp(contextAlice->channelContext[1]->mackeyr, contextBob->channelContext[1]->mackeyr, contextAlice->channelContext[1]->hashLength)==0) && (memcmp(contextAlice->channelContext[1]->zrtpkeyi, contextBob->channelContext[1]->zrtpkeyi, contextAlice->channelContext[1]->cipherKeyLength)==0) && (memcmp(contextAlice->channelContext[1]->zrtpkeyr, contextBob->channelContext[1]->zrtpkeyr, contextAlice->channelContext[1]->cipherKeyLength)==0)) { bzrtp_message("Got the same keys\n"); CU_PASS("keys match"); } else { bzrtp_message("ERROR keys differ\n"); CU_PASS("Keys mismatch"); } /* now Alice build a confirm1 packet */ alice_Confirm1 = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[1], MSGTYPE_CONFIRM1, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[1], alice_Confirm1, contextAlice->channelContext[1]->selfSequenceNumber); if (retval == 0) { contextAlice->channelContext[1]->selfSequenceNumber++; } bzrtp_message("Alice building Confirm1 return %x\n", retval); bob_Confirm1FromAlice = bzrtp_packetCheck(alice_Confirm1->packetString, alice_Confirm1->messageLength+16, contextBob->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[1], alice_Confirm1->packetString, alice_Confirm1->messageLength+16, bob_Confirm1FromAlice); bzrtp_message ("Bob parsing confirm1 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextBob->channelContext[1]->peerSequenceNumber = bob_Confirm1FromAlice->sequenceNumber; bob_Confirm1FromAlice_message = (bzrtpConfirmMessage_t *)bob_Confirm1FromAlice->messageData; memcpy(contextBob->channelContext[1]->peerH[0], bob_Confirm1FromAlice_message->H0, 32); } packetDump(bob_Confirm1FromAlice,0); bzrtp_freeZrtpPacket(bob_Confirm1FromAlice); bzrtp_freeZrtpPacket(alice_Confirm1); /* now Bob build the CONFIRM2 packet and send it to Alice */ bob_Confirm2 = bzrtp_createZrtpPacket(contextBob, contextBob->channelContext[1], MSGTYPE_CONFIRM2, &retval); retval += bzrtp_packetBuild(contextBob, contextBob->channelContext[1], bob_Confirm2, contextBob->channelContext[1]->selfSequenceNumber); if (retval == 0) { contextBob->channelContext[1]->selfSequenceNumber++; } bzrtp_message("Bob building Confirm2 return %x\n", retval); alice_Confirm2FromBob = bzrtp_packetCheck(bob_Confirm2->packetString, bob_Confirm2->messageLength+16, contextAlice->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextAlice, contextAlice->channelContext[1], bob_Confirm2->packetString, bob_Confirm2->messageLength+16, alice_Confirm2FromBob); bzrtp_message ("Alice parsing confirm2 returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextAlice->channelContext[1]->peerSequenceNumber = alice_Confirm2FromBob->sequenceNumber; alice_Confirm2FromBob_message = (bzrtpConfirmMessage_t *)alice_Confirm2FromBob->messageData; memcpy(contextAlice->channelContext[1]->peerH[0], alice_Confirm2FromBob_message->H0, 32); } packetDump(alice_Confirm2FromBob,0); bzrtp_freeZrtpPacket(alice_Confirm2FromBob); bzrtp_freeZrtpPacket(bob_Confirm2); /* Alice build the conf2Ack and send it to Bob */ alice_Conf2ACK = bzrtp_createZrtpPacket(contextAlice, contextAlice->channelContext[1], MSGTYPE_CONF2ACK, &retval); retval += bzrtp_packetBuild(contextAlice, contextAlice->channelContext[1], alice_Conf2ACK, contextAlice->channelContext[1]->selfSequenceNumber); if (retval == 0) { contextAlice->channelContext[1]->selfSequenceNumber++; } bzrtp_message("Alice building Conf2ACK return %x\n", retval); bob_Conf2ACKFromAlice = bzrtp_packetCheck(alice_Conf2ACK->packetString, alice_Conf2ACK->messageLength+16, contextBob->channelContext[1]->peerSequenceNumber, &retval); retval += bzrtp_packetParser(contextBob, contextBob->channelContext[1], alice_Conf2ACK->packetString, alice_Conf2ACK->messageLength+16, bob_Conf2ACKFromAlice); bzrtp_message ("Bob parsing conf2ACK returns %x\n", retval); if (retval==0) { /* update context with the information found in the packet */ contextBob->channelContext[1]->peerSequenceNumber = bob_Conf2ACKFromAlice->sequenceNumber; } bzrtp_freeZrtpPacket(alice_Conf2ACK); bzrtp_freeZrtpPacket(bob_Conf2ACKFromAlice); /* dumpContext("\nAlice", contextAlice); dumpContext("\nBob", contextBob); */ bzrtp_message("Destroy the contexts\n"); /* destroy the context */ bzrtp_destroyBzrtpContext(contextAlice, 0x45678901); bzrtp_destroyBzrtpContext(contextBob, 0x54321098); bzrtp_message("Destroy the contexts last channel\n"); bzrtp_destroyBzrtpContext(contextBob, 0x87654321); bzrtp_destroyBzrtpContext(contextAlice, 0x12345678); } typedef struct packetDatas_struct { uint8_t packetString[1000]; uint16_t packetLength; } packetDatas_t; /* Alice and Bob packet queues are globals */ packetDatas_t aliceQueue[10]; packetDatas_t bobQueue[10]; uint8_t aliceQueueIndex = 0; uint8_t bobQueueIndex = 0; uint8_t block_Hello = 0; /* this is a callback function for send data, just dump the packet */ /* client Data is a my_Context_t structure */ int bzrtp_sendData(void *clientData, const uint8_t *packetString, uint16_t packetLength) { /* get the client Data */ my_Context_t *contexts = (my_Context_t *)clientData; /* bzrtp_message ("%s sends a message!\n", contexts->nom); int retval; bzrtpPacket_t *zrtpPacket = bzrtp_packetCheck(packetString, packetLength, contexts->peerChannelContext->peerSequenceNumber, &retval); if (retval==0) { retval = bzrtp_packetParser(contexts->peerContext, contexts->peerChannelContext, packetString, packetLength, zrtpPacket); if (retval == 0) { */ /* packetDump(zrtpPacket,0); */ /* printHex("Data", packetString, packetLength);*/ /* } else { bzrtp_message("Parse says %04x\n", retval); } } else { bzrtp_message("Check says %04x\n", retval); } */ /* put the message in the message queue */ if (contexts->nom[0] == 'A') { /* message sent by Alice, put it in Bob's queue */ /* block the first Hello to force going through wait for hello state and check it is retransmitted */ /* if ((block_Hello == 0) && (zrtpPacket->messageType == MSGTYPE_HELLO)) { block_Hello = 1; } else {*/ memcpy(bobQueue[bobQueueIndex].packetString, packetString, packetLength); bobQueue[bobQueueIndex++].packetLength = packetLength; /* }*/ } else { memcpy(aliceQueue[aliceQueueIndex].packetString, packetString, packetLength); aliceQueue[aliceQueueIndex++].packetLength = packetLength; } /* bzrtp_freeZrtpPacket(zrtpPacket); */ return 0; } uint64_t myCurrentTime = 0; /* we do not need a real time, start at 0 and increment it at each sleep */ uint64_t getCurrentTimeInMs() { return myCurrentTime; } static void sleepMs(int ms){ #ifdef _WIN32 Sleep(ms); #else struct timespec ts; ts.tv_sec=0; ts.tv_nsec=ms*1000000LL; nanosleep(&ts,NULL); #endif myCurrentTime +=ms; } /* Ping message length is 24 bytes (already define in packetParser.c out of this scope) */ #define ZRTP_PINGMESSAGE_FIXED_LENGTH 24 void test_stateMachine() { int retval; my_Context_t aliceClientData, bobClientData; uint64_t initialTime; uint8_t pingPacketString[ZRTP_PACKET_OVERHEAD+ZRTP_PINGMESSAGE_FIXED_LENGTH]; /* there is no builder for ping packet and it is 24 bytes long(12 bytes of message header, 12 of data + packet overhead*/ uint32_t CRC; uint8_t *CRCbuffer; my_Context_t aliceSecondChannelClientData, bobSecondChannelClientData; bzrtpCallbacks_t cbs={0} ; /* Create zrtp Context */ bzrtpContext_t *contextAlice = bzrtp_createBzrtpContext(0x12345678); /* Alice's SSRC of main channel is 12345678 */ bzrtpContext_t *contextBob = bzrtp_createBzrtpContext(0x87654321); /* Bob's SSRC of main channel is 87654321 */ /* set the cache related callback functions */ cbs.bzrtp_loadCache=floadAlice; cbs.bzrtp_writeCache=fwriteAlice; cbs.bzrtp_sendData=bzrtp_sendData; bzrtp_setCallbacks(contextAlice, &cbs); cbs.bzrtp_loadCache=floadBob; cbs.bzrtp_writeCache=fwriteBob; cbs.bzrtp_sendData=bzrtp_sendData; bzrtp_setCallbacks(contextBob, &cbs); /* create the client Data and associate them to the channel contexts */ memcpy(aliceClientData.nom, "Alice", 6); memcpy(bobClientData.nom, "Bob", 4); aliceClientData.peerContext = contextBob; aliceClientData.peerChannelContext = contextBob->channelContext[0]; bobClientData.peerContext = contextAlice; bobClientData.peerChannelContext = contextAlice->channelContext[0]; strcpy(aliceClientData.zidFilename, "./ZIDAlice.txt"); strcpy(bobClientData.zidFilename, "./ZIDBob.txt"); retval = bzrtp_setClientData(contextAlice, 0x12345678, (void *)&aliceClientData); retval += bzrtp_setClientData(contextBob, 0x87654321, (void *)&bobClientData); bzrtp_message("Set client data return %x\n", retval); /* run the init */ bzrtp_initBzrtpContext(contextAlice); bzrtp_initBzrtpContext(contextBob); /* now start the engine */ initialTime = getCurrentTimeInMs(); retval = bzrtp_startChannelEngine(contextAlice, 0x12345678); bzrtp_message ("Alice starts return %x\n", retval); retval = bzrtp_startChannelEngine(contextBob, 0x87654321); bzrtp_message ("Bob starts return %x\n", retval); /* now start infinite loop until we reach secure state */ while ((contextAlice->isSecure == 0 || contextBob->isSecure == 0) && (getCurrentTimeInMs()-initialTime<5000)){ int i; /* first check the message queue */ for (i=0; i<aliceQueueIndex; i++) { bzrtp_message("Process a message for Alice\n"); retval = bzrtp_processMessage(contextAlice, 0x12345678, aliceQueue[i].packetString, aliceQueue[i].packetLength); bzrtp_message("Alice processed message %.8s of %d bytes and return %04x\n\n", aliceQueue[i].packetString+16, aliceQueue[i].packetLength, retval); memset(aliceQueue[i].packetString, 0, 1000); /* destroy the packet after sending it to the ZRTP engine */ } aliceQueueIndex = 0; for (i=0; i<bobQueueIndex; i++) { bzrtp_message("Process a message for Bob\n"); retval = bzrtp_processMessage(contextBob, 0x87654321, bobQueue[i].packetString, bobQueue[i].packetLength); bzrtp_message("Bob processed message %.8s of %d bytes and return %04x\n\n", bobQueue[i].packetString+16, bobQueue[i].packetLength, retval); memset(bobQueue[i].packetString, 0, 1000); /* destroy the packet after sending it to the ZRTP engine */ } bobQueueIndex = 0; /* send the actual time to the zrtpContext */ bzrtp_iterate(contextAlice, 0x12345678, getCurrentTimeInMs()); bzrtp_iterate(contextBob, 0x87654321, getCurrentTimeInMs()); /* sleep for 10 ms */ sleepMs(10); } /* compare SAS and check we are in secure mode */ if ((contextAlice->isSecure == 1) && (contextBob->isSecure == 1)) { /* don't compare sas if we're not secure at we may not have it */ CU_ASSERT_TRUE((memcmp(contextAlice->channelContext[0]->srtpSecrets.sas, contextBob->channelContext[0]->srtpSecrets.sas, 4) == 0)); /* call the set verified Sas function */ bzrtp_SASVerified(contextAlice); bzrtp_SASVerified(contextBob); } else { CU_FAIL("Unable to reach secure state"); } /*** Send alice a ping message from Bob ***/ /* set packet header and CRC */ /* preambule */ pingPacketString[0] = 0x10; pingPacketString[1] = 0x00; /* Sequence number */ pingPacketString[2] = (uint8_t)((contextBob->channelContext[0]->selfSequenceNumber>>8)&0x00FF); pingPacketString[3] = (uint8_t)(contextBob->channelContext[0]->selfSequenceNumber&0x00FF); /* ZRTP magic cookie */ pingPacketString[4] = (uint8_t)((ZRTP_MAGIC_COOKIE>>24)&0xFF); pingPacketString[5] = (uint8_t)((ZRTP_MAGIC_COOKIE>>16)&0xFF); pingPacketString[6] = (uint8_t)((ZRTP_MAGIC_COOKIE>>8)&0xFF); pingPacketString[7] = (uint8_t)(ZRTP_MAGIC_COOKIE&0xFF); /* Source Identifier : insert bob's one: 0x87654321 */ pingPacketString[8] = 0x87; pingPacketString[9] = 0x65; pingPacketString[10] = 0x43; pingPacketString[11] = 0x21; /* message header */ pingPacketString[12] = 0x50; pingPacketString[13] = 0x5a; /* length in 32 bits words */ pingPacketString[14] = 0x00; pingPacketString[15] = 0x06; /* message type "Ping " */ memcpy(pingPacketString+16, "Ping ",8); /* Version on 4 bytes is "1.10" */ memcpy(pingPacketString+24, "1.10", 4); /* a endPointHash, use the first 8 bytes of Bob's ZID */ memcpy(pingPacketString+28, contextBob->selfZID, 8); /* CRC */ CRC = bzrtp_CRC32(pingPacketString, ZRTP_PINGMESSAGE_FIXED_LENGTH+ZRTP_PACKET_HEADER_LENGTH); CRCbuffer = pingPacketString+ZRTP_PINGMESSAGE_FIXED_LENGTH+ZRTP_PACKET_HEADER_LENGTH; *CRCbuffer = (uint8_t)((CRC>>24)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>16)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>8)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)(CRC&0xFF); bzrtp_message("Process a PING message for Alice\n"); retval = bzrtp_processMessage(contextAlice, 0x12345678, pingPacketString, ZRTP_PACKET_OVERHEAD+ZRTP_PINGMESSAGE_FIXED_LENGTH); bzrtp_message("Alice processed PING message and return %04x\n\n", retval); /*** now add a second channel ***/ retval = bzrtp_addChannel(contextAlice, 0x34567890); bzrtp_message("Add a channel to Alice context, return %x\n", retval); retval = bzrtp_addChannel(contextBob, 0x09876543); bzrtp_message("Add a channel to Bob context, return %x\n", retval); /* create the client Data and associate them to the channel contexts */ memcpy(aliceSecondChannelClientData.nom, "Alice", 6); memcpy(bobSecondChannelClientData.nom, "Bob", 4); aliceSecondChannelClientData.peerContext = contextBob; aliceSecondChannelClientData.peerChannelContext = contextBob->channelContext[1]; bobSecondChannelClientData.peerContext = contextAlice; bobSecondChannelClientData.peerChannelContext = contextAlice->channelContext[1]; retval = bzrtp_setClientData(contextAlice, 0x34567890, (void *)&aliceSecondChannelClientData); retval += bzrtp_setClientData(contextBob, 0x09876543, (void *)&bobSecondChannelClientData); bzrtp_message("Set client data return %x\n", retval); /* start the channels */ retval = bzrtp_startChannelEngine(contextAlice, 0x34567890); bzrtp_message ("Alice starts return %x\n", retval); retval = bzrtp_startChannelEngine(contextBob, 0x09876543); bzrtp_message ("Bob starts return %x\n", retval); /* now start infinite loop until we reach secure state */ while ((getCurrentTimeInMs()-initialTime<2000)){ int i; /* first check the message queue */ for (i=0; i<aliceQueueIndex; i++) { bzrtp_message("Process a message for Alice\n"); retval = bzrtp_processMessage(contextAlice, 0x34567890, aliceQueue[i].packetString, aliceQueue[i].packetLength); bzrtp_message("Alice processed message %.8s of %d bytes and return %04x\n\n", aliceQueue[i].packetString+16, aliceQueue[i].packetLength, retval); memset(aliceQueue[i].packetString, 0, 1000); /* destroy the packet after sending it to the ZRTP engine */ } aliceQueueIndex = 0; for (i=0; i<bobQueueIndex; i++) { bzrtp_message("Process a message for Bob\n"); retval = bzrtp_processMessage(contextBob, 0x09876543, bobQueue[i].packetString, bobQueue[i].packetLength); bzrtp_message("Bob processed message %.8s of %d bytes and return %04x\n\n", bobQueue[i].packetString+16, bobQueue[i].packetLength, retval); memset(bobQueue[i].packetString, 0, 1000); /* destroy the packet after sending it to the ZRTP engine */ } bobQueueIndex = 0; /* send the actual time to the zrtpContext */ bzrtp_iterate(contextAlice, 0x34567890, getCurrentTimeInMs()); bzrtp_iterate(contextBob, 0x09876543, getCurrentTimeInMs()); /* sleep for 10 ms */ sleepMs(10); } CU_ASSERT_TRUE((memcmp(contextAlice->channelContext[1]->srtpSecrets.selfSrtpKey, contextBob->channelContext[1]->srtpSecrets.peerSrtpKey, 16) == 0) && (contextAlice->isSecure == 1) && (contextBob->isSecure == 1)); dumpContext("\nAlice", contextAlice); dumpContext("\nBob", contextBob); bzrtp_message("Destroy the contexts\n"); /* destroy the context */ bzrtp_destroyBzrtpContext(contextAlice, 0x34567890); bzrtp_destroyBzrtpContext(contextBob, 0x09876543); bzrtp_message("Destroy the contexts last channel\n"); bzrtp_destroyBzrtpContext(contextBob, 0x87654321); bzrtp_destroyBzrtpContext(contextAlice, 0x12345678); }
./CrossVul/dataset_final_sorted/CWE-254/c/good_5205_2
crossvul-cpp_data_bad_5010_0
/* * Flexible mmap layout support * * Based on code by Ingo Molnar and Andi Kleen, copyrighted * as follows: * * Copyright 2003-2009 Red Hat Inc. * All Rights Reserved. * Copyright 2005 Andi Kleen, SUSE Labs. * Copyright 2007 Jiri Kosina, SUSE Labs. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/personality.h> #include <linux/mm.h> #include <linux/random.h> #include <linux/limits.h> #include <linux/sched.h> #include <asm/elf.h> struct va_alignment __read_mostly va_align = { .flags = -1, }; static unsigned long stack_maxrandom_size(void) { unsigned long max = 0; if ((current->flags & PF_RANDOMIZE) && !(current->personality & ADDR_NO_RANDOMIZE)) { max = ((-1UL) & STACK_RND_MASK) << PAGE_SHIFT; } return max; } /* * Top of mmap area (just below the process stack). * * Leave an at least ~128 MB hole with possible stack randomization. */ #define MIN_GAP (128*1024*1024UL + stack_maxrandom_size()) #define MAX_GAP (TASK_SIZE/6*5) static int mmap_is_legacy(void) { if (current->personality & ADDR_COMPAT_LAYOUT) return 1; if (rlimit(RLIMIT_STACK) == RLIM_INFINITY) return 1; return sysctl_legacy_va_layout; } unsigned long arch_mmap_rnd(void) { unsigned long rnd; if (mmap_is_ia32()) #ifdef CONFIG_COMPAT rnd = (unsigned long)get_random_int() & ((1 << mmap_rnd_compat_bits) - 1); #else rnd = (unsigned long)get_random_int() & ((1 << mmap_rnd_bits) - 1); #endif else rnd = (unsigned long)get_random_int() & ((1 << mmap_rnd_bits) - 1); return rnd << PAGE_SHIFT; } static unsigned long mmap_base(unsigned long rnd) { unsigned long gap = rlimit(RLIMIT_STACK); if (gap < MIN_GAP) gap = MIN_GAP; else if (gap > MAX_GAP) gap = MAX_GAP; return PAGE_ALIGN(TASK_SIZE - gap - rnd); } /* * Bottom-up (legacy) layout on X86_32 did not support randomization, X86_64 * does, but not when emulating X86_32 */ static unsigned long mmap_legacy_base(unsigned long rnd) { if (mmap_is_ia32()) return TASK_UNMAPPED_BASE; else return TASK_UNMAPPED_BASE + rnd; } /* * This function, called very early during the creation of a new * process VM image, sets up which VM layout function to use: */ void arch_pick_mmap_layout(struct mm_struct *mm) { unsigned long random_factor = 0UL; if (current->flags & PF_RANDOMIZE) random_factor = arch_mmap_rnd(); mm->mmap_legacy_base = mmap_legacy_base(random_factor); if (mmap_is_legacy()) { mm->mmap_base = mm->mmap_legacy_base; mm->get_unmapped_area = arch_get_unmapped_area; } else { mm->mmap_base = mmap_base(random_factor); mm->get_unmapped_area = arch_get_unmapped_area_topdown; } } const char *arch_vma_name(struct vm_area_struct *vma) { if (vma->vm_flags & VM_MPX) return "[mpx]"; return NULL; }
./CrossVul/dataset_final_sorted/CWE-254/c/bad_5010_0
crossvul-cpp_data_bad_480_1
/* Copyright (c) 2009-2018 Roger Light <roger@atchoo.org> All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 and Eclipse Distribution License v1.0 which accompany this distribution. The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution License is available at http://www.eclipse.org/org/documents/edl-v10.php. Contributors: Roger Light - initial implementation and documentation. */ #include "config.h" #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #ifdef WIN32 #else # include <dirent.h> # include <strings.h> #endif #ifndef WIN32 # include <netdb.h> # include <sys/socket.h> #else # include <winsock2.h> # include <ws2tcpip.h> #endif #if !defined(WIN32) && !defined(__CYGWIN__) # include <syslog.h> #endif #include "mosquitto_broker_internal.h" #include "memory_mosq.h" #include "tls_mosq.h" #include "util_mosq.h" #include "mqtt3_protocol.h" struct config_recurse { int log_dest; int log_dest_set; int log_type; int log_type_set; unsigned long max_inflight_bytes; unsigned long max_queued_bytes; int max_inflight_messages; int max_queued_messages; }; #if defined(WIN32) || defined(__CYGWIN__) #include <windows.h> extern SERVICE_STATUS_HANDLE service_handle; #endif static int conf__parse_bool(char **token, const char *name, bool *value, char *saveptr); static int conf__parse_int(char **token, const char *name, int *value, char *saveptr); static int conf__parse_ssize_t(char **token, const char *name, ssize_t *value, char *saveptr); static int conf__parse_string(char **token, const char *name, char **value, char *saveptr); static int config__read_file(struct mosquitto__config *config, bool reload, const char *file, struct config_recurse *config_tmp, int level, int *lineno); static int config__check(struct mosquitto__config *config); static void config__cleanup_plugins(struct mosquitto__config *config); static char *fgets_extending(char **buf, int *buflen, FILE *stream) { char *rc; char endchar; int offset = 0; char *newbuf; do{ rc = fgets(&((*buf)[offset]), *buflen-offset, stream); if(feof(stream)){ return rc; } endchar = (*buf)[strlen(*buf)-1]; if(endchar == '\n'){ return rc; } /* No EOL char found, so extend buffer */ offset = *buflen-1; *buflen += 1000; newbuf = realloc(*buf, *buflen); if(!newbuf){ return NULL; } *buf = newbuf; }while(1); } static void conf__set_cur_security_options(struct mosquitto__config *config, struct mosquitto__listener *cur_listener, struct mosquitto__security_options **security_options) { if(config->per_listener_settings){ (*security_options) = &cur_listener->security_options; }else{ (*security_options) = &config->security_options; } } static int conf__attempt_resolve(const char *host, const char *text, int log, const char *msg) { struct addrinfo gai_hints; struct addrinfo *gai_res; int rc; memset(&gai_hints, 0, sizeof(struct addrinfo)); gai_hints.ai_family = AF_UNSPEC; gai_hints.ai_socktype = SOCK_STREAM; gai_res = NULL; rc = getaddrinfo(host, NULL, &gai_hints, &gai_res); if(gai_res){ freeaddrinfo(gai_res); } if(rc != 0){ #ifndef WIN32 if(rc == EAI_SYSTEM){ if(errno == ENOENT){ log__printf(NULL, log, "%s: Unable to resolve %s %s.", msg, text, host); }else{ log__printf(NULL, log, "%s: Error resolving %s: %s.", msg, text, strerror(errno)); } }else{ log__printf(NULL, log, "%s: Error resolving %s: %s.", msg, text, gai_strerror(rc)); } #else if(rc == WSAHOST_NOT_FOUND){ log__printf(NULL, log, "%s: Error resolving %s.", msg, text); } #endif return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static void config__init_reload(struct mosquitto_db *db, struct mosquitto__config *config) { int i; /* Set defaults */ for(i=0; i<config->listener_count; i++){ mosquitto__free(config->listeners[i].security_options.acl_file); config->listeners[i].security_options.acl_file = NULL; mosquitto__free(config->listeners[i].security_options.password_file); config->listeners[i].security_options.password_file = NULL; mosquitto__free(config->listeners[i].security_options.psk_file); config->listeners[i].security_options.psk_file = NULL; config->listeners[i].security_options.allow_anonymous = -1; config->listeners[i].security_options.allow_zero_length_clientid = true; config->listeners[i].security_options.auto_id_prefix = NULL; config->listeners[i].security_options.auto_id_prefix_len = 0; } config->allow_duplicate_messages = false; mosquitto__free(config->security_options.acl_file); config->security_options.acl_file = NULL; config->security_options.allow_anonymous = -1; config->security_options.allow_zero_length_clientid = true; config->security_options.auto_id_prefix = NULL; config->security_options.auto_id_prefix_len = 0; mosquitto__free(config->security_options.password_file); config->security_options.password_file = NULL; mosquitto__free(config->security_options.psk_file); config->security_options.psk_file = NULL; config->autosave_interval = 1800; config->autosave_on_changes = false; mosquitto__free(config->clientid_prefixes); config->connection_messages = true; config->clientid_prefixes = NULL; config->per_listener_settings = false; if(config->log_fptr){ fclose(config->log_fptr); config->log_fptr = NULL; } mosquitto__free(config->log_file); config->log_file = NULL; #if defined(WIN32) || defined(__CYGWIN__) if(service_handle){ /* This is running as a Windows service. Default to no logging. Using * stdout/stderr is forbidden because the first clients to connect will * get log information sent to them for some reason. */ config->log_dest = MQTT3_LOG_NONE; }else{ config->log_dest = MQTT3_LOG_STDERR; } #else config->log_facility = LOG_DAEMON; config->log_dest = MQTT3_LOG_STDERR; if(db->verbose){ config->log_type = INT_MAX; }else{ config->log_type = MOSQ_LOG_ERR | MOSQ_LOG_WARNING | MOSQ_LOG_NOTICE | MOSQ_LOG_INFO; } #endif config->log_timestamp = true; config->persistence = false; mosquitto__free(config->persistence_location); config->persistence_location = NULL; mosquitto__free(config->persistence_file); config->persistence_file = NULL; config->persistent_client_expiration = 0; config->queue_qos0_messages = false; config->set_tcp_nodelay = false; config->sys_interval = 10; config->upgrade_outgoing_qos = false; config__cleanup_plugins(config); } static void config__cleanup_plugins(struct mosquitto__config *config) { int i, j; struct mosquitto__auth_plugin_config *plug; if(config->security_options.auth_plugin_configs){ for(i=0; i<config->security_options.auth_plugin_config_count; i++){ plug = &config->security_options.auth_plugin_configs[i]; mosquitto__free(plug->path); plug->path = NULL; if(plug->options){ for(j=0; j<plug->option_count; j++){ mosquitto__free(plug->options[j].key); mosquitto__free(plug->options[j].value); } mosquitto__free(plug->options); plug->options = NULL; plug->option_count = 0; } } mosquitto__free(config->security_options.auth_plugin_configs); config->security_options.auth_plugin_configs = NULL; } } void config__init(struct mosquitto_db *db, struct mosquitto__config *config) { memset(config, 0, sizeof(struct mosquitto__config)); config__init_reload(db, config); config->daemon = false; memset(&config->default_listener, 0, sizeof(struct mosquitto__listener)); config->default_listener.max_connections = -1; config->default_listener.protocol = mp_mqtt; config->default_listener.security_options.allow_anonymous = -1; } void config__cleanup(struct mosquitto__config *config) { int i; int j; mosquitto__free(config->clientid_prefixes); mosquitto__free(config->persistence_location); mosquitto__free(config->persistence_file); mosquitto__free(config->persistence_filepath); mosquitto__free(config->security_options.auto_id_prefix); mosquitto__free(config->security_options.acl_file); mosquitto__free(config->security_options.password_file); mosquitto__free(config->security_options.psk_file); mosquitto__free(config->pid_file); if(config->listeners){ for(i=0; i<config->listener_count; i++){ mosquitto__free(config->listeners[i].host); mosquitto__free(config->listeners[i].mount_point); mosquitto__free(config->listeners[i].socks); mosquitto__free(config->listeners[i].security_options.auto_id_prefix); mosquitto__free(config->listeners[i].security_options.acl_file); mosquitto__free(config->listeners[i].security_options.password_file); mosquitto__free(config->listeners[i].security_options.psk_file); #ifdef WITH_TLS mosquitto__free(config->listeners[i].cafile); mosquitto__free(config->listeners[i].capath); mosquitto__free(config->listeners[i].certfile); mosquitto__free(config->listeners[i].keyfile); mosquitto__free(config->listeners[i].ciphers); mosquitto__free(config->listeners[i].psk_hint); mosquitto__free(config->listeners[i].crlfile); mosquitto__free(config->listeners[i].tls_version); #ifdef WITH_WEBSOCKETS if(!config->listeners[i].ws_context) /* libwebsockets frees its own SSL_CTX */ #endif { SSL_CTX_free(config->listeners[i].ssl_ctx); } #endif #ifdef WITH_WEBSOCKETS mosquitto__free(config->listeners[i].http_dir); #endif } mosquitto__free(config->listeners); } #ifdef WITH_BRIDGE if(config->bridges){ for(i=0; i<config->bridge_count; i++){ mosquitto__free(config->bridges[i].name); if(config->bridges[i].addresses){ for(j=0; j<config->bridges[i].address_count; j++){ mosquitto__free(config->bridges[i].addresses[j].address); } mosquitto__free(config->bridges[i].addresses); } mosquitto__free(config->bridges[i].remote_clientid); mosquitto__free(config->bridges[i].remote_username); mosquitto__free(config->bridges[i].remote_password); mosquitto__free(config->bridges[i].local_clientid); mosquitto__free(config->bridges[i].local_username); mosquitto__free(config->bridges[i].local_password); if(config->bridges[i].topics){ for(j=0; j<config->bridges[i].topic_count; j++){ mosquitto__free(config->bridges[i].topics[j].topic); mosquitto__free(config->bridges[i].topics[j].local_prefix); mosquitto__free(config->bridges[i].topics[j].remote_prefix); mosquitto__free(config->bridges[i].topics[j].local_topic); mosquitto__free(config->bridges[i].topics[j].remote_topic); } mosquitto__free(config->bridges[i].topics); } mosquitto__free(config->bridges[i].notification_topic); #ifdef WITH_TLS mosquitto__free(config->bridges[i].tls_version); mosquitto__free(config->bridges[i].tls_cafile); #ifdef WITH_TLS_PSK mosquitto__free(config->bridges[i].tls_psk_identity); mosquitto__free(config->bridges[i].tls_psk); #endif #endif } mosquitto__free(config->bridges); } #endif config__cleanup_plugins(config); if(config->log_fptr){ fclose(config->log_fptr); config->log_fptr = NULL; } if(config->log_file){ mosquitto__free(config->log_file); config->log_file = NULL; } } static void print_usage(void) { printf("mosquitto version %s\n\n", VERSION); printf("mosquitto is an MQTT v3.1.1 broker.\n\n"); printf("Usage: mosquitto [-c config_file] [-d] [-h] [-p port]\n\n"); printf(" -c : specify the broker config file.\n"); printf(" -d : put the broker into the background after starting.\n"); printf(" -h : display this help.\n"); printf(" -p : start the broker listening on the specified port.\n"); printf(" Not recommended in conjunction with the -c option.\n"); printf(" -v : verbose mode - enable all logging types. This overrides\n"); printf(" any logging options given in the config file.\n"); printf("\nSee http://mosquitto.org/ for more information.\n\n"); } int config__parse_args(struct mosquitto_db *db, struct mosquitto__config *config, int argc, char *argv[]) { int i; int port_tmp; for(i=1; i<argc; i++){ if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--config-file")){ if(i<argc-1){ db->config_file = argv[i+1]; if(config__read(db, config, false)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open configuration file."); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -c argument given, but no config file specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--daemon")){ config->daemon = true; }else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")){ print_usage(); return MOSQ_ERR_INVAL; }else if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){ if(i<argc-1){ port_tmp = atoi(argv[i+1]); if(port_tmp<1 || port_tmp>65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port specified (%d).", port_tmp); return MOSQ_ERR_INVAL; }else{ if(config->default_listener.port){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Default listener port specified multiple times. Only the latest will be used."); } config->default_listener.port = port_tmp; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -p argument given, but no port specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){ db->verbose = true; }else{ fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]); print_usage(); return MOSQ_ERR_INVAL; } } if(config->listener_count == 0 #ifdef WITH_TLS || config->default_listener.cafile || config->default_listener.capath || config->default_listener.certfile || config->default_listener.keyfile || config->default_listener.ciphers || config->default_listener.psk_hint || config->default_listener.require_certificate || config->default_listener.crlfile || config->default_listener.use_identity_as_username || config->default_listener.use_subject_as_username #endif || config->default_listener.use_username_as_clientid || config->default_listener.host || config->default_listener.port || config->default_listener.max_connections != -1 || config->default_listener.mount_point || config->default_listener.protocol != mp_mqtt || config->default_listener.socket_domain || config->default_listener.security_options.password_file || config->default_listener.security_options.psk_file || config->default_listener.security_options.auth_plugin_config_count || config->default_listener.security_options.allow_anonymous != -1 ){ config->listener_count++; config->listeners = mosquitto__realloc(config->listeners, sizeof(struct mosquitto__listener)*config->listener_count); if(!config->listeners){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } memset(&config->listeners[config->listener_count-1], 0, sizeof(struct mosquitto__listener)); if(config->default_listener.port){ config->listeners[config->listener_count-1].port = config->default_listener.port; }else{ config->listeners[config->listener_count-1].port = 1883; } if(config->default_listener.host){ config->listeners[config->listener_count-1].host = config->default_listener.host; }else{ config->listeners[config->listener_count-1].host = NULL; } if(config->default_listener.mount_point){ config->listeners[config->listener_count-1].mount_point = config->default_listener.mount_point; }else{ config->listeners[config->listener_count-1].mount_point = NULL; } config->listeners[config->listener_count-1].max_connections = config->default_listener.max_connections; config->listeners[config->listener_count-1].protocol = config->default_listener.protocol; config->listeners[config->listener_count-1].socket_domain = config->default_listener.socket_domain; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].socks = NULL; config->listeners[config->listener_count-1].sock_count = 0; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].use_username_as_clientid = config->default_listener.use_username_as_clientid; #ifdef WITH_TLS config->listeners[config->listener_count-1].tls_version = config->default_listener.tls_version; config->listeners[config->listener_count-1].cafile = config->default_listener.cafile; config->listeners[config->listener_count-1].capath = config->default_listener.capath; config->listeners[config->listener_count-1].certfile = config->default_listener.certfile; config->listeners[config->listener_count-1].keyfile = config->default_listener.keyfile; config->listeners[config->listener_count-1].ciphers = config->default_listener.ciphers; config->listeners[config->listener_count-1].psk_hint = config->default_listener.psk_hint; config->listeners[config->listener_count-1].require_certificate = config->default_listener.require_certificate; config->listeners[config->listener_count-1].ssl_ctx = NULL; config->listeners[config->listener_count-1].crlfile = config->default_listener.crlfile; config->listeners[config->listener_count-1].use_identity_as_username = config->default_listener.use_identity_as_username; config->listeners[config->listener_count-1].use_subject_as_username = config->default_listener.use_subject_as_username; #endif config->listeners[config->listener_count-1].security_options.password_file = config->default_listener.security_options.password_file; config->listeners[config->listener_count-1].security_options.psk_file = config->default_listener.security_options.psk_file; config->listeners[config->listener_count-1].security_options.auth_plugin_configs = config->default_listener.security_options.auth_plugin_configs; config->listeners[config->listener_count-1].security_options.auth_plugin_config_count = config->default_listener.security_options.auth_plugin_config_count; config->listeners[config->listener_count-1].security_options.allow_anonymous = config->default_listener.security_options.allow_anonymous; } /* Default to drop to mosquitto user if we are privileged and no user specified. */ if(!config->user){ config->user = "mosquitto"; } if(db->verbose){ config->log_type = INT_MAX; } return config__check(config); } void config__copy(struct mosquitto__config *src, struct mosquitto__config *dest) { mosquitto__free(dest->security_options.acl_file); dest->security_options.acl_file = src->security_options.acl_file; dest->security_options.allow_anonymous = src->security_options.allow_anonymous; dest->security_options.allow_zero_length_clientid = src->security_options.allow_zero_length_clientid; mosquitto__free(dest->security_options.auto_id_prefix); dest->security_options.auto_id_prefix = src->security_options.auto_id_prefix; dest->security_options.auto_id_prefix_len = src->security_options.auto_id_prefix_len; mosquitto__free(dest->security_options.password_file); dest->security_options.password_file = src->security_options.password_file; mosquitto__free(dest->security_options.psk_file); dest->security_options.psk_file = src->security_options.psk_file; dest->allow_duplicate_messages = src->allow_duplicate_messages; dest->autosave_interval = src->autosave_interval; dest->autosave_on_changes = src->autosave_on_changes; mosquitto__free(dest->clientid_prefixes); dest->clientid_prefixes = src->clientid_prefixes; dest->connection_messages = src->connection_messages; dest->log_dest = src->log_dest; dest->log_facility = src->log_facility; dest->log_type = src->log_type; dest->log_timestamp = src->log_timestamp; mosquitto__free(dest->log_file); dest->log_file = src->log_file; dest->message_size_limit = src->message_size_limit; dest->persistence = src->persistence; mosquitto__free(dest->persistence_location); dest->persistence_location = src->persistence_location; mosquitto__free(dest->persistence_file); dest->persistence_file = src->persistence_file; mosquitto__free(dest->persistence_filepath); dest->persistence_filepath = src->persistence_filepath; dest->persistent_client_expiration = src->persistent_client_expiration; dest->queue_qos0_messages = src->queue_qos0_messages; dest->sys_interval = src->sys_interval; dest->upgrade_outgoing_qos = src->upgrade_outgoing_qos; #ifdef WITH_WEBSOCKETS dest->websockets_log_level = src->websockets_log_level; #endif } int config__read(struct mosquitto_db *db, struct mosquitto__config *config, bool reload) { int rc = MOSQ_ERR_SUCCESS; struct config_recurse cr; int lineno = 0; int len; struct mosquitto__config config_reload; int i; if(reload){ memset(&config_reload, 0, sizeof(struct mosquitto__config)); } cr.log_dest = MQTT3_LOG_NONE; cr.log_dest_set = 0; cr.log_type = MOSQ_LOG_NONE; cr.log_type_set = 0; cr.max_inflight_bytes = 0; cr.max_inflight_messages = 20; cr.max_queued_bytes = 0; cr.max_queued_messages = 100; if(!db->config_file) return 0; if(reload){ /* Re-initialise appropriate config vars to default for reload. */ config__init_reload(db, &config_reload); config_reload.listeners = config->listeners; config_reload.listener_count = config->listener_count; rc = config__read_file(&config_reload, reload, db->config_file, &cr, 0, &lineno); }else{ rc = config__read_file(config, reload, db->config_file, &cr, 0, &lineno); } if(rc){ log__printf(NULL, MOSQ_LOG_ERR, "Error found at %s:%d.", db->config_file, lineno); return rc; } if(reload){ config__copy(&config_reload, config); } /* If auth/access options are set and allow_anonymous not explicitly set, disallow anon. */ if(config->per_listener_settings){ for(i=0; i<config->listener_count; i++){ if(config->listeners[i].security_options.allow_anonymous == -1){ if(config->listeners[i].security_options.password_file || config->listeners[i].security_options.psk_file || config->listeners[i].security_options.auth_plugin_configs){ /* allow_anonymous not set explicitly, some other security options * have been set - so disable allow_anonymous */ config->listeners[i].security_options.allow_anonymous = false; }else{ /* Default option if no security options set */ config->listeners[i].security_options.allow_anonymous = true; } } } }else{ if(config->security_options.allow_anonymous == -1){ if(config->security_options.password_file || config->security_options.psk_file || config->security_options.auth_plugin_configs){ /* allow_anonymous not set explicitly, some other security options * have been set - so disable allow_anonymous */ config->security_options.allow_anonymous = false; }else{ /* Default option if no security options set */ config->security_options.allow_anonymous = true; } } } #ifdef WITH_PERSISTENCE if(config->persistence){ if(!config->persistence_file){ config->persistence_file = mosquitto__strdup("mosquitto.db"); if(!config->persistence_file) return MOSQ_ERR_NOMEM; } mosquitto__free(config->persistence_filepath); if(config->persistence_location && strlen(config->persistence_location)){ len = strlen(config->persistence_location) + strlen(config->persistence_file) + 1; config->persistence_filepath = mosquitto__malloc(len); if(!config->persistence_filepath) return MOSQ_ERR_NOMEM; snprintf(config->persistence_filepath, len, "%s%s", config->persistence_location, config->persistence_file); }else{ config->persistence_filepath = mosquitto__strdup(config->persistence_file); if(!config->persistence_filepath) return MOSQ_ERR_NOMEM; } } #endif /* Default to drop to mosquitto user if no other user specified. This must * remain here even though it is covered in config__parse_args() because this * function may be called on its own. */ if(!config->user){ config->user = "mosquitto"; } db__limits_set(cr.max_inflight_messages, cr.max_inflight_bytes, cr.max_queued_messages, cr.max_queued_bytes); #ifdef WITH_BRIDGE for(i=0; i<config->bridge_count; i++){ if(!config->bridges[i].name || !config->bridges[i].addresses || !config->bridges[i].topic_count){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef WITH_TLS_PSK if(config->bridges[i].tls_psk && !config->bridges[i].tls_psk_identity){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration: missing bridge_identity.\n"); return MOSQ_ERR_INVAL; } if(config->bridges[i].tls_psk_identity && !config->bridges[i].tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration: missing bridge_psk.\n"); return MOSQ_ERR_INVAL; } #endif } #endif if(cr.log_dest_set){ config->log_dest = cr.log_dest; } if(db->verbose){ config->log_type = INT_MAX; }else if(cr.log_type_set){ config->log_type = cr.log_type; } return MOSQ_ERR_SUCCESS; } int config__read_file_core(struct mosquitto__config *config, bool reload, struct config_recurse *cr, int level, int *lineno, FILE *fptr, char **buf, int *buflen) { int rc; char *token; int tmp_int; char *saveptr = NULL; #ifdef WITH_BRIDGE char *tmp_char; struct mosquitto__bridge *cur_bridge = NULL; struct mosquitto__bridge_topic *cur_topic; #endif struct mosquitto__auth_plugin_config *cur_auth_plugin_config = NULL; time_t expiration_mult; char *key; char *conf_file; #ifdef WIN32 HANDLE fh; char dirpath[MAX_PATH]; WIN32_FIND_DATA find_data; #else DIR *dh; struct dirent *de; #endif int len; struct mosquitto__listener *cur_listener = &config->default_listener; int i; int lineno_ext; struct mosquitto__security_options *cur_security_options = NULL; *lineno = 0; while(fgets_extending(buf, buflen, fptr)){ (*lineno)++; if((*buf)[0] != '#' && (*buf)[0] != 10 && (*buf)[0] != 13){ while((*buf)[strlen((*buf))-1] == 10 || (*buf)[strlen((*buf))-1] == 13){ (*buf)[strlen((*buf))-1] = 0; } token = strtok_r((*buf), " ", &saveptr); if(token){ if(!strcmp(token, "acl_file")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(reload){ mosquitto__free(cur_security_options->acl_file); cur_security_options->acl_file = NULL; } if(conf__parse_string(&token, "acl_file", &cur_security_options->acl_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "address") || !strcmp(token, "addresses")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge || cur_bridge->addresses){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } while((token = strtok_r(NULL, " ", &saveptr))){ cur_bridge->address_count++; cur_bridge->addresses = mosquitto__realloc(cur_bridge->addresses, sizeof(struct bridge_address)*cur_bridge->address_count); if(!cur_bridge->addresses){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_bridge->addresses[cur_bridge->address_count-1].address = token; } for(i=0; i<cur_bridge->address_count; i++){ /* cur_bridge->addresses[i].address is now * "address[:port]". If address is an IPv6 address, * then port is required. We must check for the : * backwards. */ tmp_char = strrchr(cur_bridge->addresses[i].address, ':'); if(tmp_char){ /* Remove ':', so cur_bridge->addresses[i].address * now just looks like the address. */ tmp_char[0] = '\0'; /* The remainder of the string */ tmp_int = atoi(&tmp_char[1]); if(tmp_int < 1 || tmp_int > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } cur_bridge->addresses[i].port = tmp_int; }else{ cur_bridge->addresses[i].port = 1883; } /* This looks a bit weird, but isn't. Before this * call, cur_bridge->addresses[i].address points * to the tokenised part of the line, it will be * reused in a future parse of a config line so we * must duplicate it. */ cur_bridge->addresses[i].address = mosquitto__strdup(cur_bridge->addresses[i].address); conf__attempt_resolve(cur_bridge->addresses[i].address, "bridge address", MOSQ_LOG_WARNING, "Warning"); } if(cur_bridge->address_count == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty address value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "allow_anonymous")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(conf__parse_bool(&token, "allow_anonymous", (bool *)&cur_security_options->allow_anonymous, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "allow_duplicate_messages")){ if(conf__parse_bool(&token, "allow_duplicate_messages", &config->allow_duplicate_messages, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "allow_zero_length_clientid")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(conf__parse_bool(&token, "allow_zero_length_clientid", &cur_security_options->allow_zero_length_clientid, saveptr)) return MOSQ_ERR_INVAL; }else if(!strncmp(token, "auth_opt_", 9)){ if(reload) continue; // Auth plugin not currently valid for reloading. if(!cur_auth_plugin_config){ log__printf(NULL, MOSQ_LOG_ERR, "Error: An auth_opt_ option exists in the config file without an auth_plugin."); return MOSQ_ERR_INVAL; } if(strlen(token) < 12){ /* auth_opt_ == 9, + one digit key == 10, + one space == 11, + one value == 12 */ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid auth_opt_ config option."); return MOSQ_ERR_INVAL; } key = mosquitto__strdup(&token[9]); if(!key){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; }else if(STREMPTY(key)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid auth_opt_ config option."); mosquitto__free(key); return MOSQ_ERR_INVAL; } token += 9+strlen(key)+1; while(token[0] == ' ' || token[0] == '\t'){ token++; } if(token[0]){ cur_auth_plugin_config->option_count++; cur_auth_plugin_config->options = mosquitto__realloc(cur_auth_plugin_config->options, cur_auth_plugin_config->option_count*sizeof(struct mosquitto_auth_opt)); if(!cur_auth_plugin_config->options){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); mosquitto__free(key); return MOSQ_ERR_NOMEM; } cur_auth_plugin_config->options[cur_auth_plugin_config->option_count-1].key = key; cur_auth_plugin_config->options[cur_auth_plugin_config->option_count-1].value = mosquitto__strdup(token); if(!cur_auth_plugin_config->options[cur_auth_plugin_config->option_count-1].value){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", key); mosquitto__free(key); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "auth_plugin")){ if(reload) continue; // Auth plugin not currently valid for reloading. conf__set_cur_security_options(config, cur_listener, &cur_security_options); cur_security_options->auth_plugin_configs = mosquitto__realloc(cur_security_options->auth_plugin_configs, (cur_security_options->auth_plugin_config_count+1)*sizeof(struct mosquitto__auth_plugin_config)); if(!cur_security_options->auth_plugin_configs){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_auth_plugin_config = &cur_security_options->auth_plugin_configs[cur_security_options->auth_plugin_config_count]; memset(cur_auth_plugin_config, 0, sizeof(struct mosquitto__auth_plugin_config)); cur_auth_plugin_config->path = NULL; cur_auth_plugin_config->options = NULL; cur_auth_plugin_config->option_count = 0; cur_auth_plugin_config->deny_special_chars = true; cur_security_options->auth_plugin_config_count++; if(conf__parse_string(&token, "auth_plugin", &cur_auth_plugin_config->path, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "auth_plugin_deny_special_chars")){ if(reload) continue; // Auth plugin not currently valid for reloading. if(!cur_auth_plugin_config){ log__printf(NULL, MOSQ_LOG_ERR, "Error: An auth_plugin_deny_special_chars option exists in the config file without an auth_plugin."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "auth_plugin_deny_special_chars", &cur_auth_plugin_config->deny_special_chars, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "auto_id_prefix")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(conf__parse_string(&token, "auto_id_prefix", &cur_security_options->auto_id_prefix, saveptr)) return MOSQ_ERR_INVAL; if(cur_security_options->auto_id_prefix){ cur_security_options->auto_id_prefix_len = strlen(cur_security_options->auto_id_prefix); }else{ cur_security_options->auto_id_prefix_len = 0; } }else if(!strcmp(token, "autosave_interval")){ if(conf__parse_int(&token, "autosave_interval", &config->autosave_interval, saveptr)) return MOSQ_ERR_INVAL; if(config->autosave_interval < 0) config->autosave_interval = 0; }else if(!strcmp(token, "autosave_on_changes")){ if(conf__parse_bool(&token, "autosave_on_changes", &config->autosave_on_changes, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "bind_address")){ if(reload) continue; // Listener not valid for reloading. if(conf__parse_string(&token, "default listener bind_address", &config->default_listener.host, saveptr)) return MOSQ_ERR_INVAL; if(conf__attempt_resolve(config->default_listener.host, "bind_address", MOSQ_LOG_ERR, "Error")){ return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "bridge_attempt_unsubscribe")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "bridge_attempt_unsubscribe", &cur_bridge->attempt_unsubscribe, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_cafile")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_cafile", &cur_bridge->tls_cafile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_capath")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_capath", &cur_bridge->tls_capath, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_certfile")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_certfile", &cur_bridge->tls_certfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_identity")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS_PSK) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(cur_bridge->tls_cafile || cur_bridge->tls_capath || cur_bridge->tls_certfile || cur_bridge->tls_keyfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and identity encryption in a single bridge."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge_identity", &cur_bridge->tls_psk_identity, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS-PSK support not available."); #endif }else if(!strcmp(token, "bridge_insecure")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "bridge_insecure", &cur_bridge->tls_insecure, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->tls_insecure){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge %s using insecure mode.", cur_bridge->name); } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS-PSK support not available."); #endif }else if(!strcmp(token, "bridge_keyfile")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } #ifdef WITH_TLS_PSK if(cur_bridge->tls_psk_identity || cur_bridge->tls_psk){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } #endif if(conf__parse_string(&token, "bridge_keyfile", &cur_bridge->tls_keyfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "bridge_protocol_version")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, "", &saveptr); if(token){ if(!strcmp(token, "mqttv31")){ cur_bridge->protocol_version = mosq_p_mqtt31; }else if(!strcmp(token, "mqttv311")){ cur_bridge->protocol_version = mosq_p_mqtt311; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge_protocol_version value (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty bridge_protocol_version value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "bridge_psk")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS_PSK) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(cur_bridge->tls_cafile || cur_bridge->tls_capath || cur_bridge->tls_certfile || cur_bridge->tls_keyfile){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single bridge."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge_psk", &cur_bridge->tls_psk, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS-PSK support not available."); #endif }else if(!strcmp(token, "bridge_tls_version")){ #if defined(WITH_BRIDGE) && defined(WITH_TLS) if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge_tls_version", &cur_bridge->tls_version, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge and/or TLS support not available."); #endif }else if(!strcmp(token, "cafile")){ #if defined(WITH_TLS) if(reload) continue; // Listeners not valid for reloading. if(cur_listener->psk_hint){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single listener."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "cafile", &cur_listener->cafile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "capath")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "capath", &cur_listener->capath, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "certfile")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(cur_listener->psk_hint){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot use both certificate and psk encryption in a single listener."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "certfile", &cur_listener->certfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "ciphers")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "ciphers", &cur_listener->ciphers, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "clientid") || !strcmp(token, "remote_clientid")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge remote clientid", &cur_bridge->remote_clientid, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "cleansession")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "cleansession", &cur_bridge->clean_session, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "clientid_prefixes")){ if(reload){ mosquitto__free(config->clientid_prefixes); config->clientid_prefixes = NULL; } if(conf__parse_string(&token, "clientid_prefixes", &config->clientid_prefixes, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "connection")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME token = strtok_r(NULL, " ", &saveptr); if(token){ /* Check for existing bridge name. */ for(i=0; i<config->bridge_count; i++){ if(!strcmp(config->bridges[i].name, token)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate bridge name \"%s\".", token); return MOSQ_ERR_INVAL; } } config->bridge_count++; config->bridges = mosquitto__realloc(config->bridges, config->bridge_count*sizeof(struct mosquitto__bridge)); if(!config->bridges){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_bridge = &(config->bridges[config->bridge_count-1]); memset(cur_bridge, 0, sizeof(struct mosquitto__bridge)); cur_bridge->name = mosquitto__strdup(token); if(!cur_bridge->name){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_bridge->keepalive = 60; cur_bridge->notifications = true; cur_bridge->notifications_local_only = false; cur_bridge->start_type = bst_automatic; cur_bridge->idle_timeout = 60; cur_bridge->restart_timeout = 30; cur_bridge->threshold = 10; cur_bridge->try_private = true; cur_bridge->attempt_unsubscribe = true; cur_bridge->protocol_version = mosq_p_mqtt311; cur_bridge->primary_retry_sock = INVALID_SOCKET; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty connection value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "connection_messages")){ if(conf__parse_bool(&token, token, &config->connection_messages, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "crlfile")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "crlfile", &cur_listener->crlfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "http_dir")){ #ifdef WITH_WEBSOCKETS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "http_dir", &cur_listener->http_dir, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Websockets support not available."); #endif }else if(!strcmp(token, "idle_timeout")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_int(&token, "idle_timeout", &cur_bridge->idle_timeout, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->idle_timeout < 1){ log__printf(NULL, MOSQ_LOG_NOTICE, "idle_timeout interval too low, using 1 second."); cur_bridge->idle_timeout = 1; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "include_dir")){ if(level == 0){ /* Only process include_dir from the main config file. */ token = strtok_r(NULL, "", &saveptr); if(!token){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty include_dir value in configuration."); return 1; } #ifdef WIN32 snprintf(dirpath, MAX_PATH, "%s\\*.conf", token); fh = FindFirstFile(dirpath, &find_data); if(fh == INVALID_HANDLE_VALUE){ /* No files found */ continue; } do{ len = strlen(token)+1+strlen(find_data.cFileName)+1; conf_file = mosquitto__malloc(len+1); if(!conf_file){ FindClose(fh); return MOSQ_ERR_NOMEM; } snprintf(conf_file, len, "%s\\%s", token, find_data.cFileName); conf_file[len] = '\0'; rc = config__read_file(config, reload, conf_file, cr, level+1, &lineno_ext); if(rc){ FindClose(fh); log__printf(NULL, MOSQ_LOG_ERR, "Error found at %s:%d.", conf_file, lineno_ext); mosquitto__free(conf_file); return rc; } mosquitto__free(conf_file); }while(FindNextFile(fh, &find_data)); FindClose(fh); #else dh = opendir(token); if(!dh){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open include_dir '%s'.", token); return 1; } while((de = readdir(dh)) != NULL){ if(strlen(de->d_name) > 5){ if(!strcmp(&de->d_name[strlen(de->d_name)-5], ".conf")){ len = strlen(token)+1+strlen(de->d_name)+1; conf_file = mosquitto__malloc(len+1); if(!conf_file){ closedir(dh); return MOSQ_ERR_NOMEM; } snprintf(conf_file, len, "%s/%s", token, de->d_name); conf_file[len] = '\0'; rc = config__read_file(config, reload, conf_file, cr, level+1, &lineno_ext); if(rc){ closedir(dh); log__printf(NULL, MOSQ_LOG_ERR, "Error found at %s:%d.", conf_file, lineno_ext); mosquitto__free(conf_file); return rc; } mosquitto__free(conf_file); } } } closedir(dh); #endif } }else if(!strcmp(token, "keepalive_interval")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_int(&token, "keepalive_interval", &cur_bridge->keepalive, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->keepalive < 5){ log__printf(NULL, MOSQ_LOG_NOTICE, "keepalive interval too low, using 5 seconds."); cur_bridge->keepalive = 5; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "keyfile")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "keyfile", &cur_listener->keyfile, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "listener")){ token = strtok_r(NULL, " ", &saveptr); if(token){ tmp_int = atoi(token); if(tmp_int < 1 || tmp_int > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } if(reload){ /* We reload listeners settings based on port number. * If the port number doesn't already exist, exit with a complaint. */ cur_listener = NULL; for(i=0; i<config->listener_count; i++){ if(config->listeners[i].port == tmp_int){ cur_listener = &config->listeners[i]; } } if(!cur_listener){ log__printf(NULL, MOSQ_LOG_ERR, "Error: It is not currently possible to add/remove listeners when reloading the config file."); return MOSQ_ERR_INVAL; } }else{ config->listener_count++; config->listeners = mosquitto__realloc(config->listeners, sizeof(struct mosquitto__listener)*config->listener_count); if(!config->listeners){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_listener = &config->listeners[config->listener_count-1]; memset(cur_listener, 0, sizeof(struct mosquitto__listener)); } cur_listener->security_options.allow_anonymous = -1; cur_listener->protocol = mp_mqtt; cur_listener->port = tmp_int; token = strtok_r(NULL, "", &saveptr); mosquitto__free(cur_listener->host); if(token){ cur_listener->host = mosquitto__strdup(token); }else{ cur_listener->host = NULL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty listener value in configuration."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "local_clientid")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge local clientd", &cur_bridge->local_clientid, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "local_password")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge local_password", &cur_bridge->local_password, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "local_username")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge local_username", &cur_bridge->local_username, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "log_dest")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->log_dest_set = 1; if(!strcmp(token, "none")){ cr->log_dest = MQTT3_LOG_NONE; }else if(!strcmp(token, "syslog")){ cr->log_dest |= MQTT3_LOG_SYSLOG; }else if(!strcmp(token, "stdout")){ cr->log_dest |= MQTT3_LOG_STDOUT; }else if(!strcmp(token, "stderr")){ cr->log_dest |= MQTT3_LOG_STDERR; }else if(!strcmp(token, "topic")){ cr->log_dest |= MQTT3_LOG_TOPIC; }else if(!strcmp(token, "file")){ cr->log_dest |= MQTT3_LOG_FILE; if(config->log_fptr || config->log_file){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate \"log_dest file\" value."); return MOSQ_ERR_INVAL; } /* Get remaining string. */ token = &token[strlen(token)+1]; while(token[0] == ' ' || token[0] == '\t'){ token++; } if(token[0]){ config->log_file = mosquitto__strdup(token); if(!config->log_file){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty \"log_dest file\" value in configuration."); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid log_dest value (%s).", token); return MOSQ_ERR_INVAL; } #if defined(WIN32) || defined(__CYGWIN__) if(service_handle){ if(cr->log_dest == MQTT3_LOG_STDOUT || cr->log_dest == MQTT3_LOG_STDERR){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Cannot log to stdout/stderr when running as a Windows service."); return MOSQ_ERR_INVAL; } } #endif }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty log_dest value in configuration."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "log_facility")){ #if defined(WIN32) || defined(__CYGWIN__) log__printf(NULL, MOSQ_LOG_WARNING, "Warning: log_facility not supported on Windows."); #else if(conf__parse_int(&token, "log_facility", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; switch(tmp_int){ case 0: config->log_facility = LOG_LOCAL0; break; case 1: config->log_facility = LOG_LOCAL1; break; case 2: config->log_facility = LOG_LOCAL2; break; case 3: config->log_facility = LOG_LOCAL3; break; case 4: config->log_facility = LOG_LOCAL4; break; case 5: config->log_facility = LOG_LOCAL5; break; case 6: config->log_facility = LOG_LOCAL6; break; case 7: config->log_facility = LOG_LOCAL7; break; default: log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid log_facility value (%d).", tmp_int); return MOSQ_ERR_INVAL; } #endif }else if(!strcmp(token, "log_timestamp")){ if(conf__parse_bool(&token, token, &config->log_timestamp, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "log_type")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->log_type_set = 1; if(!strcmp(token, "none")){ cr->log_type = MOSQ_LOG_NONE; }else if(!strcmp(token, "information")){ cr->log_type |= MOSQ_LOG_INFO; }else if(!strcmp(token, "notice")){ cr->log_type |= MOSQ_LOG_NOTICE; }else if(!strcmp(token, "warning")){ cr->log_type |= MOSQ_LOG_WARNING; }else if(!strcmp(token, "error")){ cr->log_type |= MOSQ_LOG_ERR; }else if(!strcmp(token, "debug")){ cr->log_type |= MOSQ_LOG_DEBUG; }else if(!strcmp(token, "subscribe")){ cr->log_type |= MOSQ_LOG_SUBSCRIBE; }else if(!strcmp(token, "unsubscribe")){ cr->log_type |= MOSQ_LOG_UNSUBSCRIBE; #ifdef WITH_WEBSOCKETS }else if(!strcmp(token, "websockets")){ cr->log_type |= MOSQ_LOG_WEBSOCKETS; #endif }else if(!strcmp(token, "all")){ cr->log_type = INT_MAX; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid log_type value (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty log_type value in configuration."); } }else if(!strcmp(token, "max_connections")){ if(reload) continue; // Listeners not valid for reloading. token = strtok_r(NULL, " ", &saveptr); if(token){ cur_listener->max_connections = atoi(token); if(cur_listener->max_connections < 0) cur_listener->max_connections = -1; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_connections value in configuration."); } }else if(!strcmp(token, "max_inflight_bytes")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->max_inflight_bytes = atol(token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_inflight_bytes value in configuration."); } }else if(!strcmp(token, "max_inflight_messages")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->max_inflight_messages = atoi(token); if(cr->max_inflight_messages < 0) cr->max_inflight_messages = 0; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_inflight_messages value in configuration."); } }else if(!strcmp(token, "max_queued_bytes")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->max_queued_bytes = atol(token); /* 63 bits is ok right? */ }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_queued_bytes value in configuration."); } }else if(!strcmp(token, "max_queued_messages")){ token = strtok_r(NULL, " ", &saveptr); if(token){ cr->max_queued_messages = atoi(token); if(cr->max_queued_messages < 0) cr->max_queued_messages = 0; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty max_queued_messages value in configuration."); } }else if(!strcmp(token, "memory_limit")){ ssize_t lim; if(conf__parse_ssize_t(&token, "memory_limit", &lim, saveptr)) return MOSQ_ERR_INVAL; if(lim < 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid memory_limit value (%ld).", lim); return MOSQ_ERR_INVAL; } memory__set_limit(lim); }else if(!strcmp(token, "message_size_limit")){ if(conf__parse_int(&token, "message_size_limit", (int *)&config->message_size_limit, saveptr)) return MOSQ_ERR_INVAL; if(config->message_size_limit > MQTT_MAX_PAYLOAD){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid message_size_limit value (%u).", config->message_size_limit); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "mount_point")){ if(reload) continue; // Listeners not valid for reloading. if(config->listener_count == 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: You must use create a listener before using the mount_point option in the configuration file."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "mount_point", &cur_listener->mount_point, saveptr)) return MOSQ_ERR_INVAL; if(mosquitto_pub_topic_check(cur_listener->mount_point) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid mount_point '%s'. Does it contain a wildcard character?", cur_listener->mount_point); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "notifications")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "notifications", &cur_bridge->notifications, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "notifications_local_only")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration"); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "notifications_local_only", &cur_bridge->notifications_local_only, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "notification_topic")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "notification_topic", &cur_bridge->notification_topic, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "password") || !strcmp(token, "remote_password")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_string(&token, "bridge remote_password", &cur_bridge->remote_password, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "password_file")){ conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(reload){ mosquitto__free(cur_security_options->password_file); cur_security_options->password_file = NULL; } if(conf__parse_string(&token, "password_file", &cur_security_options->password_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "per_listener_settings")){ if(conf__parse_bool(&token, "per_listener_settings", &config->per_listener_settings, saveptr)) return MOSQ_ERR_INVAL; if(cur_security_options && config->per_listener_settings){ log__printf(NULL, MOSQ_LOG_ERR, "Error: per_listener_settings must be set before any other security settings."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "persistence") || !strcmp(token, "retained_persistence")){ if(conf__parse_bool(&token, token, &config->persistence, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "persistence_file")){ if(conf__parse_string(&token, "persistence_file", &config->persistence_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "persistence_location")){ if(conf__parse_string(&token, "persistence_location", &config->persistence_location, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "persistent_client_expiration")){ token = strtok_r(NULL, " ", &saveptr); if(token){ switch(token[strlen(token)-1]){ case 'h': expiration_mult = 3600; break; case 'd': expiration_mult = 86400; break; case 'w': expiration_mult = 86400*7; break; case 'm': expiration_mult = 86400*30; break; case 'y': expiration_mult = 86400*365; break; default: log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid persistent_client_expiration duration in configuration."); return MOSQ_ERR_INVAL; } token[strlen(token)-1] = '\0'; config->persistent_client_expiration = atoi(token)*expiration_mult; if(config->persistent_client_expiration <= 0){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid persistent_client_expiration duration in configuration."); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty persistent_client_expiration value in configuration."); } }else if(!strcmp(token, "pid_file")){ if(reload) continue; // pid file not valid for reloading. if(conf__parse_string(&token, "pid_file", &config->pid_file, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "port")){ if(reload) continue; // Listener not valid for reloading. if(config->default_listener.port){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Default listener port specified multiple times. Only the latest will be used."); } if(conf__parse_int(&token, "port", &tmp_int, saveptr)) return MOSQ_ERR_INVAL; if(tmp_int < 1 || tmp_int > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port value (%d).", tmp_int); return MOSQ_ERR_INVAL; } config->default_listener.port = tmp_int; }else if(!strcmp(token, "protocol")){ token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "mqtt")){ cur_listener->protocol = mp_mqtt; /* }else if(!strcmp(token, "mqttsn")){ cur_listener->protocol = mp_mqttsn; */ }else if(!strcmp(token, "websockets")){ #ifdef WITH_WEBSOCKETS cur_listener->protocol = mp_websockets; config->have_websockets_listener = true; #else log__printf(NULL, MOSQ_LOG_ERR, "Error: Websockets support not available."); return MOSQ_ERR_INVAL; #endif }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid protocol value (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty protocol value in configuration."); } }else if(!strcmp(token, "psk_file")){ #ifdef WITH_TLS_PSK conf__set_cur_security_options(config, cur_listener, &cur_security_options); if(reload){ mosquitto__free(cur_security_options->psk_file); cur_security_options->psk_file = NULL; } if(conf__parse_string(&token, "psk_file", &cur_security_options->psk_file, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS/TLS-PSK support not available."); #endif }else if(!strcmp(token, "psk_hint")){ #ifdef WITH_TLS_PSK if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "psk_hint", &cur_listener->psk_hint, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS/TLS-PSK support not available."); #endif }else if(!strcmp(token, "queue_qos0_messages")){ if(conf__parse_bool(&token, token, &config->queue_qos0_messages, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "require_certificate")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "require_certificate", &cur_listener->require_certificate, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "restart_timeout")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_int(&token, "restart_timeout", &cur_bridge->restart_timeout, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->restart_timeout < 1){ log__printf(NULL, MOSQ_LOG_NOTICE, "restart_timeout interval too low, using 1 second."); cur_bridge->restart_timeout = 1; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "retry_interval")){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: The retry_interval option is no longer available."); }else if(!strcmp(token, "round_robin")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "round_robin", &cur_bridge->round_robin, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "set_tcp_nodelay")){ if(conf__parse_bool(&token, "set_tcp_nodelay", &config->set_tcp_nodelay, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "start_type")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "automatic")){ cur_bridge->start_type = bst_automatic; }else if(!strcmp(token, "lazy")){ cur_bridge->start_type = bst_lazy; }else if(!strcmp(token, "manual")){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Manual start_type not supported."); return MOSQ_ERR_INVAL; }else if(!strcmp(token, "once")){ cur_bridge->start_type = bst_once; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid start_type value in configuration (%s).", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty start_type value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "socket_domain")){ if(reload) continue; // Listeners not valid for reloading. token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "ipv4")){ cur_listener->socket_domain = AF_INET; }else if(!strcmp(token, "ipv6")){ cur_listener->socket_domain = AF_INET6; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid socket_domain value \"%s\" in configuration.", token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty socket_domain value in configuration."); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "store_clean_interval")){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: store_clean_interval is no longer needed."); }else if(!strcmp(token, "sys_interval")){ if(conf__parse_int(&token, "sys_interval", &config->sys_interval, saveptr)) return MOSQ_ERR_INVAL; if(config->sys_interval < 0 || config->sys_interval > 65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid sys_interval value (%d).", config->sys_interval); return MOSQ_ERR_INVAL; } }else if(!strcmp(token, "threshold")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_int(&token, "threshold", &cur_bridge->threshold, saveptr)) return MOSQ_ERR_INVAL; if(cur_bridge->threshold < 1){ log__printf(NULL, MOSQ_LOG_NOTICE, "threshold too low, using 1 message."); cur_bridge->threshold = 1; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "tls_version")){ #if defined(WITH_TLS) if(reload) continue; // Listeners not valid for reloading. if(conf__parse_string(&token, "tls_version", &cur_listener->tls_version, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "topic")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ cur_bridge->topic_count++; cur_bridge->topics = mosquitto__realloc(cur_bridge->topics, sizeof(struct mosquitto__bridge_topic)*cur_bridge->topic_count); if(!cur_bridge->topics){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } cur_topic = &cur_bridge->topics[cur_bridge->topic_count-1]; if(!strcmp(token, "\"\"")){ cur_topic->topic = NULL; }else{ cur_topic->topic = mosquitto__strdup(token); if(!cur_topic->topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } cur_topic->direction = bd_out; cur_topic->qos = 0; cur_topic->local_prefix = NULL; cur_topic->remote_prefix = NULL; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty topic value in configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcasecmp(token, "out")){ cur_topic->direction = bd_out; }else if(!strcasecmp(token, "in")){ cur_topic->direction = bd_in; }else if(!strcasecmp(token, "both")){ cur_topic->direction = bd_both; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic direction '%s'.", token); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ cur_topic->qos = atoi(token); if(cur_topic->qos < 0 || cur_topic->qos > 2){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge QoS level '%s'.", token); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ cur_bridge->topic_remapping = true; if(!strcmp(token, "\"\"")){ cur_topic->local_prefix = NULL; }else{ if(mosquitto_pub_topic_check(token) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic local prefix '%s'.", token); return MOSQ_ERR_INVAL; } cur_topic->local_prefix = mosquitto__strdup(token); if(!cur_topic->local_prefix){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } token = strtok_r(NULL, " ", &saveptr); if(token){ if(!strcmp(token, "\"\"")){ cur_topic->remote_prefix = NULL; }else{ if(mosquitto_pub_topic_check(token) != MOSQ_ERR_SUCCESS){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge topic remote prefix '%s'.", token); return MOSQ_ERR_INVAL; } cur_topic->remote_prefix = mosquitto__strdup(token); if(!cur_topic->remote_prefix){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } } } } } if(cur_topic->topic == NULL && (cur_topic->local_prefix == NULL || cur_topic->remote_prefix == NULL)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge remapping."); return MOSQ_ERR_INVAL; } if(cur_topic->local_prefix){ if(cur_topic->topic){ len = strlen(cur_topic->topic) + strlen(cur_topic->local_prefix)+1; cur_topic->local_topic = mosquitto__malloc(len+1); if(!cur_topic->local_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } snprintf(cur_topic->local_topic, len+1, "%s%s", cur_topic->local_prefix, cur_topic->topic); cur_topic->local_topic[len] = '\0'; }else{ cur_topic->local_topic = mosquitto__strdup(cur_topic->local_prefix); if(!cur_topic->local_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } }else{ cur_topic->local_topic = mosquitto__strdup(cur_topic->topic); if(!cur_topic->local_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } if(cur_topic->remote_prefix){ if(cur_topic->topic){ len = strlen(cur_topic->topic) + strlen(cur_topic->remote_prefix)+1; cur_topic->remote_topic = mosquitto__malloc(len+1); if(!cur_topic->remote_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } snprintf(cur_topic->remote_topic, len, "%s%s", cur_topic->remote_prefix, cur_topic->topic); cur_topic->remote_topic[len] = '\0'; }else{ cur_topic->remote_topic = mosquitto__strdup(cur_topic->remote_prefix); if(!cur_topic->remote_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } }else{ cur_topic->remote_topic = mosquitto__strdup(cur_topic->topic); if(!cur_topic->remote_topic){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "try_private")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } if(conf__parse_bool(&token, "try_private", &cur_bridge->try_private, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "upgrade_outgoing_qos")){ if(conf__parse_bool(&token, token, &config->upgrade_outgoing_qos, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "use_identity_as_username")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "use_identity_as_username", &cur_listener->use_identity_as_username, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "use_subject_as_username")){ #ifdef WITH_TLS if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "use_subject_as_username", &cur_listener->use_subject_as_username, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: TLS support not available."); #endif }else if(!strcmp(token, "user")){ if(reload) continue; // Drop privileges user not valid for reloading. if(conf__parse_string(&token, "user", &config->user, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "use_username_as_clientid")){ if(reload) continue; // Listeners not valid for reloading. if(conf__parse_bool(&token, "use_username_as_clientid", &cur_listener->use_username_as_clientid, saveptr)) return MOSQ_ERR_INVAL; }else if(!strcmp(token, "username") || !strcmp(token, "remote_username")){ #ifdef WITH_BRIDGE if(reload) continue; // FIXME if(!cur_bridge){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid bridge configuration."); return MOSQ_ERR_INVAL; } token = strtok_r(NULL, " ", &saveptr); if(token){ if(cur_bridge->remote_username){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate username value in bridge configuration."); return MOSQ_ERR_INVAL; } cur_bridge->remote_username = mosquitto__strdup(token); if(!cur_bridge->remote_username){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty username value in configuration."); return MOSQ_ERR_INVAL; } #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Bridge support not available."); #endif }else if(!strcmp(token, "websockets_log_level")){ #ifdef WITH_WEBSOCKETS if(conf__parse_int(&token, "websockets_log_level", &config->websockets_log_level, saveptr)) return MOSQ_ERR_INVAL; #else log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Websockets support not available."); #endif }else if(!strcmp(token, "trace_level") || !strcmp(token, "ffdc_output") || !strcmp(token, "max_log_entries") || !strcmp(token, "trace_output")){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Unsupported rsmb configuration option \"%s\".", token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unknown configuration variable \"%s\".", token); return MOSQ_ERR_INVAL; } } } } return MOSQ_ERR_SUCCESS; } int config__read_file(struct mosquitto__config *config, bool reload, const char *file, struct config_recurse *cr, int level, int *lineno) { int rc; FILE *fptr = NULL; char *buf; int buflen; fptr = mosquitto__fopen(file, "rt", false); if(!fptr){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open config file %s\n", file); return 1; } buflen = 1000; buf = mosquitto__malloc(buflen); if(!buf){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); fclose(fptr); return MOSQ_ERR_NOMEM; } rc = config__read_file_core(config, reload, cr, level, lineno, fptr, &buf, &buflen); mosquitto__free(buf); fclose(fptr); return rc; } static int config__check(struct mosquitto__config *config) { /* Checks that are easy to make after the config has been loaded. */ #ifdef WITH_BRIDGE int i, j; struct mosquitto__bridge *bridge1, *bridge2; char hostname[256]; int len; /* Check for bridge duplicate local_clientid, need to generate missing IDs * first. */ for(i=0; i<config->bridge_count; i++){ bridge1 = &config->bridges[i]; if(!bridge1->remote_clientid){ if(!gethostname(hostname, 256)){ len = strlen(hostname) + strlen(bridge1->name) + 2; bridge1->remote_clientid = mosquitto__malloc(len); if(!bridge1->remote_clientid){ return MOSQ_ERR_NOMEM; } snprintf(bridge1->remote_clientid, len, "%s.%s", hostname, bridge1->name); }else{ return 1; } } if(!bridge1->local_clientid){ len = strlen(bridge1->remote_clientid) + strlen("local.") + 2; bridge1->local_clientid = mosquitto__malloc(len); if(!bridge1->local_clientid){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } snprintf(bridge1->local_clientid, len, "local.%s", bridge1->remote_clientid); } } for(i=0; i<config->bridge_count; i++){ bridge1 = &config->bridges[i]; for(j=i+1; j<config->bridge_count; j++){ bridge2 = &config->bridges[j]; if(!strcmp(bridge1->local_clientid, bridge2->local_clientid)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Bridge local_clientid " "'%s' is not unique. Try changing or setting the " "local_clientid value for one of the bridges.", bridge1->local_clientid); return MOSQ_ERR_INVAL; } } } #endif return MOSQ_ERR_SUCCESS; } static int conf__parse_bool(char **token, const char *name, bool *value, char *saveptr) { *token = strtok_r(NULL, " ", &saveptr); if(*token){ if(!strcmp(*token, "false") || !strcmp(*token, "0")){ *value = false; }else if(!strcmp(*token, "true") || !strcmp(*token, "1")){ *value = true; }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid %s value (%s).", name, *token); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static int conf__parse_int(char **token, const char *name, int *value, char *saveptr) { *token = strtok_r(NULL, " ", &saveptr); if(*token){ *value = atoi(*token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static int conf__parse_ssize_t(char **token, const char *name, ssize_t *value, char *saveptr) { *token = strtok_r(NULL, " ", &saveptr); if(*token){ *value = atol(*token); }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; } static int conf__parse_string(char **token, const char *name, char **value, char *saveptr) { *token = strtok_r(NULL, "", &saveptr); if(*token){ if(*value){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Duplicate %s value in configuration.", name); return MOSQ_ERR_INVAL; } /* Deal with multiple spaces at the beginning of the string. */ while((*token)[0] == ' ' || (*token)[0] == '\t'){ (*token)++; } if(mosquitto_validate_utf8(*token, strlen(*token))){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Malformed UTF-8 in configuration."); return MOSQ_ERR_INVAL; } *value = mosquitto__strdup(*token); if(!*value){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: Empty %s value in configuration.", name); return MOSQ_ERR_INVAL; } return MOSQ_ERR_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-254/c/bad_480_1
crossvul-cpp_data_good_5205_1
/** @file packetParser.c @brief functions to parse and generate a ZRTP packet @author Johan Pascal @copyright Copyright (C) 2014 Belledonne Communications, Grenoble, France 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdlib.h> #include <string.h> #include "typedef.h" #include "packetParser.h" #include <bctoolbox/crypto.h> #include "cryptoUtils.h" /* DEBUG */ #include <stdio.h> /* minimum length of a ZRTP packet: 12 bytes header + 12 bytes message(shortest are ACK messages) + 4 bytes CRC */ #define ZRTP_MIN_PACKET_LENGTH 28 /* maximum length of a ZRTP packet: 3072 bytes get it from GNU-ZRTP CPP code */ #define ZRTP_MAX_PACKET_LENGTH 3072 /* header of ZRTP message is 12 bytes : Preambule/Message Length + Message Type(2 words) */ #define ZRTP_MESSAGE_HEADER_LENGTH 12 /* length of the non optional and fixed part of all messages, in bytes */ #define ZRTP_HELLOMESSAGE_FIXED_LENGTH 88 #define ZRTP_HELLOACKMESSAGE_FIXED_LENGTH 12 #define ZRTP_COMMITMESSAGE_FIXED_LENGTH 84 #define ZRTP_DHPARTMESSAGE_FIXED_LENGTH 84 #define ZRTP_CONFIRMMESSAGE_FIXED_LENGTH 76 #define ZRTP_CONF2ACKMESSAGE_FIXED_LENGTH 12 #define ZRTP_ERRORMESSAGE_FIXED_LENGTH 16 #define ZRTP_ERRORACKMESSAGE_FIXED_LENGTH 12 #define ZRTP_GOCLEARMESSAGE_FIXED_LENGTH 20 #define ZRTP_CLEARACKMESSAGE_FIXED_LENGTH 12 #define ZRTP_SASRELAYMESSAGE_FIXED_LENGTH 76 #define ZRTP_RELAYACKMESSAGE_FIXED_LENGTH 12 #define ZRTP_PINGMESSAGE_FIXED_LENGTH 24 #define ZRTP_PINGACKMESSAGE_FIXED_LENGTH 36 /*** local functions prototypes ***/ /** * Return the variable private value length in bytes according to given key agreement algorythm * * @param[in] keyAgreementAlgo The key agreement algo mapped to an integer as defined in cryptoWrapper.h * * @return the private value length in bytes * */ uint16_t computeKeyAgreementPrivateValueLength(uint8_t keyAgreementAlgo); /** * @brief Retrieve the 8 char string value message type from the int32_t code * * @param[in] messageType The messageType code * * @return an 9 char string : 8 chars message type as specified in rfc section 5.1.1 + string terminating char */ uint8_t *messageTypeInttoString(uint32_t messageType); /** * @brief Map the 8 char string value message type to an int32_t * * @param[in] messageTypeString an 8 bytes string matching a zrtp message type * * @return a 32-bits unsigned integer mapping the message type */ int32_t messageTypeStringtoInt(uint8_t messageTypeString[8]); /** * @brief Write the message header(preambule, length, message type) into the given output buffer * * @param[out] outputBuffer Message starts at the begining of this buffer * @param[in] messageLength Message length in bytes! To be converted into 32bits words before being inserted in the message header * @param[in] messageType An 8 chars string for the message type (validity is not checked by this function) * */ void zrtpMessageSetHeader(uint8_t *outputBuffer, uint16_t messageLength, uint8_t messageType[8]); /*** Public functions implementation ***/ /* First call this function to check packet validity and create the packet structure */ bzrtpPacket_t *bzrtp_packetCheck(const uint8_t * input, uint16_t inputLength, uint16_t lastValidSequenceNumber, int *exitCode) { bzrtpPacket_t *zrtpPacket; uint16_t sequenceNumber; uint32_t packetCRC; uint16_t messageLength; uint32_t messageType; /* first check that the packet is a ZRTP one */ /* is the length compatible with a ZRTP packet */ if ((inputLength<ZRTP_MIN_PACKET_LENGTH) || (inputLength>ZRTP_MAX_PACKET_LENGTH)) { *exitCode = BZRTP_PARSER_ERROR_INVALIDPACKET; return NULL; } /* check ZRTP packet format from rfc section 5 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0 0 0 1|Not Used (set to zero) | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Magic Cookie 'ZRTP' (0x5a525450) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Identifier | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | ZRTP Message (length depends on Message Type) | | . . . | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | CRC (1 word) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+*/ if ((input[0]>>4 != 0x01) || (input[4]!= (uint8_t)((ZRTP_MAGIC_COOKIE>>24)&0xFF)) || (input[5]!= (uint8_t)((ZRTP_MAGIC_COOKIE>>16)&0xFF)) || (input[6]!= (uint8_t)((ZRTP_MAGIC_COOKIE>>8)&0xFF)) || (input[7]!= (uint8_t)(ZRTP_MAGIC_COOKIE&0xFF))) { *exitCode = BZRTP_PARSER_ERROR_INVALIDPACKET; return NULL; } /* Check the sequence number : it must be > to the last valid one (given in parameter) to discard out of order packets * TODO: what if we got a Sequence Number overflowing the 16 bits ? */ sequenceNumber = (((uint16_t)input[2])<<8) | ((uint16_t)input[3]); if (sequenceNumber <= lastValidSequenceNumber) { *exitCode = BZRTP_PARSER_ERROR_OUTOFORDER; return NULL; } /* Check the CRC : The CRC is calculated across the entire ZRTP packet, including the ZRTP header and the ZRTP message, but not including the CRC field.*/ packetCRC = ((((uint32_t)input[inputLength-4])<<24)&0xFF000000) | ((((uint32_t)input[inputLength-3])<<16)&0x00FF0000) | ((((uint32_t)input[inputLength-2])<<8)&0x0000FF00) | (((uint32_t)input[inputLength-1])&0x000000FF); if (bzrtp_CRC32((uint8_t *)input, inputLength - 4) != packetCRC) { *exitCode = BZRTP_PARSER_ERROR_INVALIDCRC; return NULL; } /* check message header : * 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0 1 0 1 0 0 0 0 0 1 0 1 1 0 1 0| length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Message Type Block (2 words) | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+*/ if ((input[ZRTP_PACKET_HEADER_LENGTH]!=0x50) || (input[ZRTP_PACKET_HEADER_LENGTH+1]!=0x5a)) { *exitCode = BZRTP_PARSER_ERROR_INVALIDMESSAGE; return NULL; } /* get the length from the message: it is expressed in 32bits words, convert it to bytes (4*) */ messageLength = 4*(((((uint16_t)input[ZRTP_PACKET_HEADER_LENGTH+2])<<8)&0xFF00) | (((uint16_t)input[ZRTP_PACKET_HEADER_LENGTH+3])&0x00FF)); /* get the message Type */ messageType = messageTypeStringtoInt((uint8_t *)(input+ZRTP_PACKET_HEADER_LENGTH+4)); if (messageType == MSGTYPE_INVALID) { *exitCode = BZRTP_PARSER_ERROR_INVALIDMESSAGE; return NULL; } /* packet and message seems to be valid, so allocate a structure and parse it */ zrtpPacket = (bzrtpPacket_t *)malloc(sizeof(bzrtpPacket_t)); memset(zrtpPacket, 0, sizeof(bzrtpPacket_t)); zrtpPacket->sequenceNumber = sequenceNumber; zrtpPacket->messageLength = messageLength; zrtpPacket->messageType = messageType; zrtpPacket->messageData = NULL; zrtpPacket->packetString = NULL; /* get the SSRC */ zrtpPacket->sourceIdentifier = ((((uint32_t)input[8])<<24)&0xFF000000) | ((((uint32_t)input[9])<<16)&0x00FF0000) | ((((uint32_t)input[10])<<8)&0x0000FF00) | (((uint32_t)input[11])&0x000000FF); *exitCode = 0; return zrtpPacket; } #define MIN(a, b) (((a) < (b)) ? (a) : (b)) /* Call this function after the packetCheck one, to actually parse the packet : create and fill the messageData structure */ int bzrtp_packetParser(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, const uint8_t * input, uint16_t inputLength, bzrtpPacket_t *zrtpPacket) { int i; /* now allocate and fill the correct message structure according to the message type */ /* messageContent points to the begining of the ZRTP message */ uint8_t *messageContent = (uint8_t *)(input+ZRTP_PACKET_HEADER_LENGTH+ZRTP_MESSAGE_HEADER_LENGTH); switch (zrtpPacket->messageType) { case MSGTYPE_HELLO : { /* allocate a Hello message structure */ bzrtpHelloMessage_t *messageData; messageData = (bzrtpHelloMessage_t *)malloc(sizeof(bzrtpHelloMessage_t)); /* fill it */ memcpy(messageData->version, messageContent, 4); messageContent +=4; memcpy(messageData->clientIdentifier, messageContent, 16); messageContent +=16; memcpy(messageData->H3, messageContent, 32); messageContent +=32; memcpy(messageData->ZID, messageContent, 12); messageContent +=12; messageData->S = ((*messageContent)>>6)&0x01; messageData->M = ((*messageContent)>>5)&0x01; messageData->P = ((*messageContent)>>4)&0x01; messageContent +=1; messageData->hc = MIN((*messageContent)&0x0F, 7); messageContent +=1; messageData->cc = MIN(((*messageContent)>>4)&0x0F, 7); messageData->ac = MIN((*messageContent)&0x0F, 7); messageContent +=1; messageData->kc = MIN(((*messageContent)>>4)&0x0F, 7); messageData->sc = MIN((*messageContent)&0x0F, 7); messageContent +=1; /* Check message length according to value in hc, cc, ac, kc and sc */ if (zrtpPacket->messageLength != ZRTP_HELLOMESSAGE_FIXED_LENGTH + 4*((uint16_t)(messageData->hc)+(uint16_t)(messageData->cc)+(uint16_t)(messageData->ac)+(uint16_t)(messageData->kc)+(uint16_t)(messageData->sc))) { free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } /* parse the variable length part: algorithms types */ for (i=0; i<messageData->hc; i++) { messageData->supportedHash[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_HASH_TYPE); messageContent +=4; } for (i=0; i<messageData->cc; i++) { messageData->supportedCipher[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_CIPHERBLOCK_TYPE); messageContent +=4; } for (i=0; i<messageData->ac; i++) { messageData->supportedAuthTag[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_AUTHTAG_TYPE); messageContent +=4; } for (i=0; i<messageData->kc; i++) { messageData->supportedKeyAgreement[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_KEYAGREEMENT_TYPE); messageContent +=4; } for (i=0; i<messageData->sc; i++) { messageData->supportedSas[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_SAS_TYPE); messageContent +=4; } addMandatoryCryptoTypesIfNeeded(ZRTP_HASH_TYPE, messageData->supportedHash, &messageData->hc); addMandatoryCryptoTypesIfNeeded(ZRTP_CIPHERBLOCK_TYPE, messageData->supportedCipher, &messageData->cc); addMandatoryCryptoTypesIfNeeded(ZRTP_AUTHTAG_TYPE, messageData->supportedAuthTag, &messageData->ac); addMandatoryCryptoTypesIfNeeded(ZRTP_KEYAGREEMENT_TYPE, messageData->supportedKeyAgreement, &messageData->kc); addMandatoryCryptoTypesIfNeeded(ZRTP_SAS_TYPE, messageData->supportedSas, &messageData->sc); memcpy(messageData->MAC, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; /* the parsed Hello packet must be saved as it may be used to generate commit message or the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_HELLO */ case MSGTYPE_HELLOACK : { /* check message length */ if (zrtpPacket->messageLength != ZRTP_HELLOACKMESSAGE_FIXED_LENGTH) { return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } } break; /* MSGTYPE_HELLOACK */ case MSGTYPE_COMMIT: { uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; uint16_t variableLength = 0; /* allocate a commit message structure */ bzrtpCommitMessage_t *messageData; messageData = (bzrtpCommitMessage_t *)malloc(sizeof(bzrtpCommitMessage_t)); /* fill the structure */ memcpy(messageData->H2, messageContent, 32); messageContent +=32; /* We have now H2, check it matches the H3 we had in the hello message H3=SHA256(H2) and that the Hello message MAC is correct */ if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this commit shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(H2) */ bctoolbox_sha256(messageData->H2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } memcpy(messageData->ZID, messageContent, 12); messageContent +=12; messageData->hashAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_HASH_TYPE); messageContent += 4; messageData->cipherAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_CIPHERBLOCK_TYPE); messageContent += 4; messageData->authTagAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_AUTHTAG_TYPE); messageContent += 4; messageData->keyAgreementAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_KEYAGREEMENT_TYPE); messageContent += 4; /* commit message length depends on the key agreement type choosen (and set in the zrtpContext->keyAgreementAlgo) */ switch(messageData->keyAgreementAlgo) { case ZRTP_KEYAGREEMENT_DH2k : case ZRTP_KEYAGREEMENT_EC25 : case ZRTP_KEYAGREEMENT_DH3k : case ZRTP_KEYAGREEMENT_EC38 : case ZRTP_KEYAGREEMENT_EC52 : variableLength = 32; /* hvi is 32 bytes length in DH Commit message format */ break; case ZRTP_KEYAGREEMENT_Prsh : variableLength = 24; /* nonce (16 bytes) and keyID(8 bytes) are 24 bytes length in preshared Commit message format */ break; case ZRTP_KEYAGREEMENT_Mult : variableLength = 16; /* nonce is 24 bytes length in multistream Commit message format */ break; default: free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } if (zrtpPacket->messageLength != ZRTP_COMMITMESSAGE_FIXED_LENGTH + variableLength) { free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } messageData->sasAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_SAS_TYPE); messageContent += 4; /* if it is a multistream or preshared commit, get the 16 bytes nonce */ if ((messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) { memcpy(messageData->nonce, messageContent, 16); messageContent +=16; /* and the keyID for preshared commit only */ if (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) { memcpy(messageData->keyID, messageContent, 8); messageContent +=8; } } else { /* it's a DH commit message, get the hvi */ memcpy(messageData->hvi, messageContent, 32); messageContent +=32; } /* get the MAC and attach the message data to the packet structure */ memcpy(messageData->MAC, messageContent, 8); zrtpPacket->messageData = (void *)messageData; /* the parsed commit packet must be saved as it is used to generate the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_COMMIT */ case MSGTYPE_DHPART1 : case MSGTYPE_DHPART2 : { bzrtpDHPartMessage_t *messageData; /*check message length, depends on the selected key agreement algo set in zrtpContext */ uint16_t pvLength = computeKeyAgreementPrivateValueLength(zrtpChannelContext->keyAgreementAlgo); if (pvLength == 0) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } if (zrtpPacket->messageLength != ZRTP_DHPARTMESSAGE_FIXED_LENGTH+pvLength) { return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } /* allocate a DHPart message structure and pv */ messageData = (bzrtpDHPartMessage_t *)malloc(sizeof(bzrtpDHPartMessage_t)); messageData->pv = (uint8_t *)malloc(pvLength*sizeof(uint8_t)); /* fill the structure */ memcpy(messageData->H1, messageContent, 32); messageContent +=32; /* We have now H1, check it matches the H2 we had in the commit message H2=SHA256(H1) and that the Commit message MAC is correct */ if ( zrtpChannelContext->role == RESPONDER) { /* do it only if we are responder (we received a commit packet) */ uint8_t checkH2[32]; uint8_t checkMAC[32]; bzrtpCommitMessage_t *peerCommitMessageData; if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Commit message in this channel, this DHPart2 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageData; /* Check H2 = SHA256(H1) */ bctoolbox_sha256(messageData->H1, 32, 32, checkH2); if (memcmp(checkH2, peerCommitMessageData->H2, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the Commit MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H1, 32, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerCommitMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } /* Check the hvi received in the commit message - RFC section 4.4.1.1*/ /* First compute the expected hvi */ /* hvi = hash(initiator's DHPart2 message(current zrtpPacket)) || responder's Hello message) using the agreed hash function truncated to 256 bits */ /* create a string with the messages concatenated */ { uint8_t computedHvi[32]; uint16_t HelloMessageLength = zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->messageLength; uint16_t DHPartHelloMessageStringLength = zrtpPacket->messageLength + HelloMessageLength; uint8_t *DHPartHelloMessageString = (uint8_t *)malloc(DHPartHelloMessageStringLength*sizeof(uint8_t)); memcpy(DHPartHelloMessageString, input+ZRTP_PACKET_HEADER_LENGTH, zrtpPacket->messageLength); memcpy(DHPartHelloMessageString+zrtpPacket->messageLength, zrtpChannelContext->selfPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, HelloMessageLength); zrtpChannelContext->hashFunction(DHPartHelloMessageString, DHPartHelloMessageStringLength, 32, computedHvi); free(DHPartHelloMessageString); /* Compare computed and received hvi */ if (memcmp(computedHvi, peerCommitMessageData->hvi, 32)!=0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHVI; } } } else { /* if we are initiator(we didn't received any commit message and then no H2), we must check that H3=SHA256(SHA256(H1)) and the Hello message MAC */ uint8_t checkH2[32]; uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this DHPart1 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(SHA256(H1)) */ bctoolbox_sha256(messageData->H1, 32, 32, checkH2); bctoolbox_sha256(checkH2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } memcpy(messageData->rs1ID, messageContent, 8); messageContent +=8; memcpy(messageData->rs2ID, messageContent, 8); messageContent +=8; memcpy(messageData->auxsecretID, messageContent, 8); messageContent +=8; memcpy(messageData->pbxsecretID, messageContent, 8); messageContent +=8; memcpy(messageData->pv, messageContent, pvLength); messageContent +=pvLength; memcpy(messageData->MAC, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; /* the parsed packet must be saved as it is used to generate the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_DHPART1 and MSGTYPE_DHPART2 */ case MSGTYPE_CONFIRM1: case MSGTYPE_CONFIRM2: { uint8_t *confirmMessageKey = NULL; uint8_t *confirmMessageMacKey = NULL; bzrtpConfirmMessage_t *messageData; uint16_t cipherTextLength; uint8_t computedHmac[8]; uint8_t *confirmPlainMessageBuffer; uint8_t *confirmPlainMessage; /* we shall first decrypt and validate the message, check we have the keys to do it */ if (zrtpChannelContext->role == RESPONDER) { /* responder uses initiator's keys to decrypt */ if ((zrtpChannelContext->zrtpkeyi == NULL) || (zrtpChannelContext->mackeyi == NULL)) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyi; confirmMessageMacKey = zrtpChannelContext->mackeyi; } if (zrtpChannelContext->role == INITIATOR) { /* the iniator uses responder's keys to decrypt */ if ((zrtpChannelContext->zrtpkeyr == NULL) || (zrtpChannelContext->mackeyr == NULL)) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyr; confirmMessageMacKey = zrtpChannelContext->mackeyr; } /* allocate a confirm message structure */ messageData = (bzrtpConfirmMessage_t *)malloc(sizeof(bzrtpConfirmMessage_t)); /* get the mac and the IV */ memcpy(messageData->confirm_mac, messageContent, 8); messageContent +=8; memcpy(messageData->CFBIV, messageContent, 16); messageContent +=16; /* get the cipher text length */ cipherTextLength = zrtpPacket->messageLength - ZRTP_MESSAGE_HEADER_LENGTH - 24; /* confirm message is header, confirm_mac(8 bytes), CFB IV(16 bytes), encrypted part */ /* validate the mac over the cipher text */ zrtpChannelContext->hmacFunction(confirmMessageMacKey, zrtpChannelContext->hashLength, messageContent, cipherTextLength, 8, computedHmac); if (memcmp(computedHmac, messageData->confirm_mac, 8) != 0) { /* confirm_mac doesn't match */ free(messageData); return BZRTP_PARSER_ERROR_UNMATCHINGCONFIRMMAC; } /* get plain message */ confirmPlainMessageBuffer = (uint8_t *)malloc(cipherTextLength*sizeof(uint8_t)); zrtpChannelContext->cipherDecryptionFunction(confirmMessageKey, messageData->CFBIV, messageContent, cipherTextLength, confirmPlainMessageBuffer); confirmPlainMessage = confirmPlainMessageBuffer; /* point into the allocated buffer */ /* parse it */ memcpy(messageData->H0, confirmPlainMessage, 32); confirmPlainMessage +=33; /* +33 because next 8 bits are unused */ /* Hash chain checking: if we are in multichannel or shared mode, we had not DHPart and then no H1 */ if (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh || zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult) { /* compute the H1=SHA256(H0) we never received */ uint8_t checkH1[32]; bctoolbox_sha256(messageData->H0, 32, 32, checkH1); /* if we are responder, we received a commit packet with H2 then check that H2=SHA256(H1) and that the commit message MAC keyed with H1 match */ if ( zrtpChannelContext->role == RESPONDER) { uint8_t checkH2[32]; uint8_t checkMAC[32]; bzrtpCommitMessage_t *peerCommitMessageData; if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Commit message in this channel, this Confirm2 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageData; /* Check H2 = SHA256(H1) */ bctoolbox_sha256(checkH1, 32, 32, checkH2); if (memcmp(checkH2, peerCommitMessageData->H2, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the Commit MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH1, 32, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerCommitMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } else { /* if we are initiator(we didn't received any commit message and then no H2), we must check that H3=SHA256(SHA256(H1)) and the Hello message MAC */ uint8_t checkH2[32]; uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this Confirm1 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(SHA256(H1)) */ bctoolbox_sha256(checkH1, 32, 32, checkH2); bctoolbox_sha256(checkH2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } } else { /* we are in DHM mode */ /* We have now H0, check it matches the H1 we had in the DHPart message H1=SHA256(H0) and that the DHPart message MAC is correct */ uint8_t checkH1[32]; uint8_t checkMAC[32]; bzrtpDHPartMessage_t *peerDHPartMessageData; if (zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no DHPART message in this channel, this confirm shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerDHPartMessageData = (bzrtpDHPartMessage_t *)zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageData; /* Check H1 = SHA256(H0) */ bctoolbox_sha256(messageData->H0, 32, 32, checkH1); if (memcmp(checkH1, peerDHPartMessageData->H1, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the DHPart message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H0, 32, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerDHPartMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } messageData->sig_len = ((uint16_t)(confirmPlainMessage[0]&0x01))<<8 | (((uint16_t)confirmPlainMessage[1])&0x00FF); confirmPlainMessage += 2; messageData->E = ((*confirmPlainMessage)&0x08)>>3; messageData->V = ((*confirmPlainMessage)&0x04)>>2; messageData->A = ((*confirmPlainMessage)&0x02)>>1; messageData->D = (*confirmPlainMessage)&0x01; confirmPlainMessage += 1; messageData->cacheExpirationInterval = (((uint32_t)confirmPlainMessage[0])<<24) | (((uint32_t)confirmPlainMessage[1])<<16) | (((uint32_t)confirmPlainMessage[2])<<8) | ((uint32_t)confirmPlainMessage[3]); confirmPlainMessage += 4; /* if sig_len indicate a signature, parse it */ if (messageData->sig_len>0) { memcpy(messageData->signatureBlockType, confirmPlainMessage, 4); confirmPlainMessage += 4; /* allocate memory for the signature block, sig_len is in words(32 bits) and includes the signature block type word */ messageData->signatureBlock = (uint8_t *)malloc(4*(messageData->sig_len-1)*sizeof(uint8_t)); memcpy(messageData->signatureBlock, confirmPlainMessage, 4*(messageData->sig_len-1)); } else { messageData->signatureBlock = NULL; } /* free plain buffer */ free(confirmPlainMessageBuffer); /* the parsed commit packet must be saved as it is used to check correct packet repetition */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; } break; /* MSGTYPE_CONFIRM1 and MSGTYPE_CONFIRM2 */ case MSGTYPE_CONF2ACK: /* nothing to do for this one */ break; /* MSGTYPE_CONF2ACK */ case MSGTYPE_PING: { /* allocate a ping message structure */ bzrtpPingMessage_t *messageData; messageData = (bzrtpPingMessage_t *)malloc(sizeof(bzrtpPingMessage_t)); /* fill the structure */ memcpy(messageData->version, messageContent, 4); messageContent +=4; memcpy(messageData->endpointHash, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; } break; /* MSGTYPE_PING */ } return 0; } /* Create the packet string from the messageData contained into the zrtp Packet structure */ int bzrtp_packetBuild(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, bzrtpPacket_t *zrtpPacket, uint16_t sequenceNumber) { int i; uint8_t *messageTypeString; uint8_t *messageString = NULL; /* will point directly to the begining of the message within the packetString buffer */ uint8_t *MACbuffer = NULL; /* if needed this will point to the beginin of the MAC in the packetString buffer */ /*uint8_t *MACMessageData = NULL; */ /* if needed this will point to the MAC field in the message Data structure */ uint8_t *MACkey = NULL; /* checks */ if (zrtpPacket==NULL) { return BZRTP_BUILDER_ERROR_INVALIDPACKET; } /* get the message type (and check it is valid) */ messageTypeString = messageTypeInttoString(zrtpPacket->messageType); if (messageTypeString == NULL) { return BZRTP_BUILDER_ERROR_INVALIDMESSAGETYPE; } /* create first the message. Header and CRC will be added afterward */ switch (zrtpPacket->messageType) { case MSGTYPE_HELLO : { bzrtpHelloMessage_t *messageData; /* get the Hello message structure */ if (zrtpPacket->messageData == NULL) { return BZRTP_BUILDER_ERROR_INVALIDMESSAGE; } messageData = (bzrtpHelloMessage_t *)zrtpPacket->messageData; /* compute the message length in bytes : fixed length and optionnal algorithms parts */ zrtpPacket->messageLength = ZRTP_HELLOMESSAGE_FIXED_LENGTH + 4*((uint16_t)(messageData->hc)+(uint16_t)(messageData->cc)+(uint16_t)(messageData->ac)+(uint16_t)(messageData->kc)+(uint16_t)(messageData->sc)); /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+zrtpPacket->messageLength+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); /* have the messageString pointer to the begining of message(after the message header wich is computed for all messages after the switch) * within the packetString buffer*/ messageString = zrtpPacket->packetString + ZRTP_PACKET_HEADER_LENGTH + ZRTP_MESSAGE_HEADER_LENGTH; /* set the version (shall be 1.10), Client identifier, H3, ZID, S,M,P flags and hc,cc,ac,kc,sc */ memcpy(messageString, messageData->version, 4); messageString += 4; memcpy(messageString, messageData->clientIdentifier, 16); messageString += 16; memcpy(messageString, messageData->H3, 32); messageString += 32; memcpy(messageString, messageData->ZID, 12); messageString += 12; *messageString = ((((messageData->S)&0x01)<<6) | (((messageData->M)&0x01)<<5) | (((messageData->P)&0x01)<<4))&0x70; messageString += 1; *messageString = (messageData->hc)&0x0F; messageString += 1; *messageString = (((messageData->cc)<<4)&0xF0) | ((messageData->ac)&0x0F) ; messageString += 1; *messageString = (((messageData->kc)<<4)&0xF0) | ((messageData->sc)&0x0F) ; messageString += 1; /* now set optionnal supported algorithms */ for (i=0; i<messageData->hc; i++) { cryptoAlgoTypeIntToString(messageData->supportedHash[i], messageString); messageString +=4; } for (i=0; i<messageData->cc; i++) { cryptoAlgoTypeIntToString(messageData->supportedCipher[i], messageString); messageString +=4; } for (i=0; i<messageData->ac; i++) { cryptoAlgoTypeIntToString(messageData->supportedAuthTag[i], messageString); messageString +=4; } for (i=0; i<messageData->kc; i++) { cryptoAlgoTypeIntToString(messageData->supportedKeyAgreement[i], messageString); messageString +=4; } for (i=0; i<messageData->sc; i++) { cryptoAlgoTypeIntToString(messageData->supportedSas[i], messageString); messageString +=4; } /* there is a MAC to compute, set the pointers to the key and MAC output buffer */ MACbuffer = messageString; MACkey = zrtpChannelContext->selfH[2]; /* HMAC of Hello packet is keyed by H2 which have been set at context initialising */ } break; /* MSGTYPE_HELLO */ case MSGTYPE_HELLOACK : { /* the message length is fixed */ zrtpPacket->messageLength = ZRTP_HELLOACKMESSAGE_FIXED_LENGTH; /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+ZRTP_HELLOACKMESSAGE_FIXED_LENGTH+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); } break; /* MSGTYPE_HELLOACK */ case MSGTYPE_COMMIT : { bzrtpCommitMessage_t *messageData; uint16_t variableLength = 0; /* get the Commit message structure */ if (zrtpPacket->messageData == NULL) { return BZRTP_BUILDER_ERROR_INVALIDMESSAGE; } messageData = (bzrtpCommitMessage_t *)zrtpPacket->messageData; /* compute message length */ switch(messageData->keyAgreementAlgo) { case ZRTP_KEYAGREEMENT_DH2k : case ZRTP_KEYAGREEMENT_EC25 : case ZRTP_KEYAGREEMENT_DH3k : case ZRTP_KEYAGREEMENT_EC38 : case ZRTP_KEYAGREEMENT_EC52 : variableLength = 32; /* hvi is 32 bytes length in DH Commit message format */ break; case ZRTP_KEYAGREEMENT_Prsh : variableLength = 24; /* nonce (16 bytes) and keyID(8 bytes) are 24 bytes length in preshared Commit message format */ break; case ZRTP_KEYAGREEMENT_Mult : variableLength = 16; /* nonce is 24 bytes length in multistream Commit message format */ break; default: return BZRTP_BUILDER_ERROR_INVALIDMESSAGE; } zrtpPacket->messageLength = ZRTP_COMMITMESSAGE_FIXED_LENGTH + variableLength; /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+zrtpPacket->messageLength+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); /* have the messageString pointer to the begining of message(after the message header wich is computed for all messages after the switch) * within the packetString buffer*/ messageString = zrtpPacket->packetString + ZRTP_PACKET_HEADER_LENGTH + ZRTP_MESSAGE_HEADER_LENGTH; /* now insert the different message parts into the packetString */ memcpy(messageString, messageData->H2, 32); messageString += 32; memcpy(messageString, messageData->ZID, 12); messageString += 12; cryptoAlgoTypeIntToString(messageData->hashAlgo, messageString); messageString += 4; cryptoAlgoTypeIntToString(messageData->cipherAlgo, messageString); messageString += 4; cryptoAlgoTypeIntToString(messageData->authTagAlgo, messageString); messageString += 4; cryptoAlgoTypeIntToString(messageData->keyAgreementAlgo, messageString); messageString += 4; cryptoAlgoTypeIntToString(messageData->sasAlgo, messageString); messageString += 4; /* if it is a multistream or preshared commit insert the 16 bytes nonce */ if ((messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) { memcpy(messageString, messageData->nonce, 16); messageString += 16; /* and the keyID for preshared commit only */ if (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) { memcpy(messageString, messageData->keyID, 8); messageString +=8; } } else { /* it's a DH commit message, set the hvi */ memcpy(messageString, messageData->hvi, 32); messageString +=32; } /* there is a MAC to compute, set the pointers to the key and MAC output buffer */ MACbuffer = messageString; MACkey = zrtpChannelContext->selfH[1]; /* HMAC of Hello packet is keyed by H1 which have been set at context initialising */ } break; /*MSGTYPE_COMMIT */ case MSGTYPE_DHPART1 : case MSGTYPE_DHPART2 : { bzrtpDHPartMessage_t *messageData; uint16_t pvLength; /* get the DHPart message structure */ if (zrtpPacket->messageData == NULL) { return BZRTP_BUILDER_ERROR_INVALIDMESSAGE; } messageData = (bzrtpDHPartMessage_t *)zrtpPacket->messageData; /* compute message length */ pvLength = computeKeyAgreementPrivateValueLength(zrtpChannelContext->keyAgreementAlgo); if (pvLength==0) { return BZRTP_BUILDER_ERROR_INVALIDCONTEXT; } zrtpPacket->messageLength = ZRTP_DHPARTMESSAGE_FIXED_LENGTH + pvLength; /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+zrtpPacket->messageLength+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); /* have the messageString pointer to the begining of message(after the message header wich is computed for all messages after the switch) * within the packetString buffer*/ messageString = zrtpPacket->packetString + ZRTP_PACKET_HEADER_LENGTH + ZRTP_MESSAGE_HEADER_LENGTH; /* now insert the different message parts into the packetString */ memcpy(messageString, messageData->H1, 32); messageString += 32; memcpy(messageString, messageData->rs1ID, 8); messageString += 8; memcpy(messageString, messageData->rs2ID, 8); messageString += 8; memcpy(messageString, messageData->auxsecretID, 8); messageString += 8; memcpy(messageString, messageData->pbxsecretID, 8); messageString += 8; memcpy(messageString, messageData->pv, pvLength); messageString += pvLength; /* there is a MAC to compute, set the pointers to the key and MAC output buffer */ MACbuffer = messageString; MACkey = zrtpChannelContext->selfH[0]; /* HMAC of Hello packet is keyed by H0 which have been set at context initialising */ } break; /* MSGTYPE_DHPART1 and 2 */ case MSGTYPE_CONFIRM1: case MSGTYPE_CONFIRM2: { uint8_t *confirmMessageKey = NULL; uint8_t *confirmMessageMacKey = NULL; bzrtpConfirmMessage_t *messageData; uint16_t encryptedPartLength; uint8_t *plainMessageString; uint16_t plainMessageStringIndex = 0; /* we will have to encrypt and validate the message, check we have the keys to do it */ if (zrtpChannelContext->role == INITIATOR) { if ((zrtpChannelContext->zrtpkeyi == NULL) || (zrtpChannelContext->mackeyi == NULL)) { return BZRTP_BUILDER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyi; confirmMessageMacKey = zrtpChannelContext->mackeyi; } if (zrtpChannelContext->role == RESPONDER) { if ((zrtpChannelContext->zrtpkeyr == NULL) || (zrtpChannelContext->mackeyr == NULL)) { return BZRTP_BUILDER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyr; confirmMessageMacKey = zrtpChannelContext->mackeyr; } /* get the Confirm message structure */ if (zrtpPacket->messageData == NULL) { return BZRTP_BUILDER_ERROR_INVALIDMESSAGE; } messageData = (bzrtpConfirmMessage_t *)zrtpPacket->messageData; /* compute message length */ zrtpPacket->messageLength = ZRTP_CONFIRMMESSAGE_FIXED_LENGTH + messageData->sig_len*4; /* sig_len is in word of 4 bytes */ /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+zrtpPacket->messageLength+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); /* have the messageString pointer to the begining of message(after the message header wich is computed for all messages after the switch) * within the packetString buffer*/ messageString = zrtpPacket->packetString + ZRTP_PACKET_HEADER_LENGTH + ZRTP_MESSAGE_HEADER_LENGTH; /* allocate a temporary buffer to store the plain text */ encryptedPartLength = zrtpPacket->messageLength - ZRTP_MESSAGE_HEADER_LENGTH - 24; /* message header, confirm_mac(8 bytes) and CFB IV(16 bytes) are not encrypted */ plainMessageString = (uint8_t *)malloc(encryptedPartLength*sizeof(uint8_t)); /* fill the plain message buffer with data from the message structure */ memcpy(plainMessageString, messageData->H0, 32); plainMessageStringIndex += 32; plainMessageString[plainMessageStringIndex++] = 0x00; plainMessageString[plainMessageStringIndex++] = (uint8_t)(((messageData->sig_len)>>8)&0x0001); plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->sig_len)&0x00FF); plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->E&0x01)<<3) | (uint8_t)((messageData->V&0x01)<<2) | (uint8_t)((messageData->A&0x01)<<1) | (uint8_t)(messageData->D&0x01) ; /* cache expiration in a 32 bits unsigned int */ plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->cacheExpirationInterval>>24)&0xFF); plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->cacheExpirationInterval>>16)&0xFF); plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->cacheExpirationInterval>>8)&0xFF); plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->cacheExpirationInterval)&0xFF); if (messageData->sig_len>0) { memcpy(plainMessageString+plainMessageStringIndex, messageData->signatureBlockType, 4); plainMessageStringIndex += 4; /* sig_len is in 4 bytes words and include the 1 word of signature block type */ memcpy(plainMessageString+plainMessageStringIndex, messageData->signatureBlock, (messageData->sig_len-1)*4); } /* encrypt the buffer, set the output directly in the messageString buffer at the correct position(+24 after message header) */ zrtpChannelContext->cipherEncryptionFunction(confirmMessageKey, messageData->CFBIV, plainMessageString, encryptedPartLength, messageString+24); free(plainMessageString); /* free the plain message string temporary buffer */ /* compute the mac over the encrypted part of the message and set the result in the messageString */ zrtpChannelContext->hmacFunction(confirmMessageMacKey, zrtpChannelContext->hashLength, messageString+24, encryptedPartLength, 8, messageString); messageString += 8; /* add the CFB IV */ memcpy(messageString, messageData->CFBIV, 16); } break; /* MSGTYPE_CONFIRM1 and MSGTYPE_CONFIRM2 */ case MSGTYPE_CONF2ACK: { /* the message length is fixed */ zrtpPacket->messageLength = ZRTP_CONF2ACKMESSAGE_FIXED_LENGTH; /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+ZRTP_CONF2ACKMESSAGE_FIXED_LENGTH+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); } break; /* MSGTYPE_CONF2ACK */ case MSGTYPE_PINGACK: { bzrtpPingAckMessage_t *messageData; /* the message length is fixed */ zrtpPacket->messageLength = ZRTP_PINGACKMESSAGE_FIXED_LENGTH; /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+ZRTP_PINGACKMESSAGE_FIXED_LENGTH+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); messageString = zrtpPacket->packetString + ZRTP_PACKET_HEADER_LENGTH + ZRTP_MESSAGE_HEADER_LENGTH; /* now insert the different message parts into the packetString */ messageData = (bzrtpPingAckMessage_t *)zrtpPacket->messageData; memcpy(messageString, messageData->version, 4); messageString += 4; memcpy(messageString, messageData->endpointHash, 8); messageString += 8; memcpy(messageString, messageData->endpointHashReceived, 8); messageString += 8; *messageString++ = (uint8_t)((messageData->SSRC>>24)&0xFF); *messageString++ = (uint8_t)((messageData->SSRC>>16)&0xFF); *messageString++ = (uint8_t)((messageData->SSRC>>8)&0xFF); *messageString++ = (uint8_t)(messageData->SSRC&0xFF); } break; /* MSGTYPE_PINGACK */ } /* write headers only if we have a packet string */ if (zrtpPacket->packetString != NULL) { uint32_t CRC; uint8_t *CRCbuffer; zrtpMessageSetHeader(zrtpPacket->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpPacket->messageLength, messageTypeString); /* Do we have a MAC to compute on the message ? */ if (MACbuffer != NULL) { /* compute the MAC(64 bits only) using the implicit HMAC function for ZRTP v1.10: HMAC-SHA256 */ /* HMAC is computed on the whole message except the MAC itself so a length of zrtpPacket->messageLength-8 */ bctoolbox_hmacSha256(MACkey, 32, zrtpPacket->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpPacket->messageLength-8, 8, MACbuffer); } /* set packet header and CRC */ /* preambule */ zrtpPacket->packetString[0] = 0x10; zrtpPacket->packetString[1] = 0x00; /* Sequence number */ zrtpPacket->packetString[2] = (uint8_t)((sequenceNumber>>8)&0x00FF); zrtpPacket->packetString[3] = (uint8_t)(sequenceNumber&0x00FF); /* ZRTP magic cookie */ zrtpPacket->packetString[4] = (uint8_t)((ZRTP_MAGIC_COOKIE>>24)&0xFF); zrtpPacket->packetString[5] = (uint8_t)((ZRTP_MAGIC_COOKIE>>16)&0xFF); zrtpPacket->packetString[6] = (uint8_t)((ZRTP_MAGIC_COOKIE>>8)&0xFF); zrtpPacket->packetString[7] = (uint8_t)(ZRTP_MAGIC_COOKIE&0xFF); /* Source Identifier */ zrtpPacket->packetString[8] = (uint8_t)(((zrtpPacket->sourceIdentifier)>>24)&0xFF); zrtpPacket->packetString[9] = (uint8_t)(((zrtpPacket->sourceIdentifier)>>16)&0xFF); zrtpPacket->packetString[10] = (uint8_t)(((zrtpPacket->sourceIdentifier)>>8)&0xFF); zrtpPacket->packetString[11] = (uint8_t)((zrtpPacket->sourceIdentifier)&0xFF); /* CRC */ CRC = bzrtp_CRC32(zrtpPacket->packetString, zrtpPacket->messageLength+ZRTP_PACKET_HEADER_LENGTH); CRCbuffer = (zrtpPacket->packetString)+(zrtpPacket->messageLength)+ZRTP_PACKET_HEADER_LENGTH; *CRCbuffer = (uint8_t)((CRC>>24)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>16)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>8)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)(CRC&0xFF); return 0; } else { /* no packetString allocated something wen't wrong but we shall never arrive here */ return BZRTP_BUILDER_ERROR_UNKNOWN; } } /* create a zrtpPacket and initialise it's structures */ bzrtpPacket_t *bzrtp_createZrtpPacket(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, uint32_t messageType, int *exitCode) { /* allocate packet */ bzrtpPacket_t *zrtpPacket = (bzrtpPacket_t *)malloc(sizeof(bzrtpPacket_t)); memset(zrtpPacket, 0, sizeof(bzrtpPacket_t)); zrtpPacket->messageData = NULL; zrtpPacket->packetString = NULL; /* initialise it */ switch(messageType) { case MSGTYPE_HELLO: { int i; bzrtpHelloMessage_t *zrtpHelloMessage = (bzrtpHelloMessage_t *)malloc(sizeof(bzrtpHelloMessage_t)); memset(zrtpHelloMessage, 0, sizeof(bzrtpHelloMessage_t)); /* initialise some fields using zrtp context data */ memcpy(zrtpHelloMessage->version, ZRTP_VERSION, 4); strncpy((char*)zrtpHelloMessage->clientIdentifier, ZRTP_CLIENT_IDENTIFIER, 16); memcpy(zrtpHelloMessage->H3, zrtpChannelContext->selfH[3], 32); memcpy(zrtpHelloMessage->ZID, zrtpContext->selfZID, 12); /* set all S,M,P flags to zero as we're not able to verify signatures, we're not a PBX(TODO: implement?), we're not passive */ zrtpHelloMessage->S = 0; zrtpHelloMessage->M = 0; zrtpHelloMessage->P = 0; /* get the algorithm availabilities from the context */ zrtpHelloMessage->hc = zrtpContext->hc; zrtpHelloMessage->cc = zrtpContext->cc; zrtpHelloMessage->ac = zrtpContext->ac; zrtpHelloMessage->kc = zrtpContext->kc; zrtpHelloMessage->sc = zrtpContext->sc; for (i=0; i<zrtpContext->hc; i++) { zrtpHelloMessage->supportedHash[i] = zrtpContext->supportedHash[i]; } for (i=0; i<zrtpContext->cc; i++) { zrtpHelloMessage->supportedCipher[i] = zrtpContext->supportedCipher[i]; } for (i=0; i<zrtpContext->ac; i++) { zrtpHelloMessage->supportedAuthTag[i] = zrtpContext->supportedAuthTag[i]; } for (i=0; i<zrtpContext->kc; i++) { zrtpHelloMessage->supportedKeyAgreement[i] = zrtpContext->supportedKeyAgreement[i]; } for (i=0; i<zrtpContext->sc; i++) { zrtpHelloMessage->supportedSas[i] = zrtpContext->supportedSas[i]; } /* attach the message data to the packet */ zrtpPacket->messageData = zrtpHelloMessage; } break; /* MSGTYPE_HELLO */ case MSGTYPE_HELLOACK : { /* nothing to do for the Hello ACK packet as it just contains it's type */ } break; /* MSGTYPE_HELLOACK */ /* In case of DH commit, this one must be called after the DHPart build and the self DH message and peer Hello message are stored in the context */ case MSGTYPE_COMMIT : { bzrtpCommitMessage_t *zrtpCommitMessage = (bzrtpCommitMessage_t *)malloc(sizeof(bzrtpCommitMessage_t)); memset(zrtpCommitMessage, 0, sizeof(bzrtpCommitMessage_t)); /* initialise some fields using zrtp context data */ memcpy(zrtpCommitMessage->H2, zrtpChannelContext->selfH[2], 32); memcpy(zrtpCommitMessage->ZID, zrtpContext->selfZID, 12); zrtpCommitMessage->hashAlgo = zrtpChannelContext->hashAlgo; zrtpCommitMessage->cipherAlgo = zrtpChannelContext->cipherAlgo; zrtpCommitMessage->authTagAlgo = zrtpChannelContext->authTagAlgo; zrtpCommitMessage->keyAgreementAlgo = zrtpChannelContext->keyAgreementAlgo; zrtpCommitMessage->sasAlgo = zrtpChannelContext->sasAlgo; /* if it is a multistream or preshared commit create a 16 random bytes nonce */ if ((zrtpCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (zrtpCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) { bctoolbox_rng_get(zrtpContext->RNGContext, zrtpCommitMessage->nonce, 16); /* and the keyID for preshared commit only */ if (zrtpCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) { /* TODO at this point we must first compute the preShared key - make sure at least rs1 is present */ /* preshared_key = hash(len(rs1) || rs1 || len(auxsecret) || auxsecret || len(pbxsecret) || pbxsecret) using the agreed hash and store it into the env */ /* and then the keyID : MAC(preshared_key, "Prsh") truncated to 64 bits using the agreed MAC */ } } else { /* it's a DH commit message, set the hvi */ /* hvi = hash(initiator's DHPart2 message || responder's Hello message) using the agreed hash function truncated to 256 bits */ /* create a string with the messages concatenated */ uint16_t DHPartMessageLength = zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength; uint16_t HelloMessageLength = zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength; uint16_t DHPartHelloMessageStringLength = DHPartMessageLength + HelloMessageLength; uint8_t *DHPartHelloMessageString = (uint8_t *)malloc(DHPartHelloMessageStringLength*sizeof(uint8_t)); memcpy(DHPartHelloMessageString, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, DHPartMessageLength); memcpy(DHPartHelloMessageString+DHPartMessageLength, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, HelloMessageLength); zrtpChannelContext->hashFunction(DHPartHelloMessageString, DHPartHelloMessageStringLength, 32, zrtpCommitMessage->hvi); free(DHPartHelloMessageString); } /* attach the message data to the packet */ zrtpPacket->messageData = zrtpCommitMessage; } break; /* MSGTYPE_COMMIT */ /* this one is called after the exchange of Hello messages when the crypto algo agreement have been performed */ case MSGTYPE_DHPART1 : case MSGTYPE_DHPART2 : { uint8_t secretLength; /* is in bytes */ uint8_t bctoolbox_keyAgreementAlgo = BCTOOLBOX_DHM_UNSET; bzrtpDHPartMessage_t *zrtpDHPartMessage = (bzrtpDHPartMessage_t *)malloc(sizeof(bzrtpDHPartMessage_t)); memset(zrtpDHPartMessage, 0, sizeof(bzrtpDHPartMessage_t)); /* initialise some fields using zrtp context data */ memcpy(zrtpDHPartMessage->H1, zrtpChannelContext->selfH[1], 32); /* get the retained secret from context, we anyway create a DHPart2 packet that we may turn into a DHPart1 packet if we end to * be the responder and not the initiator, use the initiator retained secret hashes */ memcpy(zrtpDHPartMessage->rs1ID, zrtpContext->initiatorCachedSecretHash.rs1ID, 8); memcpy(zrtpDHPartMessage->rs2ID, zrtpContext->initiatorCachedSecretHash.rs2ID, 8); memcpy(zrtpDHPartMessage->auxsecretID, zrtpChannelContext->initiatorAuxsecretID, 8); memcpy(zrtpDHPartMessage->pbxsecretID, zrtpContext->initiatorCachedSecretHash.pbxsecretID, 8); /* compute the public value and insert it in the message, will then be used whatever role - initiator or responder - we assume */ /* initialise the dhm context, secret length shall be twice the size of cipher block key length - rfc section 5.1.5 */ switch (zrtpChannelContext->cipherAlgo) { case ZRTP_CIPHER_AES3: case ZRTP_CIPHER_2FS3: secretLength = 64; break; case ZRTP_CIPHER_AES2: case ZRTP_CIPHER_2FS2: secretLength = 48; break; case ZRTP_CIPHER_AES1: case ZRTP_CIPHER_2FS1: default: secretLength = 32; break; } switch (zrtpChannelContext->keyAgreementAlgo) { case ZRTP_KEYAGREEMENT_DH2k: bctoolbox_keyAgreementAlgo = BCTOOLBOX_DHM_2048; break; case ZRTP_KEYAGREEMENT_DH3k: bctoolbox_keyAgreementAlgo = BCTOOLBOX_DHM_3072; break; default: free(zrtpPacket); free(zrtpDHPartMessage); *exitCode = BZRTP_CREATE_ERROR_UNABLETOCREATECRYPTOCONTEXT; return NULL; break; } zrtpContext->DHMContext = bctoolbox_CreateDHMContext(bctoolbox_keyAgreementAlgo, secretLength); if (zrtpContext->DHMContext == NULL) { free(zrtpPacket); free(zrtpDHPartMessage); *exitCode = BZRTP_CREATE_ERROR_UNABLETOCREATECRYPTOCONTEXT; return NULL; } /* now compute the public value */ bctoolbox_DHMCreatePublic(zrtpContext->DHMContext, (int (*)(void *, uint8_t *, size_t))bctoolbox_rng_get, zrtpContext->RNGContext); zrtpDHPartMessage->pv = (uint8_t *)malloc((zrtpChannelContext->keyAgreementLength)*sizeof(uint8_t)); memcpy(zrtpDHPartMessage->pv, zrtpContext->DHMContext->self, zrtpChannelContext->keyAgreementLength); /* attach the message data to the packet */ zrtpPacket->messageData = zrtpDHPartMessage; } break; /* MSGTYPE_DHPART1 and MSGTYPE_DHPART2 */ case MSGTYPE_CONFIRM1: case MSGTYPE_CONFIRM2: { bzrtpConfirmMessage_t *zrtpConfirmMessage = (bzrtpConfirmMessage_t *)malloc(sizeof(bzrtpConfirmMessage_t)); memset(zrtpConfirmMessage, 0, sizeof(bzrtpConfirmMessage_t)); /* initialise some fields using zrtp context data */ memcpy(zrtpConfirmMessage->H0, zrtpChannelContext->selfH[0], 32); zrtpConfirmMessage->sig_len = 0; /* signature is not supported */ zrtpConfirmMessage->cacheExpirationInterval = 0xFFFFFFFF; /* expiration interval is set to unlimited as recommended in rfc section 4.9 */ zrtpConfirmMessage->E = 0; /* we are not a PBX and then will never signal an enrollment - rfc section 7.3.1 */ zrtpConfirmMessage->V = zrtpContext->cachedSecret.previouslyVerifiedSas; zrtpConfirmMessage->A = 0; /* Go clear message is not supported - rfc section 4.7.2 */ zrtpConfirmMessage->D = 0; /* The is no backdoor in our implementation of ZRTP - rfc section 11 */ /* generate a random CFB IV */ bctoolbox_rng_get(zrtpContext->RNGContext, zrtpConfirmMessage->CFBIV, 16); /* attach the message data to the packet */ zrtpPacket->messageData = zrtpConfirmMessage; } break; /* MSGTYPE_CONFIRM1 and MSGTYPE_CONFIRM2 */ case MSGTYPE_CONF2ACK : { /* nothing to do for the conf2ACK packet as it just contains it's type */ } break; /* MSGTYPE_CONF2ACK */ case MSGTYPE_PINGACK: { bzrtpPingMessage_t *pingMessage; bzrtpPingAckMessage_t *zrtpPingAckMessage; /* to create a pingACK we must have a ping packet in the channel context, check it */ bzrtpPacket_t *pingPacket = zrtpChannelContext->pingPacket; if (pingPacket == NULL) { *exitCode = BZRTP_CREATE_ERROR_INVALIDCONTEXT; return NULL; } pingMessage = (bzrtpPingMessage_t *)pingPacket->messageData; /* create the message */ zrtpPingAckMessage = (bzrtpPingAckMessage_t *)malloc(sizeof(bzrtpPingAckMessage_t)); memset(zrtpPingAckMessage, 0, sizeof(bzrtpPingAckMessage_t)); /* initialise all fields using zrtp context data and the received ping message */ memcpy(zrtpPingAckMessage->version,ZRTP_VERSION , 4); /* we support version 1.10 only, so no need to even check what was sent in the ping */ memcpy(zrtpPingAckMessage->endpointHash, zrtpContext->selfZID, 8); /* as suggested in rfc section 5.16, use the truncated ZID as endPoint hash */ memcpy(zrtpPingAckMessage->endpointHashReceived, pingMessage->endpointHash, 8); zrtpPingAckMessage->SSRC = pingPacket->sourceIdentifier; /* attach the message data to the packet */ zrtpPacket->messageData = zrtpPingAckMessage; } /* MSGTYPE_PINGACK */ break; default: free(zrtpPacket); *exitCode = BZRTP_CREATE_ERROR_INVALIDMESSAGETYPE; return NULL; break; } zrtpPacket->sequenceNumber = 0; /* this field is not used buy the packet creator, sequence number is given as a parameter when converting the message to a packet string(packet build). Used only when parsing a string into a packet struct */ zrtpPacket->messageType = messageType; zrtpPacket->sourceIdentifier = zrtpChannelContext->selfSSRC; zrtpPacket->messageLength = 0; /* length will be computed at packet build */ zrtpPacket->packetString = NULL; *exitCode=0; return zrtpPacket; } void bzrtp_freeZrtpPacket(bzrtpPacket_t *zrtpPacket) { if (zrtpPacket != NULL) { /* some messages have fields to be freed */ if (zrtpPacket->messageData != NULL) { switch(zrtpPacket->messageType) { case MSGTYPE_DHPART1 : case MSGTYPE_DHPART2 : { bzrtpDHPartMessage_t *typedMessageData = (bzrtpDHPartMessage_t *)(zrtpPacket->messageData); if (typedMessageData != NULL) { free(typedMessageData->pv); } } break; case MSGTYPE_CONFIRM1: case MSGTYPE_CONFIRM2: { bzrtpConfirmMessage_t *typedMessageData = (bzrtpConfirmMessage_t *)(zrtpPacket->messageData); if (typedMessageData != NULL) { free(typedMessageData->signatureBlock); } } break; } } free(zrtpPacket->messageData); free(zrtpPacket->packetString); free(zrtpPacket); } } /** * @brief Modify the current sequence number of the packet in the packetString and sequenceNumber fields * The CRC at the end of packetString is also updated * * param[in/out] zrtpPacket The zrtpPacket to modify, the packetString must have been generated by * a call to bzrtp_packetBuild on this packet * param[in] sequenceNumber The new sequence number to insert in the packetString * * return 0 on succes, error code otherwise */ int bzrtp_packetUpdateSequenceNumber(bzrtpPacket_t *zrtpPacket, uint16_t sequenceNumber) { uint32_t CRC; uint8_t *CRCbuffer; if (zrtpPacket == NULL) { return BZRTP_BUILDER_ERROR_INVALIDPACKET; } if (zrtpPacket->packetString == NULL) { return BZRTP_BUILDER_ERROR_INVALIDPACKET; } /* update the sequence number field (even if it is probably useless as this function is called just before sending the DHPart2 packet only)*/ zrtpPacket->sequenceNumber = sequenceNumber; /* update hte sequence number in the packetString */ *(zrtpPacket->packetString+2)= (uint8_t)((sequenceNumber>>8)&0x00FF); *(zrtpPacket->packetString+3)= (uint8_t)(sequenceNumber&0x00FF); /* update the CRC */ CRC = bzrtp_CRC32(zrtpPacket->packetString, zrtpPacket->messageLength+ZRTP_PACKET_HEADER_LENGTH); CRCbuffer = (zrtpPacket->packetString)+(zrtpPacket->messageLength)+ZRTP_PACKET_HEADER_LENGTH; *CRCbuffer = (uint8_t)((CRC>>24)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>16)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>8)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)(CRC&0xFF); return 0; } /*** Local functions implementation ***/ uint8_t *messageTypeInttoString(uint32_t messageType) { switch(messageType) { case MSGTYPE_HELLO : return (uint8_t *)"Hello "; break; case MSGTYPE_HELLOACK : return (uint8_t *)"HelloACK"; break; case MSGTYPE_COMMIT : return (uint8_t *)"Commit "; break; case MSGTYPE_DHPART1 : return (uint8_t *)"DHPart1 "; break; case MSGTYPE_DHPART2 : return (uint8_t *)"DHPart2 "; break; case MSGTYPE_CONFIRM1 : return (uint8_t *)"Confirm1"; break; case MSGTYPE_CONFIRM2 : return (uint8_t *)"Confirm2"; break; case MSGTYPE_CONF2ACK : return (uint8_t *)"Conf2ACK"; break; case MSGTYPE_ERROR : return (uint8_t *)"Error "; break; case MSGTYPE_ERRORACK : return (uint8_t *)"ErrorACK"; break; case MSGTYPE_GOCLEAR : return (uint8_t *)"GoClear "; break; case MSGTYPE_CLEARACK : return (uint8_t *)"ClearACK"; break; case MSGTYPE_SASRELAY : return (uint8_t *)"SASrelay"; break; case MSGTYPE_RELAYACK : return (uint8_t *)"RelayACK"; break; case MSGTYPE_PING : return (uint8_t *)"Ping "; break; case MSGTYPE_PINGACK : return (uint8_t *)"PingACK "; break; } return NULL; } /* * @brief Map the 8 char string value message type to an int32_t * * @param[in] messageTypeString an 8 bytes string matching a zrtp message type * * @return a 32-bits unsigned integer mapping the message type */ int32_t messageTypeStringtoInt(uint8_t messageTypeString[8]) { if (memcmp(messageTypeString, "Hello ", 8) == 0) { return MSGTYPE_HELLO; } else if (memcmp(messageTypeString, "HelloACK", 8) == 0) { return MSGTYPE_HELLOACK; } else if (memcmp(messageTypeString, "Commit ", 8) == 0) { return MSGTYPE_COMMIT; } else if (memcmp(messageTypeString, "DHPart1 ", 8) == 0) { return MSGTYPE_DHPART1; } else if (memcmp(messageTypeString, "DHPart2 ", 8) == 0) { return MSGTYPE_DHPART2; } else if (memcmp(messageTypeString, "Confirm1", 8) == 0) { return MSGTYPE_CONFIRM1; } else if (memcmp(messageTypeString, "Confirm2", 8) == 0) { return MSGTYPE_CONFIRM2; } else if (memcmp(messageTypeString, "Conf2ACK", 8) == 0) { return MSGTYPE_CONF2ACK; } else if (memcmp(messageTypeString, "Error ", 8) == 0) { return MSGTYPE_ERROR; } else if (memcmp(messageTypeString, "ErrorACK", 8) == 0) { return MSGTYPE_ERRORACK; } else if (memcmp(messageTypeString, "GoClear ", 8) == 0) { return MSGTYPE_GOCLEAR; } else if (memcmp(messageTypeString, "ClearACK", 8) == 0) { return MSGTYPE_CLEARACK; } else if (memcmp(messageTypeString, "SASrelay", 8) == 0) { return MSGTYPE_SASRELAY; } else if (memcmp(messageTypeString, "RelayACK", 8) == 0) { return MSGTYPE_RELAYACK; } else if (memcmp(messageTypeString, "Ping ", 8) == 0) { return MSGTYPE_PING; } else if (memcmp(messageTypeString, "PingACK ", 8) == 0) { return MSGTYPE_PINGACK; } else { return MSGTYPE_INVALID; } } /* * @brief Write the message header(preambule, length, message type) into the given output buffer * * @param[out] outputBuffer Message starts at the begining of this buffer * @param[in] messageLength Message length in bytes! To be converted into 32bits words before being inserted in the message header * @param[in] messageType An 8 chars string for the message type (validity is not checked by this function) * */ void zrtpMessageSetHeader(uint8_t *outputBuffer, uint16_t messageLength, uint8_t messageType[8]) { /* insert the preambule */ outputBuffer[0] = 0x50; outputBuffer[1] = 0x5a; /* then the length in 32 bits words (param is in bytes, so >> 2) */ outputBuffer[2] = (uint8_t)((messageLength>>10)&0x00FF); outputBuffer[3] = (uint8_t)((messageLength>>2)&0x00FF); /* the message type */ memcpy(outputBuffer+4, messageType, 8); } /* * Return the variable private value length in bytes according to given key agreement algorythm * * @param[in] keyAgreementAlgo The key agreement algo mapped to an integer as defined in cryptoWrapper.h * * @return the private value length in bytes * */ uint16_t computeKeyAgreementPrivateValueLength(uint8_t keyAgreementAlgo) { uint16_t pvLength = 0; switch (keyAgreementAlgo) { case ZRTP_KEYAGREEMENT_DH3k : pvLength = 384; break; case ZRTP_KEYAGREEMENT_DH2k : pvLength = 256; break; case ZRTP_KEYAGREEMENT_EC25 : pvLength = 64; break; case ZRTP_KEYAGREEMENT_EC38 : pvLength = 96; break; case ZRTP_KEYAGREEMENT_EC52 : pvLength = 132; break; default : pvLength = 0; break; } return pvLength; }
./CrossVul/dataset_final_sorted/CWE-254/c/good_5205_1
crossvul-cpp_data_bad_1761_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-254/c/bad_1761_0
crossvul-cpp_data_bad_5328_0
/* * Copyright (c) 2012 David Vossel <davidvossel@gmail.com> * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <crm_internal.h> #include <glib.h> #include <unistd.h> #include <crm/crm.h> #include <crm/msg_xml.h> #include <crm/crm.h> #include <crm/msg_xml.h> #include <crm/common/mainloop.h> #include <lrmd_private.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <arpa/inet.h> #ifdef HAVE_GNUTLS_GNUTLS_H # define LRMD_REMOTE_AUTH_TIMEOUT 10000 gnutls_psk_server_credentials_t psk_cred_s; gnutls_dh_params_t dh_params; static int ssock = -1; extern int lrmd_call_id; static void debug_log(int level, const char *str) { fputs(str, stderr); } static int lrmd_remote_client_msg(gpointer data) { int id = 0; int rc = 0; int disconnected = 0; xmlNode *request = NULL; crm_client_t *client = data; if (client->remote->tls_handshake_complete == FALSE) { int rc = 0; /* Muliple calls to handshake will be required, this callback * will be invoked once the client sends more handshake data. */ do { rc = gnutls_handshake(*client->remote->tls_session); if (rc < 0 && rc != GNUTLS_E_AGAIN) { crm_err("Remote lrmd tls handshake failed"); return -1; } } while (rc == GNUTLS_E_INTERRUPTED); if (rc == 0) { crm_debug("Remote lrmd tls handshake completed"); client->remote->tls_handshake_complete = TRUE; if (client->remote->auth_timeout) { g_source_remove(client->remote->auth_timeout); } client->remote->auth_timeout = 0; } return 0; } rc = crm_remote_ready(client->remote, 0); if (rc == 0) { /* no msg to read */ return 0; } else if (rc < 0) { crm_info("Client disconnected during remote client read"); return -1; } crm_remote_recv(client->remote, -1, &disconnected); request = crm_remote_parse_buffer(client->remote); while (request) { crm_element_value_int(request, F_LRMD_REMOTE_MSG_ID, &id); crm_trace("processing request from remote client with remote msg id %d", id); if (!client->name) { const char *value = crm_element_value(request, F_LRMD_CLIENTNAME); if (value) { client->name = strdup(value); } } lrmd_call_id++; if (lrmd_call_id < 1) { lrmd_call_id = 1; } crm_xml_add(request, F_LRMD_CLIENTID, client->id); crm_xml_add(request, F_LRMD_CLIENTNAME, client->name); crm_xml_add_int(request, F_LRMD_CALLID, lrmd_call_id); process_lrmd_message(client, id, request); free_xml(request); /* process all the messages in the current buffer */ request = crm_remote_parse_buffer(client->remote); } if (disconnected) { crm_info("Client disconnect detected in tls msg dispatcher."); return -1; } return 0; } static void lrmd_remote_client_destroy(gpointer user_data) { crm_client_t *client = user_data; if (client == NULL) { return; } ipc_proxy_remove_provider(client); /* if this is the last remote connection, stop recurring * operations */ if (crm_hash_table_size(client_connections) == 1) { client_disconnect_cleanup(NULL); } crm_notice("LRMD client disconnecting remote client - name: %s id: %s", client->name ? client->name : "<unknown>", client->id); if (client->remote->tls_session) { void *sock_ptr; int csock; sock_ptr = gnutls_transport_get_ptr(*client->remote->tls_session); csock = GPOINTER_TO_INT(sock_ptr); gnutls_bye(*client->remote->tls_session, GNUTLS_SHUT_RDWR); gnutls_deinit(*client->remote->tls_session); gnutls_free(client->remote->tls_session); close(csock); } lrmd_client_destroy(client); return; } static gboolean lrmd_auth_timeout_cb(gpointer data) { crm_client_t *client = data; client->remote->auth_timeout = 0; if (client->remote->tls_handshake_complete == TRUE) { return FALSE; } mainloop_del_fd(client->remote->source); client->remote->source = NULL; crm_err("Remote client authentication timed out"); return FALSE; } /* Convert a struct sockaddr address to a string, IPv4 and IPv6: */ static char * get_ip_str(const struct sockaddr * sa, char * s, size_t maxlen) { switch(sa->sa_family) { case AF_INET: inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr), s, maxlen); break; case AF_INET6: inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr), s, maxlen); break; default: strncpy(s, "Unknown AF", maxlen); return NULL; } return s; } static int lrmd_remote_listen(gpointer data) { int csock = 0; int flag = 0; unsigned laddr = 0; struct sockaddr addr; gnutls_session_t *session = NULL; crm_client_t *new_client = NULL; static struct mainloop_fd_callbacks lrmd_remote_fd_cb = { .dispatch = lrmd_remote_client_msg, .destroy = lrmd_remote_client_destroy, }; laddr = sizeof(addr); memset(&addr, 0, sizeof(addr)); getsockname(ssock, &addr, &laddr); /* accept the connection */ if (addr.sa_family == AF_INET6) { struct sockaddr_in6 sa; char addr_str[INET6_ADDRSTRLEN]; laddr = sizeof(sa); memset(&sa, 0, sizeof(sa)); csock = accept(ssock, &sa, &laddr); get_ip_str((struct sockaddr *)&sa, addr_str, INET6_ADDRSTRLEN); crm_info("New remote connection from %s", addr_str); } else { struct sockaddr_in sa; char addr_str[INET_ADDRSTRLEN]; laddr = sizeof(sa); memset(&sa, 0, sizeof(sa)); csock = accept(ssock, &sa, &laddr); get_ip_str((struct sockaddr *)&sa, addr_str, INET_ADDRSTRLEN); crm_info("New remote connection from %s", addr_str); } if (csock == -1) { crm_err("accept socket failed"); return TRUE; } if ((flag = fcntl(csock, F_GETFL)) >= 0) { if (fcntl(csock, F_SETFL, flag | O_NONBLOCK) < 0) { crm_err("fcntl() write failed"); close(csock); return TRUE; } } else { crm_err("fcntl() read failed"); close(csock); return TRUE; } session = create_psk_tls_session(csock, GNUTLS_SERVER, psk_cred_s); if (session == NULL) { crm_err("TLS session creation failed"); close(csock); return TRUE; } new_client = calloc(1, sizeof(crm_client_t)); new_client->remote = calloc(1, sizeof(crm_remote_t)); new_client->kind = CRM_CLIENT_TLS; new_client->remote->tls_session = session; new_client->id = crm_generate_uuid(); new_client->remote->auth_timeout = g_timeout_add(LRMD_REMOTE_AUTH_TIMEOUT, lrmd_auth_timeout_cb, new_client); crm_notice("LRMD client connection established. %p id: %s", new_client, new_client->id); new_client->remote->source = mainloop_add_fd("lrmd-remote-client", G_PRIORITY_DEFAULT, csock, new_client, &lrmd_remote_fd_cb); g_hash_table_insert(client_connections, new_client->id, new_client); /* Alert other clients of the new connection */ notify_of_new_client(new_client); return TRUE; } static void lrmd_remote_connection_destroy(gpointer user_data) { crm_notice("Remote tls server disconnected"); return; } static int lrmd_tls_server_key_cb(gnutls_session_t session, const char *username, gnutls_datum_t * key) { return lrmd_tls_set_key(key); } static int bind_and_listen(struct addrinfo *addr) { int optval; int fd; int rc; char buffer[256] = { 0, }; if (addr->ai_family == AF_INET6) { struct sockaddr_in6 *addr_in = (struct sockaddr_in6 *)(void*)addr->ai_addr; inet_ntop(addr->ai_family, &addr_in->sin6_addr, buffer, DIMOF(buffer)); } else { struct sockaddr_in *addr_in = (struct sockaddr_in *)(void*)addr->ai_addr; inet_ntop(addr->ai_family, &addr_in->sin_addr, buffer, DIMOF(buffer)); } crm_trace("Attempting to bind on address %s", buffer); fd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (fd < 0) { return -1; } /* reuse address */ optval = 1; rc = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (rc < 0) { crm_perror(LOG_INFO, "Couldn't allow the reuse of local addresses by our remote listener, bind address %s", buffer); close(fd); return -1; } if (addr->ai_family == AF_INET6) { optval = 0; rc = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval)); if (rc < 0) { crm_perror(LOG_INFO, "Couldn't disable IPV6 only on address %s", buffer); close(fd); return -1; } } if (bind(fd, addr->ai_addr, addr->ai_addrlen) != 0) { close(fd); return -1; } if (listen(fd, 10) == -1) { crm_err("Can not start listen on address %s", buffer); close(fd); return -1; } crm_notice("Listening on address %s", buffer); return fd; } int lrmd_init_remote_tls_server(int port) { int rc; int filter; struct addrinfo hints, *res = NULL, *iter; char port_str[16]; static struct mainloop_fd_callbacks remote_listen_fd_callbacks = { .dispatch = lrmd_remote_listen, .destroy = lrmd_remote_connection_destroy, }; crm_notice("Starting a tls listener on port %d.", port); crm_gnutls_global_init(); gnutls_global_set_log_function(debug_log); gnutls_dh_params_init(&dh_params); gnutls_dh_params_generate2(dh_params, 1024); gnutls_psk_allocate_server_credentials(&psk_cred_s); gnutls_psk_set_server_credentials_function(psk_cred_s, lrmd_tls_server_key_cb); gnutls_psk_set_server_dh_params(psk_cred_s, dh_params); memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; /* Only return socket addresses with wildcard INADDR_ANY or IN6ADDR_ANY_INIT */ hints.ai_family = AF_UNSPEC; /* Return IPv6 or IPv4 */ hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; snprintf(port_str, sizeof(port_str), "%d", port); rc = getaddrinfo(NULL, port_str, &hints, &res); if (rc) { crm_err("getaddrinfo: %s", gai_strerror(rc)); return -1; } iter = res; filter = AF_INET6; /* Try IPv6 addresses first, then IPv4 */ while (iter) { if (iter->ai_family == filter) { ssock = bind_and_listen(iter); } if (ssock != -1) { break; } iter = iter->ai_next; if (iter == NULL && filter == AF_INET6) { iter = res; filter = AF_INET; } } if (ssock < 0) { crm_err("unable to bind to address"); goto init_remote_cleanup; } mainloop_add_fd("lrmd-remote", G_PRIORITY_DEFAULT, ssock, NULL, &remote_listen_fd_callbacks); rc = ssock; init_remote_cleanup: if (rc < 0) { close(ssock); ssock = 0; } freeaddrinfo(res); return rc; } void lrmd_tls_server_destroy(void) { if (psk_cred_s) { gnutls_psk_free_server_credentials(psk_cred_s); psk_cred_s = 0; } if (ssock > 0) { close(ssock); ssock = 0; } } #endif
./CrossVul/dataset_final_sorted/CWE-254/c/bad_5328_0
crossvul-cpp_data_good_1761_0
/* * Kexec bzImage loader * * Copyright (C) 2014 Red Hat Inc. * Authors: * Vivek Goyal <vgoyal@redhat.com> * * This source code is licensed under the GNU General Public License, * Version 2. See the file COPYING for more details. */ #define pr_fmt(fmt) "kexec-bzImage64: " fmt #include <linux/string.h> #include <linux/printk.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/kexec.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/efi.h> #include <linux/verify_pefile.h> #include <keys/system_keyring.h> #include <asm/bootparam.h> #include <asm/setup.h> #include <asm/crash.h> #include <asm/efi.h> #include <asm/kexec-bzimage64.h> #define MAX_ELFCOREHDR_STR_LEN 30 /* elfcorehdr=0x<64bit-value> */ /* * Defines lowest physical address for various segments. Not sure where * exactly these limits came from. Current bzimage64 loader in kexec-tools * uses these so I am retaining it. It can be changed over time as we gain * more insight. */ #define MIN_PURGATORY_ADDR 0x3000 #define MIN_BOOTPARAM_ADDR 0x3000 #define MIN_KERNEL_LOAD_ADDR 0x100000 #define MIN_INITRD_LOAD_ADDR 0x1000000 /* * This is a place holder for all boot loader specific data structure which * gets allocated in one call but gets freed much later during cleanup * time. Right now there is only one field but it can grow as need be. */ struct bzimage64_data { /* * Temporary buffer to hold bootparams buffer. This should be * freed once the bootparam segment has been loaded. */ void *bootparams_buf; }; static int setup_initrd(struct boot_params *params, unsigned long initrd_load_addr, unsigned long initrd_len) { params->hdr.ramdisk_image = initrd_load_addr & 0xffffffffUL; params->hdr.ramdisk_size = initrd_len & 0xffffffffUL; params->ext_ramdisk_image = initrd_load_addr >> 32; params->ext_ramdisk_size = initrd_len >> 32; return 0; } static int setup_cmdline(struct kimage *image, struct boot_params *params, unsigned long bootparams_load_addr, unsigned long cmdline_offset, char *cmdline, unsigned long cmdline_len) { char *cmdline_ptr = ((char *)params) + cmdline_offset; unsigned long cmdline_ptr_phys, len = 0; uint32_t cmdline_low_32, cmdline_ext_32; if (image->type == KEXEC_TYPE_CRASH) { len = sprintf(cmdline_ptr, "elfcorehdr=0x%lx ", image->arch.elf_load_addr); } memcpy(cmdline_ptr + len, cmdline, cmdline_len); cmdline_len += len; cmdline_ptr[cmdline_len - 1] = '\0'; pr_debug("Final command line is: %s\n", cmdline_ptr); cmdline_ptr_phys = bootparams_load_addr + cmdline_offset; cmdline_low_32 = cmdline_ptr_phys & 0xffffffffUL; cmdline_ext_32 = cmdline_ptr_phys >> 32; params->hdr.cmd_line_ptr = cmdline_low_32; if (cmdline_ext_32) params->ext_cmd_line_ptr = cmdline_ext_32; return 0; } static int setup_e820_entries(struct boot_params *params) { unsigned int nr_e820_entries; nr_e820_entries = e820_saved.nr_map; /* TODO: Pass entries more than E820MAX in bootparams setup data */ if (nr_e820_entries > E820MAX) nr_e820_entries = E820MAX; params->e820_entries = nr_e820_entries; memcpy(&params->e820_map, &e820_saved.map, nr_e820_entries * sizeof(struct e820entry)); return 0; } #ifdef CONFIG_EFI static int setup_efi_info_memmap(struct boot_params *params, unsigned long params_load_addr, unsigned int efi_map_offset, unsigned int efi_map_sz) { void *efi_map = (void *)params + efi_map_offset; unsigned long efi_map_phys_addr = params_load_addr + efi_map_offset; struct efi_info *ei = &params->efi_info; if (!efi_map_sz) return 0; efi_runtime_map_copy(efi_map, efi_map_sz); ei->efi_memmap = efi_map_phys_addr & 0xffffffff; ei->efi_memmap_hi = efi_map_phys_addr >> 32; ei->efi_memmap_size = efi_map_sz; return 0; } static int prepare_add_efi_setup_data(struct boot_params *params, unsigned long params_load_addr, unsigned int efi_setup_data_offset) { unsigned long setup_data_phys; struct setup_data *sd = (void *)params + efi_setup_data_offset; struct efi_setup_data *esd = (void *)sd + sizeof(struct setup_data); esd->fw_vendor = efi.fw_vendor; esd->runtime = efi.runtime; esd->tables = efi.config_table; esd->smbios = efi.smbios; sd->type = SETUP_EFI; sd->len = sizeof(struct efi_setup_data); /* Add setup data */ setup_data_phys = params_load_addr + efi_setup_data_offset; sd->next = params->hdr.setup_data; params->hdr.setup_data = setup_data_phys; return 0; } static int setup_efi_state(struct boot_params *params, unsigned long params_load_addr, unsigned int efi_map_offset, unsigned int efi_map_sz, unsigned int efi_setup_data_offset) { struct efi_info *current_ei = &boot_params.efi_info; struct efi_info *ei = &params->efi_info; if (!current_ei->efi_memmap_size) return 0; /* * If 1:1 mapping is not enabled, second kernel can not setup EFI * and use EFI run time services. User space will have to pass * acpi_rsdp=<addr> on kernel command line to make second kernel boot * without efi. */ if (efi_enabled(EFI_OLD_MEMMAP)) return 0; params->secure_boot = boot_params.secure_boot; ei->efi_loader_signature = current_ei->efi_loader_signature; ei->efi_systab = current_ei->efi_systab; ei->efi_systab_hi = current_ei->efi_systab_hi; ei->efi_memdesc_version = current_ei->efi_memdesc_version; ei->efi_memdesc_size = efi_get_runtime_map_desc_size(); setup_efi_info_memmap(params, params_load_addr, efi_map_offset, efi_map_sz); prepare_add_efi_setup_data(params, params_load_addr, efi_setup_data_offset); return 0; } #endif /* CONFIG_EFI */ static int setup_boot_parameters(struct kimage *image, struct boot_params *params, unsigned long params_load_addr, unsigned int efi_map_offset, unsigned int efi_map_sz, unsigned int efi_setup_data_offset) { unsigned int nr_e820_entries; unsigned long long mem_k, start, end; int i, ret = 0; /* Get subarch from existing bootparams */ params->hdr.hardware_subarch = boot_params.hdr.hardware_subarch; /* Copying screen_info will do? */ memcpy(&params->screen_info, &boot_params.screen_info, sizeof(struct screen_info)); /* Fill in memsize later */ params->screen_info.ext_mem_k = 0; params->alt_mem_k = 0; /* Default APM info */ memset(&params->apm_bios_info, 0, sizeof(params->apm_bios_info)); /* Default drive info */ memset(&params->hd0_info, 0, sizeof(params->hd0_info)); memset(&params->hd1_info, 0, sizeof(params->hd1_info)); if (image->type == KEXEC_TYPE_CRASH) { ret = crash_setup_memmap_entries(image, params); if (ret) return ret; } else setup_e820_entries(params); nr_e820_entries = params->e820_entries; for (i = 0; i < nr_e820_entries; i++) { if (params->e820_map[i].type != E820_RAM) continue; start = params->e820_map[i].addr; end = params->e820_map[i].addr + params->e820_map[i].size - 1; if ((start <= 0x100000) && end > 0x100000) { mem_k = (end >> 10) - (0x100000 >> 10); params->screen_info.ext_mem_k = mem_k; params->alt_mem_k = mem_k; if (mem_k > 0xfc00) params->screen_info.ext_mem_k = 0xfc00; /* 64M*/ if (mem_k > 0xffffffff) params->alt_mem_k = 0xffffffff; } } #ifdef CONFIG_EFI /* Setup EFI state */ setup_efi_state(params, params_load_addr, efi_map_offset, efi_map_sz, efi_setup_data_offset); #endif /* Setup EDD info */ memcpy(params->eddbuf, boot_params.eddbuf, EDDMAXNR * sizeof(struct edd_info)); params->eddbuf_entries = boot_params.eddbuf_entries; memcpy(params->edd_mbr_sig_buffer, boot_params.edd_mbr_sig_buffer, EDD_MBR_SIG_MAX * sizeof(unsigned int)); return ret; } static int bzImage64_probe(const char *buf, unsigned long len) { int ret = -ENOEXEC; struct setup_header *header; /* kernel should be at least two sectors long */ if (len < 2 * 512) { pr_err("File is too short to be a bzImage\n"); return ret; } header = (struct setup_header *)(buf + offsetof(struct boot_params, hdr)); if (memcmp((char *)&header->header, "HdrS", 4) != 0) { pr_err("Not a bzImage\n"); return ret; } if (header->boot_flag != 0xAA55) { pr_err("No x86 boot sector present\n"); return ret; } if (header->version < 0x020C) { pr_err("Must be at least protocol version 2.12\n"); return ret; } if (!(header->loadflags & LOADED_HIGH)) { pr_err("zImage not a bzImage\n"); return ret; } if (!(header->xloadflags & XLF_KERNEL_64)) { pr_err("Not a bzImage64. XLF_KERNEL_64 is not set.\n"); return ret; } if (!(header->xloadflags & XLF_CAN_BE_LOADED_ABOVE_4G)) { pr_err("XLF_CAN_BE_LOADED_ABOVE_4G is not set.\n"); return ret; } /* * Can't handle 32bit EFI as it does not allow loading kernel * above 4G. This should be handled by 32bit bzImage loader */ if (efi_enabled(EFI_RUNTIME_SERVICES) && !efi_enabled(EFI_64BIT)) { pr_debug("EFI is 32 bit. Can't load kernel above 4G.\n"); return ret; } /* I've got a bzImage */ pr_debug("It's a relocatable bzImage64\n"); ret = 0; return ret; } static void *bzImage64_load(struct kimage *image, char *kernel, unsigned long kernel_len, char *initrd, unsigned long initrd_len, char *cmdline, unsigned long cmdline_len) { struct setup_header *header; int setup_sects, kern16_size, ret = 0; unsigned long setup_header_size, params_cmdline_sz, params_misc_sz; struct boot_params *params; unsigned long bootparam_load_addr, kernel_load_addr, initrd_load_addr; unsigned long purgatory_load_addr; unsigned long kernel_bufsz, kernel_memsz, kernel_align; char *kernel_buf; struct bzimage64_data *ldata; struct kexec_entry64_regs regs64; void *stack; unsigned int setup_hdr_offset = offsetof(struct boot_params, hdr); unsigned int efi_map_offset, efi_map_sz, efi_setup_data_offset; header = (struct setup_header *)(kernel + setup_hdr_offset); setup_sects = header->setup_sects; if (setup_sects == 0) setup_sects = 4; kern16_size = (setup_sects + 1) * 512; if (kernel_len < kern16_size) { pr_err("bzImage truncated\n"); return ERR_PTR(-ENOEXEC); } if (cmdline_len > header->cmdline_size) { pr_err("Kernel command line too long\n"); return ERR_PTR(-EINVAL); } /* * In case of crash dump, we will append elfcorehdr=<addr> to * command line. Make sure it does not overflow */ if (cmdline_len + MAX_ELFCOREHDR_STR_LEN > header->cmdline_size) { pr_debug("Appending elfcorehdr=<addr> to command line exceeds maximum allowed length\n"); return ERR_PTR(-EINVAL); } /* Allocate and load backup region */ if (image->type == KEXEC_TYPE_CRASH) { ret = crash_load_segments(image); if (ret) return ERR_PTR(ret); } /* * Load purgatory. For 64bit entry point, purgatory code can be * anywhere. */ ret = kexec_load_purgatory(image, MIN_PURGATORY_ADDR, ULONG_MAX, 1, &purgatory_load_addr); if (ret) { pr_err("Loading purgatory failed\n"); return ERR_PTR(ret); } pr_debug("Loaded purgatory at 0x%lx\n", purgatory_load_addr); /* * Load Bootparams and cmdline and space for efi stuff. * * Allocate memory together for multiple data structures so * that they all can go in single area/segment and we don't * have to create separate segment for each. Keeps things * little bit simple */ efi_map_sz = efi_get_runtime_map_size(); efi_map_sz = ALIGN(efi_map_sz, 16); params_cmdline_sz = sizeof(struct boot_params) + cmdline_len + MAX_ELFCOREHDR_STR_LEN; params_cmdline_sz = ALIGN(params_cmdline_sz, 16); params_misc_sz = params_cmdline_sz + efi_map_sz + sizeof(struct setup_data) + sizeof(struct efi_setup_data); params = kzalloc(params_misc_sz, GFP_KERNEL); if (!params) return ERR_PTR(-ENOMEM); efi_map_offset = params_cmdline_sz; efi_setup_data_offset = efi_map_offset + efi_map_sz; /* Copy setup header onto bootparams. Documentation/x86/boot.txt */ setup_header_size = 0x0202 + kernel[0x0201] - setup_hdr_offset; /* Is there a limit on setup header size? */ memcpy(&params->hdr, (kernel + setup_hdr_offset), setup_header_size); ret = kexec_add_buffer(image, (char *)params, params_misc_sz, params_misc_sz, 16, MIN_BOOTPARAM_ADDR, ULONG_MAX, 1, &bootparam_load_addr); if (ret) goto out_free_params; pr_debug("Loaded boot_param, command line and misc at 0x%lx bufsz=0x%lx memsz=0x%lx\n", bootparam_load_addr, params_misc_sz, params_misc_sz); /* Load kernel */ kernel_buf = kernel + kern16_size; kernel_bufsz = kernel_len - kern16_size; kernel_memsz = PAGE_ALIGN(header->init_size); kernel_align = header->kernel_alignment; ret = kexec_add_buffer(image, kernel_buf, kernel_bufsz, kernel_memsz, kernel_align, MIN_KERNEL_LOAD_ADDR, ULONG_MAX, 1, &kernel_load_addr); if (ret) goto out_free_params; pr_debug("Loaded 64bit kernel at 0x%lx bufsz=0x%lx memsz=0x%lx\n", kernel_load_addr, kernel_memsz, kernel_memsz); /* Load initrd high */ if (initrd) { ret = kexec_add_buffer(image, initrd, initrd_len, initrd_len, PAGE_SIZE, MIN_INITRD_LOAD_ADDR, ULONG_MAX, 1, &initrd_load_addr); if (ret) goto out_free_params; pr_debug("Loaded initrd at 0x%lx bufsz=0x%lx memsz=0x%lx\n", initrd_load_addr, initrd_len, initrd_len); setup_initrd(params, initrd_load_addr, initrd_len); } setup_cmdline(image, params, bootparam_load_addr, sizeof(struct boot_params), cmdline, cmdline_len); /* bootloader info. Do we need a separate ID for kexec kernel loader? */ params->hdr.type_of_loader = 0x0D << 4; params->hdr.loadflags = 0; /* Setup purgatory regs for entry */ ret = kexec_purgatory_get_set_symbol(image, "entry64_regs", &regs64, sizeof(regs64), 1); if (ret) goto out_free_params; regs64.rbx = 0; /* Bootstrap Processor */ regs64.rsi = bootparam_load_addr; regs64.rip = kernel_load_addr + 0x200; stack = kexec_purgatory_get_symbol_addr(image, "stack_end"); if (IS_ERR(stack)) { pr_err("Could not find address of symbol stack_end\n"); ret = -EINVAL; goto out_free_params; } regs64.rsp = (unsigned long)stack; ret = kexec_purgatory_get_set_symbol(image, "entry64_regs", &regs64, sizeof(regs64), 0); if (ret) goto out_free_params; ret = setup_boot_parameters(image, params, bootparam_load_addr, efi_map_offset, efi_map_sz, efi_setup_data_offset); if (ret) goto out_free_params; /* Allocate loader specific data */ ldata = kzalloc(sizeof(struct bzimage64_data), GFP_KERNEL); if (!ldata) { ret = -ENOMEM; goto out_free_params; } /* * Store pointer to params so that it could be freed after loading * params segment has been loaded and contents have been copied * somewhere else. */ ldata->bootparams_buf = params; return ldata; out_free_params: kfree(params); return ERR_PTR(ret); } /* This cleanup function is called after various segments have been loaded */ static int bzImage64_cleanup(void *loader_data) { struct bzimage64_data *ldata = loader_data; if (!ldata) return 0; kfree(ldata->bootparams_buf); ldata->bootparams_buf = NULL; return 0; } #ifdef CONFIG_KEXEC_BZIMAGE_VERIFY_SIG static int bzImage64_verify_sig(const char *kernel, unsigned long kernel_len) { bool trusted; int ret; ret = verify_pefile_signature(kernel, kernel_len, system_trusted_keyring, VERIFYING_KEXEC_PE_SIGNATURE, &trusted); if (ret < 0) return ret; if (!trusted) return -EKEYREJECTED; return 0; } #endif struct kexec_file_ops kexec_bzImage64_ops = { .probe = bzImage64_probe, .load = bzImage64_load, .cleanup = bzImage64_cleanup, #ifdef CONFIG_KEXEC_BZIMAGE_VERIFY_SIG .verify_sig = bzImage64_verify_sig, #endif };
./CrossVul/dataset_final_sorted/CWE-254/c/good_1761_0
crossvul-cpp_data_good_4872_0
/* * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "server.h" #include <sys/uio.h> #include <math.h> static void setProtocolError(client *c, int pos); /* Return the size consumed from the allocator, for the specified SDS string, * including internal fragmentation. This function is used in order to compute * the client output buffer size. */ size_t sdsZmallocSize(sds s) { void *sh = sdsAllocPtr(s); return zmalloc_size(sh); } /* Return the amount of memory used by the sds string at object->ptr * for a string object. */ size_t getStringObjectSdsUsedMemory(robj *o) { serverAssertWithInfo(NULL,o,o->type == OBJ_STRING); switch(o->encoding) { case OBJ_ENCODING_RAW: return sdsZmallocSize(o->ptr); case OBJ_ENCODING_EMBSTR: return zmalloc_size(o)-sizeof(robj); default: return 0; /* Just integer encoding for now. */ } } void *dupClientReplyValue(void *o) { incrRefCount((robj*)o); return o; } int listMatchObjects(void *a, void *b) { return equalStringObjects(a,b); } client *createClient(int fd) { client *c = zmalloc(sizeof(client)); /* passing -1 as fd it is possible to create a non connected client. * This is useful since all the commands needs to be executed * in the context of a client. When commands are executed in other * contexts (for instance a Lua script) we need a non connected client. */ if (fd != -1) { anetNonBlock(NULL,fd); anetEnableTcpNoDelay(NULL,fd); if (server.tcpkeepalive) anetKeepAlive(NULL,fd,server.tcpkeepalive); if (aeCreateFileEvent(server.el,fd,AE_READABLE, readQueryFromClient, c) == AE_ERR) { close(fd); zfree(c); return NULL; } } selectDb(c,0); c->id = server.next_client_id++; c->fd = fd; c->name = NULL; c->bufpos = 0; c->querybuf = sdsempty(); c->querybuf_peak = 0; c->reqtype = 0; c->argc = 0; c->argv = NULL; c->cmd = c->lastcmd = NULL; c->multibulklen = 0; c->bulklen = -1; c->sentlen = 0; c->flags = 0; c->ctime = c->lastinteraction = server.unixtime; c->authenticated = 0; c->replstate = REPL_STATE_NONE; c->repl_put_online_on_ack = 0; c->reploff = 0; c->repl_ack_off = 0; c->repl_ack_time = 0; c->slave_listening_port = 0; c->slave_ip[0] = '\0'; c->slave_capa = SLAVE_CAPA_NONE; c->reply = listCreate(); c->reply_bytes = 0; c->obuf_soft_limit_reached_time = 0; listSetFreeMethod(c->reply,decrRefCountVoid); listSetDupMethod(c->reply,dupClientReplyValue); c->btype = BLOCKED_NONE; c->bpop.timeout = 0; c->bpop.keys = dictCreate(&setDictType,NULL); c->bpop.target = NULL; c->bpop.numreplicas = 0; c->bpop.reploffset = 0; c->woff = 0; c->watched_keys = listCreate(); c->pubsub_channels = dictCreate(&setDictType,NULL); c->pubsub_patterns = listCreate(); c->peerid = NULL; listSetFreeMethod(c->pubsub_patterns,decrRefCountVoid); listSetMatchMethod(c->pubsub_patterns,listMatchObjects); if (fd != -1) listAddNodeTail(server.clients,c); initClientMultiState(c); return c; } /* This function is called every time we are going to transmit new data * to the client. The behavior is the following: * * If the client should receive new data (normal clients will) the function * returns C_OK, and make sure to install the write handler in our event * loop so that when the socket is writable new data gets written. * * If the client should not receive new data, because it is a fake client * (used to load AOF in memory), a master or because the setup of the write * handler failed, the function returns C_ERR. * * The function may return C_OK without actually installing the write * event handler in the following cases: * * 1) The event handler should already be installed since the output buffer * already contained something. * 2) The client is a slave but not yet online, so we want to just accumulate * writes in the buffer but not actually sending them yet. * * Typically gets called every time a reply is built, before adding more * data to the clients output buffers. If the function returns C_ERR no * data should be appended to the output buffers. */ int prepareClientToWrite(client *c) { /* If it's the Lua client we always return ok without installing any * handler since there is no socket at all. */ if (c->flags & CLIENT_LUA) return C_OK; /* CLIENT REPLY OFF / SKIP handling: don't send replies. */ if (c->flags & (CLIENT_REPLY_OFF|CLIENT_REPLY_SKIP)) return C_ERR; /* Masters don't receive replies, unless CLIENT_MASTER_FORCE_REPLY flag * is set. */ if ((c->flags & CLIENT_MASTER) && !(c->flags & CLIENT_MASTER_FORCE_REPLY)) return C_ERR; if (c->fd <= 0) return C_ERR; /* Fake client for AOF loading. */ /* Schedule the client to write the output buffers to the socket only * if not already done (there were no pending writes already and the client * was yet not flagged), and, for slaves, if the slave can actually * receive writes at this stage. */ if (!clientHasPendingReplies(c) && !(c->flags & CLIENT_PENDING_WRITE) && (c->replstate == REPL_STATE_NONE || (c->replstate == SLAVE_STATE_ONLINE && !c->repl_put_online_on_ack))) { /* Here instead of installing the write handler, we just flag the * client and put it into a list of clients that have something * to write to the socket. This way before re-entering the event * loop, we can try to directly write to the client sockets avoiding * a system call. We'll only really install the write handler if * we'll not be able to write the whole reply at once. */ c->flags |= CLIENT_PENDING_WRITE; listAddNodeHead(server.clients_pending_write,c); } /* Authorize the caller to queue in the output buffer of this client. */ return C_OK; } /* Create a duplicate of the last object in the reply list when * it is not exclusively owned by the reply list. */ robj *dupLastObjectIfNeeded(list *reply) { robj *new, *cur; listNode *ln; serverAssert(listLength(reply) > 0); ln = listLast(reply); cur = listNodeValue(ln); if (cur->refcount > 1) { new = dupStringObject(cur); decrRefCount(cur); listNodeValue(ln) = new; } return listNodeValue(ln); } /* ----------------------------------------------------------------------------- * Low level functions to add more data to output buffers. * -------------------------------------------------------------------------- */ int _addReplyToBuffer(client *c, const char *s, size_t len) { size_t available = sizeof(c->buf)-c->bufpos; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return C_OK; /* If there already are entries in the reply list, we cannot * add anything more to the static buffer. */ if (listLength(c->reply) > 0) return C_ERR; /* Check that the buffer has enough space available for this string. */ if (len > available) return C_ERR; memcpy(c->buf+c->bufpos,s,len); c->bufpos+=len; return C_OK; } void _addReplyObjectToList(client *c, robj *o) { robj *tail; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return; if (listLength(c->reply) == 0) { incrRefCount(o); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } else { tail = listNodeValue(listLast(c->reply)); /* Append to this object when possible. */ if (tail->ptr != NULL && tail->encoding == OBJ_ENCODING_RAW && sdslen(tail->ptr)+sdslen(o->ptr) <= PROTO_REPLY_CHUNK_BYTES) { c->reply_bytes -= sdsZmallocSize(tail->ptr); tail = dupLastObjectIfNeeded(c->reply); tail->ptr = sdscatlen(tail->ptr,o->ptr,sdslen(o->ptr)); c->reply_bytes += sdsZmallocSize(tail->ptr); } else { incrRefCount(o); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } } asyncCloseClientOnOutputBufferLimitReached(c); } /* This method takes responsibility over the sds. When it is no longer * needed it will be free'd, otherwise it ends up in a robj. */ void _addReplySdsToList(client *c, sds s) { robj *tail; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) { sdsfree(s); return; } if (listLength(c->reply) == 0) { listAddNodeTail(c->reply,createObject(OBJ_STRING,s)); c->reply_bytes += sdsZmallocSize(s); } else { tail = listNodeValue(listLast(c->reply)); /* Append to this object when possible. */ if (tail->ptr != NULL && tail->encoding == OBJ_ENCODING_RAW && sdslen(tail->ptr)+sdslen(s) <= PROTO_REPLY_CHUNK_BYTES) { c->reply_bytes -= sdsZmallocSize(tail->ptr); tail = dupLastObjectIfNeeded(c->reply); tail->ptr = sdscatlen(tail->ptr,s,sdslen(s)); c->reply_bytes += sdsZmallocSize(tail->ptr); sdsfree(s); } else { listAddNodeTail(c->reply,createObject(OBJ_STRING,s)); c->reply_bytes += sdsZmallocSize(s); } } asyncCloseClientOnOutputBufferLimitReached(c); } void _addReplyStringToList(client *c, const char *s, size_t len) { robj *tail; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return; if (listLength(c->reply) == 0) { robj *o = createStringObject(s,len); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } else { tail = listNodeValue(listLast(c->reply)); /* Append to this object when possible. */ if (tail->ptr != NULL && tail->encoding == OBJ_ENCODING_RAW && sdslen(tail->ptr)+len <= PROTO_REPLY_CHUNK_BYTES) { c->reply_bytes -= sdsZmallocSize(tail->ptr); tail = dupLastObjectIfNeeded(c->reply); tail->ptr = sdscatlen(tail->ptr,s,len); c->reply_bytes += sdsZmallocSize(tail->ptr); } else { robj *o = createStringObject(s,len); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } } asyncCloseClientOnOutputBufferLimitReached(c); } /* ----------------------------------------------------------------------------- * Higher level functions to queue data on the client output buffer. * The following functions are the ones that commands implementations will call. * -------------------------------------------------------------------------- */ void addReply(client *c, robj *obj) { if (prepareClientToWrite(c) != C_OK) return; /* This is an important place where we can avoid copy-on-write * when there is a saving child running, avoiding touching the * refcount field of the object if it's not needed. * * If the encoding is RAW and there is room in the static buffer * we'll be able to send the object to the client without * messing with its page. */ if (sdsEncodedObject(obj)) { if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != C_OK) _addReplyObjectToList(c,obj); } else if (obj->encoding == OBJ_ENCODING_INT) { /* Optimization: if there is room in the static buffer for 32 bytes * (more than the max chars a 64 bit integer can take as string) we * avoid decoding the object and go for the lower level approach. */ if (listLength(c->reply) == 0 && (sizeof(c->buf) - c->bufpos) >= 32) { char buf[32]; int len; len = ll2string(buf,sizeof(buf),(long)obj->ptr); if (_addReplyToBuffer(c,buf,len) == C_OK) return; /* else... continue with the normal code path, but should never * happen actually since we verified there is room. */ } obj = getDecodedObject(obj); if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != C_OK) _addReplyObjectToList(c,obj); decrRefCount(obj); } else { serverPanic("Wrong obj->encoding in addReply()"); } } void addReplySds(client *c, sds s) { if (prepareClientToWrite(c) != C_OK) { /* The caller expects the sds to be free'd. */ sdsfree(s); return; } if (_addReplyToBuffer(c,s,sdslen(s)) == C_OK) { sdsfree(s); } else { /* This method free's the sds when it is no longer needed. */ _addReplySdsToList(c,s); } } void addReplyString(client *c, const char *s, size_t len) { if (prepareClientToWrite(c) != C_OK) return; if (_addReplyToBuffer(c,s,len) != C_OK) _addReplyStringToList(c,s,len); } void addReplyErrorLength(client *c, const char *s, size_t len) { addReplyString(c,"-ERR ",5); addReplyString(c,s,len); addReplyString(c,"\r\n",2); } void addReplyError(client *c, const char *err) { addReplyErrorLength(c,err,strlen(err)); } void addReplyErrorFormat(client *c, const char *fmt, ...) { size_t l, j; va_list ap; va_start(ap,fmt); sds s = sdscatvprintf(sdsempty(),fmt,ap); va_end(ap); /* Make sure there are no newlines in the string, otherwise invalid protocol * is emitted. */ l = sdslen(s); for (j = 0; j < l; j++) { if (s[j] == '\r' || s[j] == '\n') s[j] = ' '; } addReplyErrorLength(c,s,sdslen(s)); sdsfree(s); } void addReplyStatusLength(client *c, const char *s, size_t len) { addReplyString(c,"+",1); addReplyString(c,s,len); addReplyString(c,"\r\n",2); } void addReplyStatus(client *c, const char *status) { addReplyStatusLength(c,status,strlen(status)); } void addReplyStatusFormat(client *c, const char *fmt, ...) { va_list ap; va_start(ap,fmt); sds s = sdscatvprintf(sdsempty(),fmt,ap); va_end(ap); addReplyStatusLength(c,s,sdslen(s)); sdsfree(s); } /* Adds an empty object to the reply list that will contain the multi bulk * length, which is not known when this function is called. */ void *addDeferredMultiBulkLength(client *c) { /* Note that we install the write event here even if the object is not * ready to be sent, since we are sure that before returning to the * event loop setDeferredMultiBulkLength() will be called. */ if (prepareClientToWrite(c) != C_OK) return NULL; listAddNodeTail(c->reply,createObject(OBJ_STRING,NULL)); return listLast(c->reply); } /* Populate the length object and try gluing it to the next chunk. */ void setDeferredMultiBulkLength(client *c, void *node, long length) { listNode *ln = (listNode*)node; robj *len, *next; /* Abort when *node is NULL (see addDeferredMultiBulkLength). */ if (node == NULL) return; len = listNodeValue(ln); len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length); len->encoding = OBJ_ENCODING_RAW; /* in case it was an EMBSTR. */ c->reply_bytes += sdsZmallocSize(len->ptr); if (ln->next != NULL) { next = listNodeValue(ln->next); /* Only glue when the next node is non-NULL (an sds in this case) */ if (next->ptr != NULL) { c->reply_bytes -= sdsZmallocSize(len->ptr); c->reply_bytes -= getStringObjectSdsUsedMemory(next); len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr)); c->reply_bytes += sdsZmallocSize(len->ptr); listDelNode(c->reply,ln->next); } } asyncCloseClientOnOutputBufferLimitReached(c); } /* Add a double as a bulk reply */ void addReplyDouble(client *c, double d) { char dbuf[128], sbuf[128]; int dlen, slen; if (isinf(d)) { /* Libc in odd systems (Hi Solaris!) will format infinite in a * different way, so better to handle it in an explicit way. */ addReplyBulkCString(c, d > 0 ? "inf" : "-inf"); } else { dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d); slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf); addReplyString(c,sbuf,slen); } } /* Add a long double as a bulk reply, but uses a human readable formatting * of the double instead of exposing the crude behavior of doubles to the * dear user. */ void addReplyHumanLongDouble(client *c, long double d) { robj *o = createStringObjectFromLongDouble(d,1); addReplyBulk(c,o); decrRefCount(o); } /* Add a long long as integer reply or bulk len / multi bulk count. * Basically this is used to output <prefix><long long><crlf>. */ void addReplyLongLongWithPrefix(client *c, long long ll, char prefix) { char buf[128]; int len; /* Things like $3\r\n or *2\r\n are emitted very often by the protocol * so we have a few shared objects to use if the integer is small * like it is most of the times. */ if (prefix == '*' && ll < OBJ_SHARED_BULKHDR_LEN && ll >= 0) { addReply(c,shared.mbulkhdr[ll]); return; } else if (prefix == '$' && ll < OBJ_SHARED_BULKHDR_LEN && ll >= 0) { addReply(c,shared.bulkhdr[ll]); return; } buf[0] = prefix; len = ll2string(buf+1,sizeof(buf)-1,ll); buf[len+1] = '\r'; buf[len+2] = '\n'; addReplyString(c,buf,len+3); } void addReplyLongLong(client *c, long long ll) { if (ll == 0) addReply(c,shared.czero); else if (ll == 1) addReply(c,shared.cone); else addReplyLongLongWithPrefix(c,ll,':'); } void addReplyMultiBulkLen(client *c, long length) { if (length < OBJ_SHARED_BULKHDR_LEN) addReply(c,shared.mbulkhdr[length]); else addReplyLongLongWithPrefix(c,length,'*'); } /* Create the length prefix of a bulk reply, example: $2234 */ void addReplyBulkLen(client *c, robj *obj) { size_t len; if (sdsEncodedObject(obj)) { len = sdslen(obj->ptr); } else { long n = (long)obj->ptr; /* Compute how many bytes will take this integer as a radix 10 string */ len = 1; if (n < 0) { len++; n = -n; } while((n = n/10) != 0) { len++; } } if (len < OBJ_SHARED_BULKHDR_LEN) addReply(c,shared.bulkhdr[len]); else addReplyLongLongWithPrefix(c,len,'$'); } /* Add a Redis Object as a bulk reply */ void addReplyBulk(client *c, robj *obj) { addReplyBulkLen(c,obj); addReply(c,obj); addReply(c,shared.crlf); } /* Add a C buffer as bulk reply */ void addReplyBulkCBuffer(client *c, const void *p, size_t len) { addReplyLongLongWithPrefix(c,len,'$'); addReplyString(c,p,len); addReply(c,shared.crlf); } /* Add sds to reply (takes ownership of sds and frees it) */ void addReplyBulkSds(client *c, sds s) { addReplySds(c,sdscatfmt(sdsempty(),"$%u\r\n", (unsigned long)sdslen(s))); addReplySds(c,s); addReply(c,shared.crlf); } /* Add a C nul term string as bulk reply */ void addReplyBulkCString(client *c, const char *s) { if (s == NULL) { addReply(c,shared.nullbulk); } else { addReplyBulkCBuffer(c,s,strlen(s)); } } /* Add a long long as a bulk reply */ void addReplyBulkLongLong(client *c, long long ll) { char buf[64]; int len; len = ll2string(buf,64,ll); addReplyBulkCBuffer(c,buf,len); } /* Copy 'src' client output buffers into 'dst' client output buffers. * The function takes care of freeing the old output buffers of the * destination client. */ void copyClientOutputBuffer(client *dst, client *src) { listRelease(dst->reply); dst->reply = listDup(src->reply); memcpy(dst->buf,src->buf,src->bufpos); dst->bufpos = src->bufpos; dst->reply_bytes = src->reply_bytes; } /* Return true if the specified client has pending reply buffers to write to * the socket. */ int clientHasPendingReplies(client *c) { return c->bufpos || listLength(c->reply); } #define MAX_ACCEPTS_PER_CALL 1000 static void acceptCommonHandler(int fd, int flags, char *ip) { client *c; if ((c = createClient(fd)) == NULL) { serverLog(LL_WARNING, "Error registering fd event for the new client: %s (fd=%d)", strerror(errno),fd); close(fd); /* May be already closed, just ignore errors */ return; } /* If maxclient directive is set and this is one client more... close the * connection. Note that we create the client instead to check before * for this condition, since now the socket is already set in non-blocking * mode and we can send an error for free using the Kernel I/O */ if (listLength(server.clients) > server.maxclients) { char *err = "-ERR max number of clients reached\r\n"; /* That's a best effort error message, don't check write errors */ if (write(c->fd,err,strlen(err)) == -1) { /* Nothing to do, Just to avoid the warning... */ } server.stat_rejected_conn++; freeClient(c); return; } /* If the server is running in protected mode (the default) and there * is no password set, nor a specific interface is bound, we don't accept * requests from non loopback interfaces. Instead we try to explain the * user what to do to fix it if needed. */ if (server.protected_mode && server.bindaddr_count == 0 && server.requirepass == NULL && !(flags & CLIENT_UNIX_SOCKET) && ip != NULL) { if (strcmp(ip,"127.0.0.1") && strcmp(ip,"::1")) { char *err = "-DENIED Redis is running in protected mode because protected " "mode is enabled, no bind address was specified, no " "authentication password is requested to clients. In this mode " "connections are only accepted from the loopback interface. " "If you want to connect from external computers to Redis you " "may adopt one of the following solutions: " "1) Just disable protected mode sending the command " "'CONFIG SET protected-mode no' from the loopback interface " "by connecting to Redis from the same host the server is " "running, however MAKE SURE Redis is not publicly accessible " "from internet if you do so. Use CONFIG REWRITE to make this " "change permanent. " "2) Alternatively you can just disable the protected mode by " "editing the Redis configuration file, and setting the protected " "mode option to 'no', and then restarting the server. " "3) If you started the server manually just for testing, restart " "it with the '--protected-mode no' option. " "4) Setup a bind address or an authentication password. " "NOTE: You only need to do one of the above things in order for " "the server to start accepting connections from the outside.\r\n"; if (write(c->fd,err,strlen(err)) == -1) { /* Nothing to do, Just to avoid the warning... */ } server.stat_rejected_conn++; freeClient(c); return; } } server.stat_numconnections++; c->flags |= flags; } void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) { int cport, cfd, max = MAX_ACCEPTS_PER_CALL; char cip[NET_IP_STR_LEN]; UNUSED(el); UNUSED(mask); UNUSED(privdata); while(max--) { cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); if (cfd == ANET_ERR) { if (errno != EWOULDBLOCK) serverLog(LL_WARNING, "Accepting client connection: %s", server.neterr); return; } serverLog(LL_VERBOSE,"Accepted %s:%d", cip, cport); acceptCommonHandler(cfd,0,cip); } } void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) { int cfd, max = MAX_ACCEPTS_PER_CALL; UNUSED(el); UNUSED(mask); UNUSED(privdata); while(max--) { cfd = anetUnixAccept(server.neterr, fd); if (cfd == ANET_ERR) { if (errno != EWOULDBLOCK) serverLog(LL_WARNING, "Accepting client connection: %s", server.neterr); return; } serverLog(LL_VERBOSE,"Accepted connection to %s", server.unixsocket); acceptCommonHandler(cfd,CLIENT_UNIX_SOCKET,NULL); } } static void freeClientArgv(client *c) { int j; for (j = 0; j < c->argc; j++) decrRefCount(c->argv[j]); c->argc = 0; c->cmd = NULL; } /* Close all the slaves connections. This is useful in chained replication * when we resync with our own master and want to force all our slaves to * resync with us as well. */ void disconnectSlaves(void) { while (listLength(server.slaves)) { listNode *ln = listFirst(server.slaves); freeClient((client*)ln->value); } } /* Remove the specified client from global lists where the client could * be referenced, not including the Pub/Sub channels. * This is used by freeClient() and replicationCacheMaster(). */ void unlinkClient(client *c) { listNode *ln; /* If this is marked as current client unset it. */ if (server.current_client == c) server.current_client = NULL; /* Certain operations must be done only if the client has an active socket. * If the client was already unlinked or if it's a "fake client" the * fd is already set to -1. */ if (c->fd != -1) { /* Remove from the list of active clients. */ ln = listSearchKey(server.clients,c); serverAssert(ln != NULL); listDelNode(server.clients,ln); /* Unregister async I/O handlers and close the socket. */ aeDeleteFileEvent(server.el,c->fd,AE_READABLE); aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE); close(c->fd); c->fd = -1; } /* Remove from the list of pending writes if needed. */ if (c->flags & CLIENT_PENDING_WRITE) { ln = listSearchKey(server.clients_pending_write,c); serverAssert(ln != NULL); listDelNode(server.clients_pending_write,ln); c->flags &= ~CLIENT_PENDING_WRITE; } /* When client was just unblocked because of a blocking operation, * remove it from the list of unblocked clients. */ if (c->flags & CLIENT_UNBLOCKED) { ln = listSearchKey(server.unblocked_clients,c); serverAssert(ln != NULL); listDelNode(server.unblocked_clients,ln); c->flags &= ~CLIENT_UNBLOCKED; } } void freeClient(client *c) { listNode *ln; /* If it is our master that's beging disconnected we should make sure * to cache the state to try a partial resynchronization later. * * Note that before doing this we make sure that the client is not in * some unexpected state, by checking its flags. */ if (server.master && c->flags & CLIENT_MASTER) { serverLog(LL_WARNING,"Connection with master lost."); if (!(c->flags & (CLIENT_CLOSE_AFTER_REPLY| CLIENT_CLOSE_ASAP| CLIENT_BLOCKED| CLIENT_UNBLOCKED))) { replicationCacheMaster(c); return; } } /* Log link disconnection with slave */ if ((c->flags & CLIENT_SLAVE) && !(c->flags & CLIENT_MONITOR)) { serverLog(LL_WARNING,"Connection with slave %s lost.", replicationGetSlaveName(c)); } /* Free the query buffer */ sdsfree(c->querybuf); c->querybuf = NULL; /* Deallocate structures used to block on blocking ops. */ if (c->flags & CLIENT_BLOCKED) unblockClient(c); dictRelease(c->bpop.keys); /* UNWATCH all the keys */ unwatchAllKeys(c); listRelease(c->watched_keys); /* Unsubscribe from all the pubsub channels */ pubsubUnsubscribeAllChannels(c,0); pubsubUnsubscribeAllPatterns(c,0); dictRelease(c->pubsub_channels); listRelease(c->pubsub_patterns); /* Free data structures. */ listRelease(c->reply); freeClientArgv(c); /* Unlink the client: this will close the socket, remove the I/O * handlers, and remove references of the client from different * places where active clients may be referenced. */ unlinkClient(c); /* Master/slave cleanup Case 1: * we lost the connection with a slave. */ if (c->flags & CLIENT_SLAVE) { if (c->replstate == SLAVE_STATE_SEND_BULK) { if (c->repldbfd != -1) close(c->repldbfd); if (c->replpreamble) sdsfree(c->replpreamble); } list *l = (c->flags & CLIENT_MONITOR) ? server.monitors : server.slaves; ln = listSearchKey(l,c); serverAssert(ln != NULL); listDelNode(l,ln); /* We need to remember the time when we started to have zero * attached slaves, as after some time we'll free the replication * backlog. */ if (c->flags & CLIENT_SLAVE && listLength(server.slaves) == 0) server.repl_no_slaves_since = server.unixtime; refreshGoodSlavesCount(); } /* Master/slave cleanup Case 2: * we lost the connection with the master. */ if (c->flags & CLIENT_MASTER) replicationHandleMasterDisconnection(); /* If this client was scheduled for async freeing we need to remove it * from the queue. */ if (c->flags & CLIENT_CLOSE_ASAP) { ln = listSearchKey(server.clients_to_close,c); serverAssert(ln != NULL); listDelNode(server.clients_to_close,ln); } /* Release other dynamically allocated client structure fields, * and finally release the client structure itself. */ if (c->name) decrRefCount(c->name); zfree(c->argv); freeClientMultiState(c); sdsfree(c->peerid); zfree(c); } /* Schedule a client to free it at a safe time in the serverCron() function. * This function is useful when we need to terminate a client but we are in * a context where calling freeClient() is not possible, because the client * should be valid for the continuation of the flow of the program. */ void freeClientAsync(client *c) { if (c->flags & CLIENT_CLOSE_ASAP || c->flags & CLIENT_LUA) return; c->flags |= CLIENT_CLOSE_ASAP; listAddNodeTail(server.clients_to_close,c); } void freeClientsInAsyncFreeQueue(void) { while (listLength(server.clients_to_close)) { listNode *ln = listFirst(server.clients_to_close); client *c = listNodeValue(ln); c->flags &= ~CLIENT_CLOSE_ASAP; freeClient(c); listDelNode(server.clients_to_close,ln); } } /* Write data in output buffers to client. Return C_OK if the client * is still valid after the call, C_ERR if it was freed. */ int writeToClient(int fd, client *c, int handler_installed) { ssize_t nwritten = 0, totwritten = 0; size_t objlen; size_t objmem; robj *o; while(clientHasPendingReplies(c)) { if (c->bufpos > 0) { nwritten = write(fd,c->buf+c->sentlen,c->bufpos-c->sentlen); if (nwritten <= 0) break; c->sentlen += nwritten; totwritten += nwritten; /* If the buffer was sent, set bufpos to zero to continue with * the remainder of the reply. */ if ((int)c->sentlen == c->bufpos) { c->bufpos = 0; c->sentlen = 0; } } else { o = listNodeValue(listFirst(c->reply)); objlen = sdslen(o->ptr); objmem = getStringObjectSdsUsedMemory(o); if (objlen == 0) { listDelNode(c->reply,listFirst(c->reply)); c->reply_bytes -= objmem; continue; } nwritten = write(fd, ((char*)o->ptr)+c->sentlen,objlen-c->sentlen); if (nwritten <= 0) break; c->sentlen += nwritten; totwritten += nwritten; /* If we fully sent the object on head go to the next one */ if (c->sentlen == objlen) { listDelNode(c->reply,listFirst(c->reply)); c->sentlen = 0; c->reply_bytes -= objmem; } } /* Note that we avoid to send more than NET_MAX_WRITES_PER_EVENT * bytes, in a single threaded server it's a good idea to serve * other clients as well, even if a very large request comes from * super fast link that is always able to accept data (in real world * scenario think about 'KEYS *' against the loopback interface). * * However if we are over the maxmemory limit we ignore that and * just deliver as much data as it is possible to deliver. */ server.stat_net_output_bytes += totwritten; if (totwritten > NET_MAX_WRITES_PER_EVENT && (server.maxmemory == 0 || zmalloc_used_memory() < server.maxmemory)) break; } if (nwritten == -1) { if (errno == EAGAIN) { nwritten = 0; } else { serverLog(LL_VERBOSE, "Error writing to client: %s", strerror(errno)); freeClient(c); return C_ERR; } } if (totwritten > 0) { /* For clients representing masters we don't count sending data * as an interaction, since we always send REPLCONF ACK commands * that take some time to just fill the socket output buffer. * We just rely on data / pings received for timeout detection. */ if (!(c->flags & CLIENT_MASTER)) c->lastinteraction = server.unixtime; } if (!clientHasPendingReplies(c)) { c->sentlen = 0; if (handler_installed) aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE); /* Close connection after entire reply has been sent. */ if (c->flags & CLIENT_CLOSE_AFTER_REPLY) { freeClient(c); return C_ERR; } } return C_OK; } /* Write event handler. Just send data to the client. */ void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) { UNUSED(el); UNUSED(mask); writeToClient(fd,privdata,1); } /* This function is called just before entering the event loop, in the hope * we can just write the replies to the client output buffer without any * need to use a syscall in order to install the writable event handler, * get it called, and so forth. */ int handleClientsWithPendingWrites(void) { listIter li; listNode *ln; int processed = listLength(server.clients_pending_write); listRewind(server.clients_pending_write,&li); while((ln = listNext(&li))) { client *c = listNodeValue(ln); c->flags &= ~CLIENT_PENDING_WRITE; listDelNode(server.clients_pending_write,ln); /* Try to write buffers to the client socket. */ if (writeToClient(c->fd,c,0) == C_ERR) continue; /* If there is nothing left, do nothing. Otherwise install * the write handler. */ if (clientHasPendingReplies(c) && aeCreateFileEvent(server.el, c->fd, AE_WRITABLE, sendReplyToClient, c) == AE_ERR) { freeClientAsync(c); } } return processed; } /* resetClient prepare the client to process the next command */ void resetClient(client *c) { redisCommandProc *prevcmd = c->cmd ? c->cmd->proc : NULL; freeClientArgv(c); c->reqtype = 0; c->multibulklen = 0; c->bulklen = -1; /* We clear the ASKING flag as well if we are not inside a MULTI, and * if what we just executed is not the ASKING command itself. */ if (!(c->flags & CLIENT_MULTI) && prevcmd != askingCommand) c->flags &= ~CLIENT_ASKING; /* Remove the CLIENT_REPLY_SKIP flag if any so that the reply * to the next command will be sent, but set the flag if the command * we just processed was "CLIENT REPLY SKIP". */ c->flags &= ~CLIENT_REPLY_SKIP; if (c->flags & CLIENT_REPLY_SKIP_NEXT) { c->flags |= CLIENT_REPLY_SKIP; c->flags &= ~CLIENT_REPLY_SKIP_NEXT; } } int processInlineBuffer(client *c) { char *newline; int argc, j; sds *argv, aux; size_t querylen; /* Search for end of line */ newline = strchr(c->querybuf,'\n'); /* Nothing to do without a \r\n */ if (newline == NULL) { if (sdslen(c->querybuf) > PROTO_INLINE_MAX_SIZE) { addReplyError(c,"Protocol error: too big inline request"); setProtocolError(c,0); } return C_ERR; } /* Handle the \r\n case. */ if (newline && newline != c->querybuf && *(newline-1) == '\r') newline--; /* Split the input buffer up to the \r\n */ querylen = newline-(c->querybuf); aux = sdsnewlen(c->querybuf,querylen); argv = sdssplitargs(aux,&argc); sdsfree(aux); if (argv == NULL) { addReplyError(c,"Protocol error: unbalanced quotes in request"); setProtocolError(c,0); return C_ERR; } /* Newline from slaves can be used to refresh the last ACK time. * This is useful for a slave to ping back while loading a big * RDB file. */ if (querylen == 0 && c->flags & CLIENT_SLAVE) c->repl_ack_time = server.unixtime; /* Leave data after the first line of the query in the buffer */ sdsrange(c->querybuf,querylen+2,-1); /* Setup argv array on client structure */ if (argc) { if (c->argv) zfree(c->argv); c->argv = zmalloc(sizeof(robj*)*argc); } /* Create redis objects for all arguments. */ for (c->argc = 0, j = 0; j < argc; j++) { if (sdslen(argv[j])) { c->argv[c->argc] = createObject(OBJ_STRING,argv[j]); c->argc++; } else { sdsfree(argv[j]); } } zfree(argv); return C_OK; } /* Helper function. Trims query buffer to make the function that processes * multi bulk requests idempotent. */ static void setProtocolError(client *c, int pos) { if (server.verbosity <= LL_VERBOSE) { sds client = catClientInfoString(sdsempty(),c); serverLog(LL_VERBOSE, "Protocol error from client: %s", client); sdsfree(client); } c->flags |= CLIENT_CLOSE_AFTER_REPLY; sdsrange(c->querybuf,pos,-1); } int processMultibulkBuffer(client *c) { char *newline = NULL; int pos = 0, ok; long long ll; if (c->multibulklen == 0) { /* The client should have been reset */ serverAssertWithInfo(c,NULL,c->argc == 0); /* Multi bulk length cannot be read without a \r\n */ newline = strchr(c->querybuf,'\r'); if (newline == NULL) { if (sdslen(c->querybuf) > PROTO_INLINE_MAX_SIZE) { addReplyError(c,"Protocol error: too big mbulk count string"); setProtocolError(c,0); } return C_ERR; } /* Buffer should also contain \n */ if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2)) return C_ERR; /* We know for sure there is a whole line since newline != NULL, * so go ahead and find out the multi bulk length. */ serverAssertWithInfo(c,NULL,c->querybuf[0] == '*'); ok = string2ll(c->querybuf+1,newline-(c->querybuf+1),&ll); if (!ok || ll > 1024*1024) { addReplyError(c,"Protocol error: invalid multibulk length"); setProtocolError(c,pos); return C_ERR; } pos = (newline-c->querybuf)+2; if (ll <= 0) { sdsrange(c->querybuf,pos,-1); return C_OK; } c->multibulklen = ll; /* Setup argv array on client structure */ if (c->argv) zfree(c->argv); c->argv = zmalloc(sizeof(robj*)*c->multibulklen); } serverAssertWithInfo(c,NULL,c->multibulklen > 0); while(c->multibulklen) { /* Read bulk length if unknown */ if (c->bulklen == -1) { newline = strchr(c->querybuf+pos,'\r'); if (newline == NULL) { if (sdslen(c->querybuf) > PROTO_INLINE_MAX_SIZE) { addReplyError(c, "Protocol error: too big bulk count string"); setProtocolError(c,0); return C_ERR; } break; } /* Buffer should also contain \n */ if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2)) break; if (c->querybuf[pos] != '$') { addReplyErrorFormat(c, "Protocol error: expected '$', got '%c'", c->querybuf[pos]); setProtocolError(c,pos); return C_ERR; } ok = string2ll(c->querybuf+pos+1,newline-(c->querybuf+pos+1),&ll); if (!ok || ll < 0 || ll > 512*1024*1024) { addReplyError(c,"Protocol error: invalid bulk length"); setProtocolError(c,pos); return C_ERR; } pos += newline-(c->querybuf+pos)+2; if (ll >= PROTO_MBULK_BIG_ARG) { size_t qblen; /* If we are going to read a large object from network * try to make it likely that it will start at c->querybuf * boundary so that we can optimize object creation * avoiding a large copy of data. */ sdsrange(c->querybuf,pos,-1); pos = 0; qblen = sdslen(c->querybuf); /* Hint the sds library about the amount of bytes this string is * going to contain. */ if (qblen < (size_t)ll+2) c->querybuf = sdsMakeRoomFor(c->querybuf,ll+2-qblen); } c->bulklen = ll; } /* Read bulk argument */ if (sdslen(c->querybuf)-pos < (unsigned)(c->bulklen+2)) { /* Not enough data (+2 == trailing \r\n) */ break; } else { /* Optimization: if the buffer contains JUST our bulk element * instead of creating a new object by *copying* the sds we * just use the current sds string. */ if (pos == 0 && c->bulklen >= PROTO_MBULK_BIG_ARG && (signed) sdslen(c->querybuf) == c->bulklen+2) { c->argv[c->argc++] = createObject(OBJ_STRING,c->querybuf); sdsIncrLen(c->querybuf,-2); /* remove CRLF */ /* Assume that if we saw a fat argument we'll see another one * likely... */ c->querybuf = sdsnewlen(NULL,c->bulklen+2); sdsclear(c->querybuf); pos = 0; } else { c->argv[c->argc++] = createStringObject(c->querybuf+pos,c->bulklen); pos += c->bulklen+2; } c->bulklen = -1; c->multibulklen--; } } /* Trim to pos */ if (pos) sdsrange(c->querybuf,pos,-1); /* We're done when c->multibulk == 0 */ if (c->multibulklen == 0) return C_OK; /* Still not read to process the command */ return C_ERR; } void processInputBuffer(client *c) { server.current_client = c; /* Keep processing while there is something in the input buffer */ while(sdslen(c->querybuf)) { /* Return if clients are paused. */ if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break; /* Immediately abort if the client is in the middle of something. */ if (c->flags & CLIENT_BLOCKED) break; /* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is * written to the client. Make sure to not let the reply grow after * this flag has been set (i.e. don't process more commands). * * The same applies for clients we want to terminate ASAP. */ if (c->flags & (CLIENT_CLOSE_AFTER_REPLY|CLIENT_CLOSE_ASAP)) break; /* Determine request type when unknown. */ if (!c->reqtype) { if (c->querybuf[0] == '*') { c->reqtype = PROTO_REQ_MULTIBULK; } else { c->reqtype = PROTO_REQ_INLINE; } } if (c->reqtype == PROTO_REQ_INLINE) { if (processInlineBuffer(c) != C_OK) break; } else if (c->reqtype == PROTO_REQ_MULTIBULK) { if (processMultibulkBuffer(c) != C_OK) break; } else { serverPanic("Unknown request type"); } /* Multibulk processing could see a <= 0 length. */ if (c->argc == 0) { resetClient(c); } else { /* Only reset the client when the command was executed. */ if (processCommand(c) == C_OK) resetClient(c); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) break; } } server.current_client = NULL; } void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) { client *c = (client*) privdata; int nread, readlen; size_t qblen; UNUSED(el); UNUSED(mask); readlen = PROTO_IOBUF_LEN; /* If this is a multi bulk request, and we are processing a bulk reply * that is large enough, try to maximize the probability that the query * buffer contains exactly the SDS string representing the object, even * at the risk of requiring more read(2) calls. This way the function * processMultiBulkBuffer() can avoid copying buffers to create the * Redis Object representing the argument. */ if (c->reqtype == PROTO_REQ_MULTIBULK && c->multibulklen && c->bulklen != -1 && c->bulklen >= PROTO_MBULK_BIG_ARG) { int remaining = (unsigned)(c->bulklen+2)-sdslen(c->querybuf); if (remaining < readlen) readlen = remaining; } qblen = sdslen(c->querybuf); if (c->querybuf_peak < qblen) c->querybuf_peak = qblen; c->querybuf = sdsMakeRoomFor(c->querybuf, readlen); nread = read(fd, c->querybuf+qblen, readlen); if (nread == -1) { if (errno == EAGAIN) { return; } else { serverLog(LL_VERBOSE, "Reading from client: %s",strerror(errno)); freeClient(c); return; } } else if (nread == 0) { serverLog(LL_VERBOSE, "Client closed connection"); freeClient(c); return; } sdsIncrLen(c->querybuf,nread); c->lastinteraction = server.unixtime; if (c->flags & CLIENT_MASTER) c->reploff += nread; server.stat_net_input_bytes += nread; if (sdslen(c->querybuf) > server.client_max_querybuf_len) { sds ci = catClientInfoString(sdsempty(),c), bytes = sdsempty(); bytes = sdscatrepr(bytes,c->querybuf,64); serverLog(LL_WARNING,"Closing client that reached max query buffer length: %s (qbuf initial bytes: %s)", ci, bytes); sdsfree(ci); sdsfree(bytes); freeClient(c); return; } processInputBuffer(c); } void getClientsMaxBuffers(unsigned long *longest_output_list, unsigned long *biggest_input_buffer) { client *c; listNode *ln; listIter li; unsigned long lol = 0, bib = 0; listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { c = listNodeValue(ln); if (listLength(c->reply) > lol) lol = listLength(c->reply); if (sdslen(c->querybuf) > bib) bib = sdslen(c->querybuf); } *longest_output_list = lol; *biggest_input_buffer = bib; } /* A Redis "Peer ID" is a colon separated ip:port pair. * For IPv4 it's in the form x.y.z.k:port, example: "127.0.0.1:1234". * For IPv6 addresses we use [] around the IP part, like in "[::1]:1234". * For Unix sockets we use path:0, like in "/tmp/redis:0". * * A Peer ID always fits inside a buffer of NET_PEER_ID_LEN bytes, including * the null term. * * On failure the function still populates 'peerid' with the "?:0" string * in case you want to relax error checking or need to display something * anyway (see anetPeerToString implementation for more info). */ void genClientPeerId(client *client, char *peerid, size_t peerid_len) { if (client->flags & CLIENT_UNIX_SOCKET) { /* Unix socket client. */ snprintf(peerid,peerid_len,"%s:0",server.unixsocket); } else { /* TCP client. */ anetFormatPeer(client->fd,peerid,peerid_len); } } /* This function returns the client peer id, by creating and caching it * if client->peerid is NULL, otherwise returning the cached value. * The Peer ID never changes during the life of the client, however it * is expensive to compute. */ char *getClientPeerId(client *c) { char peerid[NET_PEER_ID_LEN]; if (c->peerid == NULL) { genClientPeerId(c,peerid,sizeof(peerid)); c->peerid = sdsnew(peerid); } return c->peerid; } /* Concatenate a string representing the state of a client in an human * readable format, into the sds string 's'. */ sds catClientInfoString(sds s, client *client) { char flags[16], events[3], *p; int emask; p = flags; if (client->flags & CLIENT_SLAVE) { if (client->flags & CLIENT_MONITOR) *p++ = 'O'; else *p++ = 'S'; } if (client->flags & CLIENT_MASTER) *p++ = 'M'; if (client->flags & CLIENT_MULTI) *p++ = 'x'; if (client->flags & CLIENT_BLOCKED) *p++ = 'b'; if (client->flags & CLIENT_DIRTY_CAS) *p++ = 'd'; if (client->flags & CLIENT_CLOSE_AFTER_REPLY) *p++ = 'c'; if (client->flags & CLIENT_UNBLOCKED) *p++ = 'u'; if (client->flags & CLIENT_CLOSE_ASAP) *p++ = 'A'; if (client->flags & CLIENT_UNIX_SOCKET) *p++ = 'U'; if (client->flags & CLIENT_READONLY) *p++ = 'r'; if (p == flags) *p++ = 'N'; *p++ = '\0'; emask = client->fd == -1 ? 0 : aeGetFileEvents(server.el,client->fd); p = events; if (emask & AE_READABLE) *p++ = 'r'; if (emask & AE_WRITABLE) *p++ = 'w'; *p = '\0'; return sdscatfmt(s, "id=%U addr=%s fd=%i name=%s age=%I idle=%I flags=%s db=%i sub=%i psub=%i multi=%i qbuf=%U qbuf-free=%U obl=%U oll=%U omem=%U events=%s cmd=%s", (unsigned long long) client->id, getClientPeerId(client), client->fd, client->name ? (char*)client->name->ptr : "", (long long)(server.unixtime - client->ctime), (long long)(server.unixtime - client->lastinteraction), flags, client->db->id, (int) dictSize(client->pubsub_channels), (int) listLength(client->pubsub_patterns), (client->flags & CLIENT_MULTI) ? client->mstate.count : -1, (unsigned long long) sdslen(client->querybuf), (unsigned long long) sdsavail(client->querybuf), (unsigned long long) client->bufpos, (unsigned long long) listLength(client->reply), (unsigned long long) getClientOutputBufferMemoryUsage(client), events, client->lastcmd ? client->lastcmd->name : "NULL"); } sds getAllClientsInfoString(void) { listNode *ln; listIter li; client *client; sds o = sdsnewlen(NULL,200*listLength(server.clients)); sdsclear(o); listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { client = listNodeValue(ln); o = catClientInfoString(o,client); o = sdscatlen(o,"\n",1); } return o; } void clientCommand(client *c) { listNode *ln; listIter li; client *client; if (!strcasecmp(c->argv[1]->ptr,"list") && c->argc == 2) { /* CLIENT LIST */ sds o = getAllClientsInfoString(); addReplyBulkCBuffer(c,o,sdslen(o)); sdsfree(o); } else if (!strcasecmp(c->argv[1]->ptr,"reply") && c->argc == 3) { /* CLIENT REPLY ON|OFF|SKIP */ if (!strcasecmp(c->argv[2]->ptr,"on")) { c->flags &= ~(CLIENT_REPLY_SKIP|CLIENT_REPLY_OFF); addReply(c,shared.ok); } else if (!strcasecmp(c->argv[2]->ptr,"off")) { c->flags |= CLIENT_REPLY_OFF; } else if (!strcasecmp(c->argv[2]->ptr,"skip")) { if (!(c->flags & CLIENT_REPLY_OFF)) c->flags |= CLIENT_REPLY_SKIP_NEXT; } else { addReply(c,shared.syntaxerr); return; } } else if (!strcasecmp(c->argv[1]->ptr,"kill")) { /* CLIENT KILL <ip:port> * CLIENT KILL <option> [value] ... <option> [value] */ char *addr = NULL; int type = -1; uint64_t id = 0; int skipme = 1; int killed = 0, close_this_client = 0; if (c->argc == 3) { /* Old style syntax: CLIENT KILL <addr> */ addr = c->argv[2]->ptr; skipme = 0; /* With the old form, you can kill yourself. */ } else if (c->argc > 3) { int i = 2; /* Next option index. */ /* New style syntax: parse options. */ while(i < c->argc) { int moreargs = c->argc > i+1; if (!strcasecmp(c->argv[i]->ptr,"id") && moreargs) { long long tmp; if (getLongLongFromObjectOrReply(c,c->argv[i+1],&tmp,NULL) != C_OK) return; id = tmp; } else if (!strcasecmp(c->argv[i]->ptr,"type") && moreargs) { type = getClientTypeByName(c->argv[i+1]->ptr); if (type == -1) { addReplyErrorFormat(c,"Unknown client type '%s'", (char*) c->argv[i+1]->ptr); return; } } else if (!strcasecmp(c->argv[i]->ptr,"addr") && moreargs) { addr = c->argv[i+1]->ptr; } else if (!strcasecmp(c->argv[i]->ptr,"skipme") && moreargs) { if (!strcasecmp(c->argv[i+1]->ptr,"yes")) { skipme = 1; } else if (!strcasecmp(c->argv[i+1]->ptr,"no")) { skipme = 0; } else { addReply(c,shared.syntaxerr); return; } } else { addReply(c,shared.syntaxerr); return; } i += 2; } } else { addReply(c,shared.syntaxerr); return; } /* Iterate clients killing all the matching clients. */ listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { client = listNodeValue(ln); if (addr && strcmp(getClientPeerId(client),addr) != 0) continue; if (type != -1 && getClientType(client) != type) continue; if (id != 0 && client->id != id) continue; if (c == client && skipme) continue; /* Kill it. */ if (c == client) { close_this_client = 1; } else { freeClient(client); } killed++; } /* Reply according to old/new format. */ if (c->argc == 3) { if (killed == 0) addReplyError(c,"No such client"); else addReply(c,shared.ok); } else { addReplyLongLong(c,killed); } /* If this client has to be closed, flag it as CLOSE_AFTER_REPLY * only after we queued the reply to its output buffers. */ if (close_this_client) c->flags |= CLIENT_CLOSE_AFTER_REPLY; } else if (!strcasecmp(c->argv[1]->ptr,"setname") && c->argc == 3) { int j, len = sdslen(c->argv[2]->ptr); char *p = c->argv[2]->ptr; /* Setting the client name to an empty string actually removes * the current name. */ if (len == 0) { if (c->name) decrRefCount(c->name); c->name = NULL; addReply(c,shared.ok); return; } /* Otherwise check if the charset is ok. We need to do this otherwise * CLIENT LIST format will break. You should always be able to * split by space to get the different fields. */ for (j = 0; j < len; j++) { if (p[j] < '!' || p[j] > '~') { /* ASCII is assumed. */ addReplyError(c, "Client names cannot contain spaces, " "newlines or special characters."); return; } } if (c->name) decrRefCount(c->name); c->name = c->argv[2]; incrRefCount(c->name); addReply(c,shared.ok); } else if (!strcasecmp(c->argv[1]->ptr,"getname") && c->argc == 2) { if (c->name) addReplyBulk(c,c->name); else addReply(c,shared.nullbulk); } else if (!strcasecmp(c->argv[1]->ptr,"pause") && c->argc == 3) { long long duration; if (getTimeoutFromObjectOrReply(c,c->argv[2],&duration,UNIT_MILLISECONDS) != C_OK) return; pauseClients(duration); addReply(c,shared.ok); } else { addReplyError(c, "Syntax error, try CLIENT (LIST | KILL | GETNAME | SETNAME | PAUSE | REPLY)"); } } /* This callback is bound to POST and "Host:" command names. Those are not * really commands, but are used in security attacks in order to talk to * Redis instances via HTTP, with a technique called "cross protocol scripting" * which exploits the fact that services like Redis will discard invalid * HTTP headers and will process what follows. * * As a protection against this attack, Redis will terminate the connection * when a POST or "Host:" header is seen, and will log the event from * time to time (to avoid creating a DOS as a result of too many logs). */ void securityWarningCommand(client *c) { static time_t logged_time; time_t now = time(NULL); if (labs(now-logged_time) > 60) { serverLog(LL_WARNING,"Possible SECURITY ATTACK detected. It looks like somebody is sending POST or Host: commands to Redis. This is likely due to an attacker attempting to use Cross Protocol Scripting to compromise your Redis instance. Connection aborted."); logged_time = now; } freeClientAsync(c); } /* Rewrite the command vector of the client. All the new objects ref count * is incremented. The old command vector is freed, and the old objects * ref count is decremented. */ void rewriteClientCommandVector(client *c, int argc, ...) { va_list ap; int j; robj **argv; /* The new argument vector */ argv = zmalloc(sizeof(robj*)*argc); va_start(ap,argc); for (j = 0; j < argc; j++) { robj *a; a = va_arg(ap, robj*); argv[j] = a; incrRefCount(a); } /* We free the objects in the original vector at the end, so we are * sure that if the same objects are reused in the new vector the * refcount gets incremented before it gets decremented. */ for (j = 0; j < c->argc; j++) decrRefCount(c->argv[j]); zfree(c->argv); /* Replace argv and argc with our new versions. */ c->argv = argv; c->argc = argc; c->cmd = lookupCommandOrOriginal(c->argv[0]->ptr); serverAssertWithInfo(c,NULL,c->cmd != NULL); va_end(ap); } /* Completely replace the client command vector with the provided one. */ void replaceClientCommandVector(client *c, int argc, robj **argv) { freeClientArgv(c); zfree(c->argv); c->argv = argv; c->argc = argc; c->cmd = lookupCommandOrOriginal(c->argv[0]->ptr); serverAssertWithInfo(c,NULL,c->cmd != NULL); } /* Rewrite a single item in the command vector. * The new val ref count is incremented, and the old decremented. * * It is possible to specify an argument over the current size of the * argument vector: in this case the array of objects gets reallocated * and c->argc set to the max value. However it's up to the caller to * * 1. Make sure there are no "holes" and all the arguments are set. * 2. If the original argument vector was longer than the one we * want to end with, it's up to the caller to set c->argc and * free the no longer used objects on c->argv. */ void rewriteClientCommandArgument(client *c, int i, robj *newval) { robj *oldval; if (i >= c->argc) { c->argv = zrealloc(c->argv,sizeof(robj*)*(i+1)); c->argc = i+1; c->argv[i] = NULL; } oldval = c->argv[i]; c->argv[i] = newval; incrRefCount(newval); if (oldval) decrRefCount(oldval); /* If this is the command name make sure to fix c->cmd. */ if (i == 0) { c->cmd = lookupCommandOrOriginal(c->argv[0]->ptr); serverAssertWithInfo(c,NULL,c->cmd != NULL); } } /* This function returns the number of bytes that Redis is virtually * using to store the reply still not read by the client. * It is "virtual" since the reply output list may contain objects that * are shared and are not really using additional memory. * * The function returns the total sum of the length of all the objects * stored in the output list, plus the memory used to allocate every * list node. The static reply buffer is not taken into account since it * is allocated anyway. * * Note: this function is very fast so can be called as many time as * the caller wishes. The main usage of this function currently is * enforcing the client output length limits. */ unsigned long getClientOutputBufferMemoryUsage(client *c) { unsigned long list_item_size = sizeof(listNode)+sizeof(robj); return c->reply_bytes + (list_item_size*listLength(c->reply)); } /* Get the class of a client, used in order to enforce limits to different * classes of clients. * * The function will return one of the following: * CLIENT_TYPE_NORMAL -> Normal client * CLIENT_TYPE_SLAVE -> Slave or client executing MONITOR command * CLIENT_TYPE_PUBSUB -> Client subscribed to Pub/Sub channels * CLIENT_TYPE_MASTER -> The client representing our replication master. */ int getClientType(client *c) { if (c->flags & CLIENT_MASTER) return CLIENT_TYPE_MASTER; if ((c->flags & CLIENT_SLAVE) && !(c->flags & CLIENT_MONITOR)) return CLIENT_TYPE_SLAVE; if (c->flags & CLIENT_PUBSUB) return CLIENT_TYPE_PUBSUB; return CLIENT_TYPE_NORMAL; } int getClientTypeByName(char *name) { if (!strcasecmp(name,"normal")) return CLIENT_TYPE_NORMAL; else if (!strcasecmp(name,"slave")) return CLIENT_TYPE_SLAVE; else if (!strcasecmp(name,"pubsub")) return CLIENT_TYPE_PUBSUB; else if (!strcasecmp(name,"master")) return CLIENT_TYPE_MASTER; else return -1; } char *getClientTypeName(int class) { switch(class) { case CLIENT_TYPE_NORMAL: return "normal"; case CLIENT_TYPE_SLAVE: return "slave"; case CLIENT_TYPE_PUBSUB: return "pubsub"; case CLIENT_TYPE_MASTER: return "master"; default: return NULL; } } /* The function checks if the client reached output buffer soft or hard * limit, and also update the state needed to check the soft limit as * a side effect. * * Return value: non-zero if the client reached the soft or the hard limit. * Otherwise zero is returned. */ int checkClientOutputBufferLimits(client *c) { int soft = 0, hard = 0, class; unsigned long used_mem = getClientOutputBufferMemoryUsage(c); class = getClientType(c); /* For the purpose of output buffer limiting, masters are handled * like normal clients. */ if (class == CLIENT_TYPE_MASTER) class = CLIENT_TYPE_NORMAL; if (server.client_obuf_limits[class].hard_limit_bytes && used_mem >= server.client_obuf_limits[class].hard_limit_bytes) hard = 1; if (server.client_obuf_limits[class].soft_limit_bytes && used_mem >= server.client_obuf_limits[class].soft_limit_bytes) soft = 1; /* We need to check if the soft limit is reached continuously for the * specified amount of seconds. */ if (soft) { if (c->obuf_soft_limit_reached_time == 0) { c->obuf_soft_limit_reached_time = server.unixtime; soft = 0; /* First time we see the soft limit reached */ } else { time_t elapsed = server.unixtime - c->obuf_soft_limit_reached_time; if (elapsed <= server.client_obuf_limits[class].soft_limit_seconds) { soft = 0; /* The client still did not reached the max number of seconds for the soft limit to be considered reached. */ } } } else { c->obuf_soft_limit_reached_time = 0; } return soft || hard; } /* Asynchronously close a client if soft or hard limit is reached on the * output buffer size. The caller can check if the client will be closed * checking if the client CLIENT_CLOSE_ASAP flag is set. * * Note: we need to close the client asynchronously because this function is * called from contexts where the client can't be freed safely, i.e. from the * lower level functions pushing data inside the client output buffers. */ void asyncCloseClientOnOutputBufferLimitReached(client *c) { serverAssert(c->reply_bytes < SIZE_MAX-(1024*64)); if (c->reply_bytes == 0 || c->flags & CLIENT_CLOSE_ASAP) return; if (checkClientOutputBufferLimits(c)) { sds client = catClientInfoString(sdsempty(),c); freeClientAsync(c); serverLog(LL_WARNING,"Client %s scheduled to be closed ASAP for overcoming of output buffer limits.", client); sdsfree(client); } } /* Helper function used by freeMemoryIfNeeded() in order to flush slaves * output buffers without returning control to the event loop. * This is also called by SHUTDOWN for a best-effort attempt to send * slaves the latest writes. */ void flushSlavesOutputBuffers(void) { listIter li; listNode *ln; listRewind(server.slaves,&li); while((ln = listNext(&li))) { client *slave = listNodeValue(ln); int events; /* Note that the following will not flush output buffers of slaves * in STATE_ONLINE but having put_online_on_ack set to true: in this * case the writable event is never installed, since the purpose * of put_online_on_ack is to postpone the moment it is installed. * This is what we want since slaves in this state should not receive * writes before the first ACK. */ events = aeGetFileEvents(server.el,slave->fd); if (events & AE_WRITABLE && slave->replstate == SLAVE_STATE_ONLINE && clientHasPendingReplies(slave)) { writeToClient(slave->fd,slave,0); } } } /* Pause clients up to the specified unixtime (in ms). While clients * are paused no command is processed from clients, so the data set can't * change during that time. * * However while this function pauses normal and Pub/Sub clients, slaves are * still served, so this function can be used on server upgrades where it is * required that slaves process the latest bytes from the replication stream * before being turned to masters. * * This function is also internally used by Redis Cluster for the manual * failover procedure implemented by CLUSTER FAILOVER. * * The function always succeed, even if there is already a pause in progress. * In such a case, the pause is extended if the duration is more than the * time left for the previous duration. However if the duration is smaller * than the time left for the previous pause, no change is made to the * left duration. */ void pauseClients(mstime_t end) { if (!server.clients_paused || end > server.clients_pause_end_time) server.clients_pause_end_time = end; server.clients_paused = 1; } /* Return non-zero if clients are currently paused. As a side effect the * function checks if the pause time was reached and clear it. */ int clientsArePaused(void) { if (server.clients_paused && server.clients_pause_end_time < server.mstime) { listNode *ln; listIter li; client *c; server.clients_paused = 0; /* Put all the clients in the unblocked clients queue in order to * force the re-processing of the input buffer if any. */ listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { c = listNodeValue(ln); /* Don't touch slaves and blocked clients. The latter pending * requests be processed when unblocked. */ if (c->flags & (CLIENT_SLAVE|CLIENT_BLOCKED)) continue; c->flags |= CLIENT_UNBLOCKED; listAddNodeTail(server.unblocked_clients,c); } } return server.clients_paused; } /* This function is called by Redis in order to process a few events from * time to time while blocked into some not interruptible operation. * This allows to reply to clients with the -LOADING error while loading the * data set at startup or after a full resynchronization with the master * and so forth. * * It calls the event loop in order to process a few events. Specifically we * try to call the event loop 4 times as long as we receive acknowledge that * some event was processed, in order to go forward with the accept, read, * write, close sequence needed to serve a client. * * The function returns the total number of events processed. */ int processEventsWhileBlocked(void) { int iterations = 4; /* See the function top-comment. */ int count = 0; while (iterations--) { int events = 0; events += aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT); events += handleClientsWithPendingWrites(); if (!events) break; count += events; } return count; }
./CrossVul/dataset_final_sorted/CWE-254/c/good_4872_0
crossvul-cpp_data_bad_5205_4
/** @file bzrtpTests.c @author Johan Pascal @copyright Copyright (C) 2014 Belledonne Communications, Grenoble, France 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdio.h> #include "CUnit/Basic.h" #include "bzrtpCryptoTest.h" #include "bzrtpParserTest.h" #include "typedef.h" #include "testUtils.h" #ifdef HAVE_LIBXML2 #include <libxml/parser.h> #endif int main(int argc, char *argv[] ) { int i, fails_count=0; CU_pSuite cryptoUtilsTestSuite, parserTestSuite; CU_pSuite *suites[] = { &cryptoUtilsTestSuite, &parserTestSuite, NULL }; if (argc>1) { if (argv[1][0] == '-') { if (strcmp(argv[1], "-verbose") == 0) { verbose = 1; } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } #ifdef HAVE_LIBXML2 xmlInitParser(); #endif /* initialize the CUnit test registry */ if (CUE_SUCCESS != CU_initialize_registry()) { return CU_get_error(); } /* Add the cryptoUtils suite to the registry */ cryptoUtilsTestSuite = CU_add_suite("Bzrtp Crypto Utils", NULL, NULL); CU_add_test(cryptoUtilsTestSuite, "zrtpKDF", test_zrtpKDF); CU_add_test(cryptoUtilsTestSuite, "CRC32", test_CRC32); CU_add_test(cryptoUtilsTestSuite, "algo agreement", test_algoAgreement); CU_add_test(cryptoUtilsTestSuite, "context algo setter and getter", test_algoSetterGetter); CU_add_test(cryptoUtilsTestSuite, "adding mandatory crypto algorithms if needed", test_addMandatoryCryptoTypesIfNeeded); /* Add the parser suite to the registry */ parserTestSuite = CU_add_suite("Bzrtp ZRTP Packet Parser", NULL, NULL); CU_add_test(parserTestSuite, "Parse", test_parser); CU_add_test(parserTestSuite, "Parse Exchange", test_parserComplete); CU_add_test(parserTestSuite, "State machine", test_stateMachine); /* Run all suites */ for(i=0; suites[i]; i++){ CU_basic_run_suite(*suites[i]); fails_count += CU_get_number_of_tests_failed(); } /* cleanup the CUnit registry */ CU_cleanup_registry(); #ifdef HAVE_LIBXML2 /* cleanup libxml2 */ xmlCleanupParser(); #endif return (fails_count == 0 ? 0 : 1); }
./CrossVul/dataset_final_sorted/CWE-254/c/bad_5205_4
crossvul-cpp_data_good_5010_0
/* * Flexible mmap layout support * * Based on code by Ingo Molnar and Andi Kleen, copyrighted * as follows: * * Copyright 2003-2009 Red Hat Inc. * All Rights Reserved. * Copyright 2005 Andi Kleen, SUSE Labs. * Copyright 2007 Jiri Kosina, SUSE Labs. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/personality.h> #include <linux/mm.h> #include <linux/random.h> #include <linux/limits.h> #include <linux/sched.h> #include <asm/elf.h> struct va_alignment __read_mostly va_align = { .flags = -1, }; static unsigned long stack_maxrandom_size(void) { unsigned long max = 0; if ((current->flags & PF_RANDOMIZE) && !(current->personality & ADDR_NO_RANDOMIZE)) { max = ((-1UL) & STACK_RND_MASK) << PAGE_SHIFT; } return max; } /* * Top of mmap area (just below the process stack). * * Leave an at least ~128 MB hole with possible stack randomization. */ #define MIN_GAP (128*1024*1024UL + stack_maxrandom_size()) #define MAX_GAP (TASK_SIZE/6*5) static int mmap_is_legacy(void) { if (current->personality & ADDR_COMPAT_LAYOUT) return 1; if (rlimit(RLIMIT_STACK) == RLIM_INFINITY) return 1; return sysctl_legacy_va_layout; } unsigned long arch_mmap_rnd(void) { unsigned long rnd; if (mmap_is_ia32()) #ifdef CONFIG_COMPAT rnd = (unsigned long)get_random_int() & ((1 << mmap_rnd_compat_bits) - 1); #else rnd = (unsigned long)get_random_int() & ((1 << mmap_rnd_bits) - 1); #endif else rnd = (unsigned long)get_random_int() & ((1 << mmap_rnd_bits) - 1); return rnd << PAGE_SHIFT; } static unsigned long mmap_base(unsigned long rnd) { unsigned long gap = rlimit(RLIMIT_STACK); if (gap < MIN_GAP) gap = MIN_GAP; else if (gap > MAX_GAP) gap = MAX_GAP; return PAGE_ALIGN(TASK_SIZE - gap - rnd); } /* * This function, called very early during the creation of a new * process VM image, sets up which VM layout function to use: */ void arch_pick_mmap_layout(struct mm_struct *mm) { unsigned long random_factor = 0UL; if (current->flags & PF_RANDOMIZE) random_factor = arch_mmap_rnd(); mm->mmap_legacy_base = TASK_UNMAPPED_BASE + random_factor; if (mmap_is_legacy()) { mm->mmap_base = mm->mmap_legacy_base; mm->get_unmapped_area = arch_get_unmapped_area; } else { mm->mmap_base = mmap_base(random_factor); mm->get_unmapped_area = arch_get_unmapped_area_topdown; } } const char *arch_vma_name(struct vm_area_struct *vma) { if (vma->vm_flags & VM_MPX) return "[mpx]"; return NULL; }
./CrossVul/dataset_final_sorted/CWE-254/c/good_5010_0
crossvul-cpp_data_bad_1548_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-254/c/bad_1548_0
crossvul-cpp_data_good_5328_0
/* * Copyright (c) 2012 David Vossel <davidvossel@gmail.com> * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <crm_internal.h> #include <glib.h> #include <unistd.h> #include <crm/crm.h> #include <crm/msg_xml.h> #include <crm/crm.h> #include <crm/msg_xml.h> #include <crm/common/mainloop.h> #include <lrmd_private.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <arpa/inet.h> #ifdef HAVE_GNUTLS_GNUTLS_H # define LRMD_REMOTE_AUTH_TIMEOUT 10000 gnutls_psk_server_credentials_t psk_cred_s; gnutls_dh_params_t dh_params; static int ssock = -1; extern int lrmd_call_id; static void debug_log(int level, const char *str) { fputs(str, stderr); } static int lrmd_remote_client_msg(gpointer data) { int id = 0; int rc = 0; int disconnected = 0; xmlNode *request = NULL; crm_client_t *client = data; if (client->remote->tls_handshake_complete == FALSE) { int rc = 0; /* Muliple calls to handshake will be required, this callback * will be invoked once the client sends more handshake data. */ do { rc = gnutls_handshake(*client->remote->tls_session); if (rc < 0 && rc != GNUTLS_E_AGAIN) { crm_err("Remote lrmd tls handshake failed"); return -1; } } while (rc == GNUTLS_E_INTERRUPTED); if (rc == 0) { crm_debug("Remote lrmd tls handshake completed"); client->remote->tls_handshake_complete = TRUE; if (client->remote->auth_timeout) { g_source_remove(client->remote->auth_timeout); } client->remote->auth_timeout = 0; /* Alert other clients of the new connection */ notify_of_new_client(client); } return 0; } rc = crm_remote_ready(client->remote, 0); if (rc == 0) { /* no msg to read */ return 0; } else if (rc < 0) { crm_info("Client disconnected during remote client read"); return -1; } crm_remote_recv(client->remote, -1, &disconnected); request = crm_remote_parse_buffer(client->remote); while (request) { crm_element_value_int(request, F_LRMD_REMOTE_MSG_ID, &id); crm_trace("processing request from remote client with remote msg id %d", id); if (!client->name) { const char *value = crm_element_value(request, F_LRMD_CLIENTNAME); if (value) { client->name = strdup(value); } } lrmd_call_id++; if (lrmd_call_id < 1) { lrmd_call_id = 1; } crm_xml_add(request, F_LRMD_CLIENTID, client->id); crm_xml_add(request, F_LRMD_CLIENTNAME, client->name); crm_xml_add_int(request, F_LRMD_CALLID, lrmd_call_id); process_lrmd_message(client, id, request); free_xml(request); /* process all the messages in the current buffer */ request = crm_remote_parse_buffer(client->remote); } if (disconnected) { crm_info("Client disconnect detected in tls msg dispatcher."); return -1; } return 0; } static void lrmd_remote_client_destroy(gpointer user_data) { crm_client_t *client = user_data; if (client == NULL) { return; } ipc_proxy_remove_provider(client); /* if this is the last remote connection, stop recurring * operations */ if (crm_hash_table_size(client_connections) == 1) { client_disconnect_cleanup(NULL); } crm_notice("LRMD client disconnecting remote client - name: %s id: %s", client->name ? client->name : "<unknown>", client->id); if (client->remote->tls_session) { void *sock_ptr; int csock; sock_ptr = gnutls_transport_get_ptr(*client->remote->tls_session); csock = GPOINTER_TO_INT(sock_ptr); gnutls_bye(*client->remote->tls_session, GNUTLS_SHUT_RDWR); gnutls_deinit(*client->remote->tls_session); gnutls_free(client->remote->tls_session); close(csock); } lrmd_client_destroy(client); return; } static gboolean lrmd_auth_timeout_cb(gpointer data) { crm_client_t *client = data; client->remote->auth_timeout = 0; if (client->remote->tls_handshake_complete == TRUE) { return FALSE; } mainloop_del_fd(client->remote->source); client->remote->source = NULL; crm_err("Remote client authentication timed out"); return FALSE; } /* Convert a struct sockaddr address to a string, IPv4 and IPv6: */ static char * get_ip_str(const struct sockaddr * sa, char * s, size_t maxlen) { switch(sa->sa_family) { case AF_INET: inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr), s, maxlen); break; case AF_INET6: inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr), s, maxlen); break; default: strncpy(s, "Unknown AF", maxlen); return NULL; } return s; } static int lrmd_remote_listen(gpointer data) { int csock = 0; int flag = 0; unsigned laddr = 0; struct sockaddr addr; gnutls_session_t *session = NULL; crm_client_t *new_client = NULL; static struct mainloop_fd_callbacks lrmd_remote_fd_cb = { .dispatch = lrmd_remote_client_msg, .destroy = lrmd_remote_client_destroy, }; laddr = sizeof(addr); memset(&addr, 0, sizeof(addr)); getsockname(ssock, &addr, &laddr); /* accept the connection */ if (addr.sa_family == AF_INET6) { struct sockaddr_in6 sa; char addr_str[INET6_ADDRSTRLEN]; laddr = sizeof(sa); memset(&sa, 0, sizeof(sa)); csock = accept(ssock, &sa, &laddr); get_ip_str((struct sockaddr *)&sa, addr_str, INET6_ADDRSTRLEN); crm_info("New remote connection from %s", addr_str); } else { struct sockaddr_in sa; char addr_str[INET_ADDRSTRLEN]; laddr = sizeof(sa); memset(&sa, 0, sizeof(sa)); csock = accept(ssock, &sa, &laddr); get_ip_str((struct sockaddr *)&sa, addr_str, INET_ADDRSTRLEN); crm_info("New remote connection from %s", addr_str); } if (csock == -1) { crm_err("accept socket failed"); return TRUE; } if ((flag = fcntl(csock, F_GETFL)) >= 0) { if (fcntl(csock, F_SETFL, flag | O_NONBLOCK) < 0) { crm_err("fcntl() write failed"); close(csock); return TRUE; } } else { crm_err("fcntl() read failed"); close(csock); return TRUE; } session = create_psk_tls_session(csock, GNUTLS_SERVER, psk_cred_s); if (session == NULL) { crm_err("TLS session creation failed"); close(csock); return TRUE; } new_client = calloc(1, sizeof(crm_client_t)); new_client->remote = calloc(1, sizeof(crm_remote_t)); new_client->kind = CRM_CLIENT_TLS; new_client->remote->tls_session = session; new_client->id = crm_generate_uuid(); new_client->remote->auth_timeout = g_timeout_add(LRMD_REMOTE_AUTH_TIMEOUT, lrmd_auth_timeout_cb, new_client); crm_notice("LRMD client connection established. %p id: %s", new_client, new_client->id); new_client->remote->source = mainloop_add_fd("lrmd-remote-client", G_PRIORITY_DEFAULT, csock, new_client, &lrmd_remote_fd_cb); g_hash_table_insert(client_connections, new_client->id, new_client); return TRUE; } static void lrmd_remote_connection_destroy(gpointer user_data) { crm_notice("Remote tls server disconnected"); return; } static int lrmd_tls_server_key_cb(gnutls_session_t session, const char *username, gnutls_datum_t * key) { return lrmd_tls_set_key(key); } static int bind_and_listen(struct addrinfo *addr) { int optval; int fd; int rc; char buffer[256] = { 0, }; if (addr->ai_family == AF_INET6) { struct sockaddr_in6 *addr_in = (struct sockaddr_in6 *)(void*)addr->ai_addr; inet_ntop(addr->ai_family, &addr_in->sin6_addr, buffer, DIMOF(buffer)); } else { struct sockaddr_in *addr_in = (struct sockaddr_in *)(void*)addr->ai_addr; inet_ntop(addr->ai_family, &addr_in->sin_addr, buffer, DIMOF(buffer)); } crm_trace("Attempting to bind on address %s", buffer); fd = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (fd < 0) { return -1; } /* reuse address */ optval = 1; rc = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (rc < 0) { crm_perror(LOG_INFO, "Couldn't allow the reuse of local addresses by our remote listener, bind address %s", buffer); close(fd); return -1; } if (addr->ai_family == AF_INET6) { optval = 0; rc = setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof(optval)); if (rc < 0) { crm_perror(LOG_INFO, "Couldn't disable IPV6 only on address %s", buffer); close(fd); return -1; } } if (bind(fd, addr->ai_addr, addr->ai_addrlen) != 0) { close(fd); return -1; } if (listen(fd, 10) == -1) { crm_err("Can not start listen on address %s", buffer); close(fd); return -1; } crm_notice("Listening on address %s", buffer); return fd; } int lrmd_init_remote_tls_server(int port) { int rc; int filter; struct addrinfo hints, *res = NULL, *iter; char port_str[16]; static struct mainloop_fd_callbacks remote_listen_fd_callbacks = { .dispatch = lrmd_remote_listen, .destroy = lrmd_remote_connection_destroy, }; crm_notice("Starting a tls listener on port %d.", port); crm_gnutls_global_init(); gnutls_global_set_log_function(debug_log); gnutls_dh_params_init(&dh_params); gnutls_dh_params_generate2(dh_params, 1024); gnutls_psk_allocate_server_credentials(&psk_cred_s); gnutls_psk_set_server_credentials_function(psk_cred_s, lrmd_tls_server_key_cb); gnutls_psk_set_server_dh_params(psk_cred_s, dh_params); memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; /* Only return socket addresses with wildcard INADDR_ANY or IN6ADDR_ANY_INIT */ hints.ai_family = AF_UNSPEC; /* Return IPv6 or IPv4 */ hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; snprintf(port_str, sizeof(port_str), "%d", port); rc = getaddrinfo(NULL, port_str, &hints, &res); if (rc) { crm_err("getaddrinfo: %s", gai_strerror(rc)); return -1; } iter = res; filter = AF_INET6; /* Try IPv6 addresses first, then IPv4 */ while (iter) { if (iter->ai_family == filter) { ssock = bind_and_listen(iter); } if (ssock != -1) { break; } iter = iter->ai_next; if (iter == NULL && filter == AF_INET6) { iter = res; filter = AF_INET; } } if (ssock < 0) { crm_err("unable to bind to address"); goto init_remote_cleanup; } mainloop_add_fd("lrmd-remote", G_PRIORITY_DEFAULT, ssock, NULL, &remote_listen_fd_callbacks); rc = ssock; init_remote_cleanup: if (rc < 0) { close(ssock); ssock = 0; } freeaddrinfo(res); return rc; } void lrmd_tls_server_destroy(void) { if (psk_cred_s) { gnutls_psk_free_server_credentials(psk_cred_s); psk_cred_s = 0; } if (ssock > 0) { close(ssock); ssock = 0; } } #endif
./CrossVul/dataset_final_sorted/CWE-254/c/good_5328_0
crossvul-cpp_data_good_4872_1
/* * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "server.h" #include "cluster.h" #include "slowlog.h" #include "bio.h" #include "latency.h" #include <time.h> #include <signal.h> #include <sys/wait.h> #include <errno.h> #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <arpa/inet.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/uio.h> #include <sys/un.h> #include <limits.h> #include <float.h> #include <math.h> #include <sys/resource.h> #include <sys/utsname.h> #include <locale.h> #include <sys/socket.h> /* Our shared "common" objects */ struct sharedObjectsStruct shared; /* Global vars that are actually used as constants. The following double * values are used for double on-disk serialization, and are initialized * at runtime to avoid strange compiler optimizations. */ double R_Zero, R_PosInf, R_NegInf, R_Nan; /*================================= Globals ================================= */ /* Global vars */ struct redisServer server; /* server global state */ /* Our command table. * * Every entry is composed of the following fields: * * name: a string representing the command name. * function: pointer to the C function implementing the command. * arity: number of arguments, it is possible to use -N to say >= N * sflags: command flags as string. See below for a table of flags. * flags: flags as bitmask. Computed by Redis using the 'sflags' field. * get_keys_proc: an optional function to get key arguments from a command. * This is only used when the following three fields are not * enough to specify what arguments are keys. * first_key_index: first argument that is a key * last_key_index: last argument that is a key * key_step: step to get all the keys from first to last argument. For instance * in MSET the step is two since arguments are key,val,key,val,... * microseconds: microseconds of total execution time for this command. * calls: total number of calls of this command. * * The flags, microseconds and calls fields are computed by Redis and should * always be set to zero. * * Command flags are expressed using strings where every character represents * a flag. Later the populateCommandTable() function will take care of * populating the real 'flags' field using this characters. * * This is the meaning of the flags: * * w: write command (may modify the key space). * r: read command (will never modify the key space). * m: may increase memory usage once called. Don't allow if out of memory. * a: admin command, like SAVE or SHUTDOWN. * p: Pub/Sub related command. * f: force replication of this command, regardless of server.dirty. * s: command not allowed in scripts. * R: random command. Command is not deterministic, that is, the same command * with the same arguments, with the same key space, may have different * results. For instance SPOP and RANDOMKEY are two random commands. * S: Sort command output array if called from script, so that the output * is deterministic. * l: Allow command while loading the database. * t: Allow command while a slave has stale data but is not allowed to * server this data. Normally no command is accepted in this condition * but just a few. * M: Do not automatically propagate the command on MONITOR. * k: Perform an implicit ASKING for this command, so the command will be * accepted in cluster mode if the slot is marked as 'importing'. * F: Fast command: O(1) or O(log(N)) command that should never delay * its execution as long as the kernel scheduler is giving us time. * Note that commands that may trigger a DEL as a side effect (like SET) * are not fast commands. */ struct redisCommand redisCommandTable[] = { {"get",getCommand,2,"rF",0,NULL,1,1,1,0,0}, {"set",setCommand,-3,"wm",0,NULL,1,1,1,0,0}, {"setnx",setnxCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"setex",setexCommand,4,"wm",0,NULL,1,1,1,0,0}, {"psetex",psetexCommand,4,"wm",0,NULL,1,1,1,0,0}, {"append",appendCommand,3,"wm",0,NULL,1,1,1,0,0}, {"strlen",strlenCommand,2,"rF",0,NULL,1,1,1,0,0}, {"del",delCommand,-2,"w",0,NULL,1,-1,1,0,0}, {"exists",existsCommand,-2,"rF",0,NULL,1,-1,1,0,0}, {"setbit",setbitCommand,4,"wm",0,NULL,1,1,1,0,0}, {"getbit",getbitCommand,3,"rF",0,NULL,1,1,1,0,0}, {"bitfield",bitfieldCommand,-2,"wm",0,NULL,1,1,1,0,0}, {"setrange",setrangeCommand,4,"wm",0,NULL,1,1,1,0,0}, {"getrange",getrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"substr",getrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"incr",incrCommand,2,"wmF",0,NULL,1,1,1,0,0}, {"decr",decrCommand,2,"wmF",0,NULL,1,1,1,0,0}, {"mget",mgetCommand,-2,"r",0,NULL,1,-1,1,0,0}, {"rpush",rpushCommand,-3,"wmF",0,NULL,1,1,1,0,0}, {"lpush",lpushCommand,-3,"wmF",0,NULL,1,1,1,0,0}, {"rpushx",rpushxCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"lpushx",lpushxCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"linsert",linsertCommand,5,"wm",0,NULL,1,1,1,0,0}, {"rpop",rpopCommand,2,"wF",0,NULL,1,1,1,0,0}, {"lpop",lpopCommand,2,"wF",0,NULL,1,1,1,0,0}, {"brpop",brpopCommand,-3,"ws",0,NULL,1,1,1,0,0}, {"brpoplpush",brpoplpushCommand,4,"wms",0,NULL,1,2,1,0,0}, {"blpop",blpopCommand,-3,"ws",0,NULL,1,-2,1,0,0}, {"llen",llenCommand,2,"rF",0,NULL,1,1,1,0,0}, {"lindex",lindexCommand,3,"r",0,NULL,1,1,1,0,0}, {"lset",lsetCommand,4,"wm",0,NULL,1,1,1,0,0}, {"lrange",lrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"ltrim",ltrimCommand,4,"w",0,NULL,1,1,1,0,0}, {"lrem",lremCommand,4,"w",0,NULL,1,1,1,0,0}, {"rpoplpush",rpoplpushCommand,3,"wm",0,NULL,1,2,1,0,0}, {"sadd",saddCommand,-3,"wmF",0,NULL,1,1,1,0,0}, {"srem",sremCommand,-3,"wF",0,NULL,1,1,1,0,0}, {"smove",smoveCommand,4,"wF",0,NULL,1,2,1,0,0}, {"sismember",sismemberCommand,3,"rF",0,NULL,1,1,1,0,0}, {"scard",scardCommand,2,"rF",0,NULL,1,1,1,0,0}, {"spop",spopCommand,-2,"wRF",0,NULL,1,1,1,0,0}, {"srandmember",srandmemberCommand,-2,"rR",0,NULL,1,1,1,0,0}, {"sinter",sinterCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sinterstore",sinterstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"sunion",sunionCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sunionstore",sunionstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"sdiff",sdiffCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sdiffstore",sdiffstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"smembers",sinterCommand,2,"rS",0,NULL,1,1,1,0,0}, {"sscan",sscanCommand,-3,"rR",0,NULL,1,1,1,0,0}, {"zadd",zaddCommand,-4,"wmF",0,NULL,1,1,1,0,0}, {"zincrby",zincrbyCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"zrem",zremCommand,-3,"wF",0,NULL,1,1,1,0,0}, {"zremrangebyscore",zremrangebyscoreCommand,4,"w",0,NULL,1,1,1,0,0}, {"zremrangebyrank",zremrangebyrankCommand,4,"w",0,NULL,1,1,1,0,0}, {"zremrangebylex",zremrangebylexCommand,4,"w",0,NULL,1,1,1,0,0}, {"zunionstore",zunionstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0}, {"zinterstore",zinterstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0}, {"zrange",zrangeCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrangebyscore",zrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrevrangebyscore",zrevrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrangebylex",zrangebylexCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrevrangebylex",zrevrangebylexCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zcount",zcountCommand,4,"rF",0,NULL,1,1,1,0,0}, {"zlexcount",zlexcountCommand,4,"rF",0,NULL,1,1,1,0,0}, {"zrevrange",zrevrangeCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zcard",zcardCommand,2,"rF",0,NULL,1,1,1,0,0}, {"zscore",zscoreCommand,3,"rF",0,NULL,1,1,1,0,0}, {"zrank",zrankCommand,3,"rF",0,NULL,1,1,1,0,0}, {"zrevrank",zrevrankCommand,3,"rF",0,NULL,1,1,1,0,0}, {"zscan",zscanCommand,-3,"rR",0,NULL,1,1,1,0,0}, {"hset",hsetCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hsetnx",hsetnxCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hget",hgetCommand,3,"rF",0,NULL,1,1,1,0,0}, {"hmset",hmsetCommand,-4,"wm",0,NULL,1,1,1,0,0}, {"hmget",hmgetCommand,-3,"r",0,NULL,1,1,1,0,0}, {"hincrby",hincrbyCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hincrbyfloat",hincrbyfloatCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hdel",hdelCommand,-3,"wF",0,NULL,1,1,1,0,0}, {"hlen",hlenCommand,2,"rF",0,NULL,1,1,1,0,0}, {"hstrlen",hstrlenCommand,3,"rF",0,NULL,1,1,1,0,0}, {"hkeys",hkeysCommand,2,"rS",0,NULL,1,1,1,0,0}, {"hvals",hvalsCommand,2,"rS",0,NULL,1,1,1,0,0}, {"hgetall",hgetallCommand,2,"r",0,NULL,1,1,1,0,0}, {"hexists",hexistsCommand,3,"rF",0,NULL,1,1,1,0,0}, {"hscan",hscanCommand,-3,"rR",0,NULL,1,1,1,0,0}, {"incrby",incrbyCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"decrby",decrbyCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"incrbyfloat",incrbyfloatCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"getset",getsetCommand,3,"wm",0,NULL,1,1,1,0,0}, {"mset",msetCommand,-3,"wm",0,NULL,1,-1,2,0,0}, {"msetnx",msetnxCommand,-3,"wm",0,NULL,1,-1,2,0,0}, {"randomkey",randomkeyCommand,1,"rR",0,NULL,0,0,0,0,0}, {"select",selectCommand,2,"lF",0,NULL,0,0,0,0,0}, {"move",moveCommand,3,"wF",0,NULL,1,1,1,0,0}, {"rename",renameCommand,3,"w",0,NULL,1,2,1,0,0}, {"renamenx",renamenxCommand,3,"wF",0,NULL,1,2,1,0,0}, {"expire",expireCommand,3,"wF",0,NULL,1,1,1,0,0}, {"expireat",expireatCommand,3,"wF",0,NULL,1,1,1,0,0}, {"pexpire",pexpireCommand,3,"wF",0,NULL,1,1,1,0,0}, {"pexpireat",pexpireatCommand,3,"wF",0,NULL,1,1,1,0,0}, {"keys",keysCommand,2,"rS",0,NULL,0,0,0,0,0}, {"scan",scanCommand,-2,"rR",0,NULL,0,0,0,0,0}, {"dbsize",dbsizeCommand,1,"rF",0,NULL,0,0,0,0,0}, {"auth",authCommand,2,"sltF",0,NULL,0,0,0,0,0}, {"ping",pingCommand,-1,"tF",0,NULL,0,0,0,0,0}, {"echo",echoCommand,2,"F",0,NULL,0,0,0,0,0}, {"save",saveCommand,1,"as",0,NULL,0,0,0,0,0}, {"bgsave",bgsaveCommand,-1,"a",0,NULL,0,0,0,0,0}, {"bgrewriteaof",bgrewriteaofCommand,1,"a",0,NULL,0,0,0,0,0}, {"shutdown",shutdownCommand,-1,"alt",0,NULL,0,0,0,0,0}, {"lastsave",lastsaveCommand,1,"RF",0,NULL,0,0,0,0,0}, {"type",typeCommand,2,"rF",0,NULL,1,1,1,0,0}, {"multi",multiCommand,1,"sF",0,NULL,0,0,0,0,0}, {"exec",execCommand,1,"sM",0,NULL,0,0,0,0,0}, {"discard",discardCommand,1,"sF",0,NULL,0,0,0,0,0}, {"sync",syncCommand,1,"ars",0,NULL,0,0,0,0,0}, {"psync",syncCommand,3,"ars",0,NULL,0,0,0,0,0}, {"replconf",replconfCommand,-1,"aslt",0,NULL,0,0,0,0,0}, {"flushdb",flushdbCommand,1,"w",0,NULL,0,0,0,0,0}, {"flushall",flushallCommand,1,"w",0,NULL,0,0,0,0,0}, {"sort",sortCommand,-2,"wm",0,sortGetKeys,1,1,1,0,0}, {"info",infoCommand,-1,"lt",0,NULL,0,0,0,0,0}, {"monitor",monitorCommand,1,"as",0,NULL,0,0,0,0,0}, {"ttl",ttlCommand,2,"rF",0,NULL,1,1,1,0,0}, {"touch",touchCommand,-2,"rF",0,NULL,1,1,1,0,0}, {"pttl",pttlCommand,2,"rF",0,NULL,1,1,1,0,0}, {"persist",persistCommand,2,"wF",0,NULL,1,1,1,0,0}, {"slaveof",slaveofCommand,3,"ast",0,NULL,0,0,0,0,0}, {"role",roleCommand,1,"lst",0,NULL,0,0,0,0,0}, {"debug",debugCommand,-1,"as",0,NULL,0,0,0,0,0}, {"config",configCommand,-2,"lat",0,NULL,0,0,0,0,0}, {"subscribe",subscribeCommand,-2,"pslt",0,NULL,0,0,0,0,0}, {"unsubscribe",unsubscribeCommand,-1,"pslt",0,NULL,0,0,0,0,0}, {"psubscribe",psubscribeCommand,-2,"pslt",0,NULL,0,0,0,0,0}, {"punsubscribe",punsubscribeCommand,-1,"pslt",0,NULL,0,0,0,0,0}, {"publish",publishCommand,3,"pltF",0,NULL,0,0,0,0,0}, {"pubsub",pubsubCommand,-2,"pltR",0,NULL,0,0,0,0,0}, {"watch",watchCommand,-2,"sF",0,NULL,1,-1,1,0,0}, {"unwatch",unwatchCommand,1,"sF",0,NULL,0,0,0,0,0}, {"cluster",clusterCommand,-2,"a",0,NULL,0,0,0,0,0}, {"restore",restoreCommand,-4,"wm",0,NULL,1,1,1,0,0}, {"restore-asking",restoreCommand,-4,"wmk",0,NULL,1,1,1,0,0}, {"migrate",migrateCommand,-6,"w",0,migrateGetKeys,0,0,0,0,0}, {"asking",askingCommand,1,"F",0,NULL,0,0,0,0,0}, {"readonly",readonlyCommand,1,"F",0,NULL,0,0,0,0,0}, {"readwrite",readwriteCommand,1,"F",0,NULL,0,0,0,0,0}, {"dump",dumpCommand,2,"r",0,NULL,1,1,1,0,0}, {"object",objectCommand,3,"r",0,NULL,2,2,2,0,0}, {"client",clientCommand,-2,"as",0,NULL,0,0,0,0,0}, {"eval",evalCommand,-3,"s",0,evalGetKeys,0,0,0,0,0}, {"evalsha",evalShaCommand,-3,"s",0,evalGetKeys,0,0,0,0,0}, {"slowlog",slowlogCommand,-2,"a",0,NULL,0,0,0,0,0}, {"script",scriptCommand,-2,"s",0,NULL,0,0,0,0,0}, {"time",timeCommand,1,"RF",0,NULL,0,0,0,0,0}, {"bitop",bitopCommand,-4,"wm",0,NULL,2,-1,1,0,0}, {"bitcount",bitcountCommand,-2,"r",0,NULL,1,1,1,0,0}, {"bitpos",bitposCommand,-3,"r",0,NULL,1,1,1,0,0}, {"wait",waitCommand,3,"s",0,NULL,0,0,0,0,0}, {"command",commandCommand,0,"lt",0,NULL,0,0,0,0,0}, {"geoadd",geoaddCommand,-5,"wm",0,NULL,1,1,1,0,0}, {"georadius",georadiusCommand,-6,"w",0,NULL,1,1,1,0,0}, {"georadiusbymember",georadiusByMemberCommand,-5,"w",0,NULL,1,1,1,0,0}, {"geohash",geohashCommand,-2,"r",0,NULL,1,1,1,0,0}, {"geopos",geoposCommand,-2,"r",0,NULL,1,1,1,0,0}, {"geodist",geodistCommand,-4,"r",0,NULL,1,1,1,0,0}, {"pfselftest",pfselftestCommand,1,"a",0,NULL,0,0,0,0,0}, {"pfadd",pfaddCommand,-2,"wmF",0,NULL,1,1,1,0,0}, {"pfcount",pfcountCommand,-2,"r",0,NULL,1,-1,1,0,0}, {"pfmerge",pfmergeCommand,-2,"wm",0,NULL,1,-1,1,0,0}, {"pfdebug",pfdebugCommand,-3,"w",0,NULL,0,0,0,0,0}, {"post",securityWarningCommand,-1,"lt",0,NULL,0,0,0,0,0}, {"host:",securityWarningCommand,-1,"lt",0,NULL,0,0,0,0,0}, {"latency",latencyCommand,-2,"aslt",0,NULL,0,0,0,0,0} }; struct evictionPoolEntry *evictionPoolAlloc(void); /*============================ Utility functions ============================ */ /* Low level logging. To use only for very big messages, otherwise * serverLog() is to prefer. */ void serverLogRaw(int level, const char *msg) { const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING }; const char *c = ".-*#"; FILE *fp; char buf[64]; int rawmode = (level & LL_RAW); int log_to_stdout = server.logfile[0] == '\0'; level &= 0xff; /* clear flags */ if (level < server.verbosity) return; fp = log_to_stdout ? stdout : fopen(server.logfile,"a"); if (!fp) return; if (rawmode) { fprintf(fp,"%s",msg); } else { int off; struct timeval tv; int role_char; pid_t pid = getpid(); gettimeofday(&tv,NULL); off = strftime(buf,sizeof(buf),"%d %b %H:%M:%S.",localtime(&tv.tv_sec)); snprintf(buf+off,sizeof(buf)-off,"%03d",(int)tv.tv_usec/1000); if (server.sentinel_mode) { role_char = 'X'; /* Sentinel. */ } else if (pid != server.pid) { role_char = 'C'; /* RDB / AOF writing child. */ } else { role_char = (server.masterhost ? 'S':'M'); /* Slave or Master. */ } fprintf(fp,"%d:%c %s %c %s\n", (int)getpid(),role_char, buf,c[level],msg); } fflush(fp); if (!log_to_stdout) fclose(fp); if (server.syslog_enabled) syslog(syslogLevelMap[level], "%s", msg); } /* Like serverLogRaw() but with printf-alike support. This is the function that * is used across the code. The raw version is only used in order to dump * the INFO output on crash. */ void serverLog(int level, const char *fmt, ...) { va_list ap; char msg[LOG_MAX_LEN]; if ((level&0xff) < server.verbosity) return; va_start(ap, fmt); vsnprintf(msg, sizeof(msg), fmt, ap); va_end(ap); serverLogRaw(level,msg); } /* Log a fixed message without printf-alike capabilities, in a way that is * safe to call from a signal handler. * * We actually use this only for signals that are not fatal from the point * of view of Redis. Signals that are going to kill the server anyway and * where we need printf-alike features are served by serverLog(). */ void serverLogFromHandler(int level, const char *msg) { int fd; int log_to_stdout = server.logfile[0] == '\0'; char buf[64]; if ((level&0xff) < server.verbosity || (log_to_stdout && server.daemonize)) return; fd = log_to_stdout ? STDOUT_FILENO : open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644); if (fd == -1) return; ll2string(buf,sizeof(buf),getpid()); if (write(fd,buf,strlen(buf)) == -1) goto err; if (write(fd,":signal-handler (",17) == -1) goto err; ll2string(buf,sizeof(buf),time(NULL)); if (write(fd,buf,strlen(buf)) == -1) goto err; if (write(fd,") ",2) == -1) goto err; if (write(fd,msg,strlen(msg)) == -1) goto err; if (write(fd,"\n",1) == -1) goto err; err: if (!log_to_stdout) close(fd); } /* Return the UNIX time in microseconds */ long long ustime(void) { struct timeval tv; long long ust; gettimeofday(&tv, NULL); ust = ((long long)tv.tv_sec)*1000000; ust += tv.tv_usec; return ust; } /* Return the UNIX time in milliseconds */ mstime_t mstime(void) { return ustime()/1000; } /* After an RDB dump or AOF rewrite we exit from children using _exit() instead of * exit(), because the latter may interact with the same file objects used by * the parent process. However if we are testing the coverage normal exit() is * used in order to obtain the right coverage information. */ void exitFromChild(int retcode) { #ifdef COVERAGE_TEST exit(retcode); #else _exit(retcode); #endif } /*====================== Hash table type implementation ==================== */ /* This is a hash table type that uses the SDS dynamic strings library as * keys and redis objects as values (objects can hold SDS strings, * lists, sets). */ void dictVanillaFree(void *privdata, void *val) { DICT_NOTUSED(privdata); zfree(val); } void dictListDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); listRelease((list*)val); } int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2) { int l1,l2; DICT_NOTUSED(privdata); l1 = sdslen((sds)key1); l2 = sdslen((sds)key2); if (l1 != l2) return 0; return memcmp(key1, key2, l1) == 0; } /* A case insensitive version used for the command lookup table and other * places where case insensitive non binary-safe comparison is needed. */ int dictSdsKeyCaseCompare(void *privdata, const void *key1, const void *key2) { DICT_NOTUSED(privdata); return strcasecmp(key1, key2) == 0; } void dictObjectDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); if (val == NULL) return; /* Values of swapped out keys as set to NULL */ decrRefCount(val); } void dictSdsDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); sdsfree(val); } int dictObjKeyCompare(void *privdata, const void *key1, const void *key2) { const robj *o1 = key1, *o2 = key2; return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); } unsigned int dictObjHash(const void *key) { const robj *o = key; return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); } unsigned int dictSdsHash(const void *key) { return dictGenHashFunction((unsigned char*)key, sdslen((char*)key)); } unsigned int dictSdsCaseHash(const void *key) { return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key)); } int dictEncObjKeyCompare(void *privdata, const void *key1, const void *key2) { robj *o1 = (robj*) key1, *o2 = (robj*) key2; int cmp; if (o1->encoding == OBJ_ENCODING_INT && o2->encoding == OBJ_ENCODING_INT) return o1->ptr == o2->ptr; o1 = getDecodedObject(o1); o2 = getDecodedObject(o2); cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); decrRefCount(o1); decrRefCount(o2); return cmp; } unsigned int dictEncObjHash(const void *key) { robj *o = (robj*) key; if (sdsEncodedObject(o)) { return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); } else { if (o->encoding == OBJ_ENCODING_INT) { char buf[32]; int len; len = ll2string(buf,32,(long)o->ptr); return dictGenHashFunction((unsigned char*)buf, len); } else { unsigned int hash; o = getDecodedObject(o); hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); decrRefCount(o); return hash; } } } /* Sets type hash table */ dictType setDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictObjectDestructor, /* key destructor */ NULL /* val destructor */ }; /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ dictType zsetDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictObjectDestructor, /* key destructor */ NULL /* val destructor */ }; /* Db->dict, keys are sds strings, vals are Redis objects. */ dictType dbDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ dictSdsDestructor, /* key destructor */ dictObjectDestructor /* val destructor */ }; /* server.lua_scripts sha (as sds string) -> scripts (as robj) cache. */ dictType shaScriptObjectDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ dictObjectDestructor /* val destructor */ }; /* Db->expires */ dictType keyptrDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ NULL, /* key destructor */ NULL /* val destructor */ }; /* Command table. sds string -> command struct pointer. */ dictType commandTableDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Hash type hash table (note that small hashes are represented with ziplists) */ dictType hashDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictObjectDestructor, /* key destructor */ dictObjectDestructor /* val destructor */ }; /* Keylist hash table type has unencoded redis objects as keys and * lists as values. It's used for blocking operations (BLPOP) and to * map swapped keys to a list of clients waiting for this keys to be loaded. */ dictType keylistDictType = { dictObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictObjKeyCompare, /* key compare */ dictObjectDestructor, /* key destructor */ dictListDestructor /* val destructor */ }; /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to * clusterNode structures. */ dictType clusterNodesDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Cluster re-addition blacklist. This maps node IDs to the time * we can re-add this node. The goal is to avoid readding a removed * node for some time. */ dictType clusterNodesBlackListDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Migrate cache dict type. */ dictType migrateCacheDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Replication cached script dict (server.repl_scriptcache_dict). * Keys are sds SHA1 strings, while values are not used at all in the current * implementation. */ dictType replScriptCacheDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; int htNeedsResize(dict *dict) { long long size, used; size = dictSlots(dict); used = dictSize(dict); return (size > DICT_HT_INITIAL_SIZE && (used*100/size < HASHTABLE_MIN_FILL)); } /* If the percentage of used slots in the HT reaches HASHTABLE_MIN_FILL * we resize the hash table to save memory */ void tryResizeHashTables(int dbid) { if (htNeedsResize(server.db[dbid].dict)) dictResize(server.db[dbid].dict); if (htNeedsResize(server.db[dbid].expires)) dictResize(server.db[dbid].expires); } /* Our hash table implementation performs rehashing incrementally while * we write/read from the hash table. Still if the server is idle, the hash * table will use two tables for a long time. So we try to use 1 millisecond * of CPU time at every call of this function to perform some rehahsing. * * The function returns 1 if some rehashing was performed, otherwise 0 * is returned. */ int incrementallyRehash(int dbid) { /* Keys dictionary */ if (dictIsRehashing(server.db[dbid].dict)) { dictRehashMilliseconds(server.db[dbid].dict,1); return 1; /* already used our millisecond for this loop... */ } /* Expires */ if (dictIsRehashing(server.db[dbid].expires)) { dictRehashMilliseconds(server.db[dbid].expires,1); return 1; /* already used our millisecond for this loop... */ } return 0; } /* This function is called once a background process of some kind terminates, * as we want to avoid resizing the hash tables when there is a child in order * to play well with copy-on-write (otherwise when a resize happens lots of * memory pages are copied). The goal of this function is to update the ability * for dict.c to resize the hash tables accordingly to the fact we have o not * running childs. */ void updateDictResizePolicy(void) { if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) dictEnableResize(); else dictDisableResize(); } /* ======================= Cron: called every 100 ms ======================== */ /* Helper function for the activeExpireCycle() function. * This function will try to expire the key that is stored in the hash table * entry 'de' of the 'expires' hash table of a Redis database. * * If the key is found to be expired, it is removed from the database and * 1 is returned. Otherwise no operation is performed and 0 is returned. * * When a key is expired, server.stat_expiredkeys is incremented. * * The parameter 'now' is the current time in milliseconds as is passed * to the function to avoid too many gettimeofday() syscalls. */ int activeExpireCycleTryExpire(redisDb *db, dictEntry *de, long long now) { long long t = dictGetSignedIntegerVal(de); if (now > t) { sds key = dictGetKey(de); robj *keyobj = createStringObject(key,sdslen(key)); propagateExpire(db,keyobj); dbDelete(db,keyobj); notifyKeyspaceEvent(NOTIFY_EXPIRED, "expired",keyobj,db->id); decrRefCount(keyobj); server.stat_expiredkeys++; return 1; } else { return 0; } } /* Try to expire a few timed out keys. The algorithm used is adaptive and * will use few CPU cycles if there are few expiring keys, otherwise * it will get more aggressive to avoid that too much memory is used by * keys that can be removed from the keyspace. * * No more than CRON_DBS_PER_CALL databases are tested at every * iteration. * * This kind of call is used when Redis detects that timelimit_exit is * true, so there is more work to do, and we do it more incrementally from * the beforeSleep() function of the event loop. * * Expire cycle type: * * If type is ACTIVE_EXPIRE_CYCLE_FAST the function will try to run a * "fast" expire cycle that takes no longer than EXPIRE_FAST_CYCLE_DURATION * microseconds, and is not repeated again before the same amount of time. * * If type is ACTIVE_EXPIRE_CYCLE_SLOW, that normal expire cycle is * executed, where the time limit is a percentage of the REDIS_HZ period * as specified by the REDIS_EXPIRELOOKUPS_TIME_PERC define. */ void activeExpireCycle(int type) { /* This function has some global state in order to continue the work * incrementally across calls. */ static unsigned int current_db = 0; /* Last DB tested. */ static int timelimit_exit = 0; /* Time limit hit in previous call? */ static long long last_fast_cycle = 0; /* When last fast cycle ran. */ int j, iteration = 0; int dbs_per_call = CRON_DBS_PER_CALL; long long start = ustime(), timelimit; if (type == ACTIVE_EXPIRE_CYCLE_FAST) { /* Don't start a fast cycle if the previous cycle did not exited * for time limt. Also don't repeat a fast cycle for the same period * as the fast cycle total duration itself. */ if (!timelimit_exit) return; if (start < last_fast_cycle + ACTIVE_EXPIRE_CYCLE_FAST_DURATION*2) return; last_fast_cycle = start; } /* We usually should test CRON_DBS_PER_CALL per iteration, with * two exceptions: * * 1) Don't test more DBs than we have. * 2) If last time we hit the time limit, we want to scan all DBs * in this iteration, as there is work to do in some DB and we don't want * expired keys to use memory for too much time. */ if (dbs_per_call > server.dbnum || timelimit_exit) dbs_per_call = server.dbnum; /* We can use at max ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC percentage of CPU time * per iteration. Since this function gets called with a frequency of * server.hz times per second, the following is the max amount of * microseconds we can spend in this function. */ timelimit = 1000000*ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC/server.hz/100; timelimit_exit = 0; if (timelimit <= 0) timelimit = 1; if (type == ACTIVE_EXPIRE_CYCLE_FAST) timelimit = ACTIVE_EXPIRE_CYCLE_FAST_DURATION; /* in microseconds. */ for (j = 0; j < dbs_per_call; j++) { int expired; redisDb *db = server.db+(current_db % server.dbnum); /* Increment the DB now so we are sure if we run out of time * in the current DB we'll restart from the next. This allows to * distribute the time evenly across DBs. */ current_db++; /* Continue to expire if at the end of the cycle more than 25% * of the keys were expired. */ do { unsigned long num, slots; long long now, ttl_sum; int ttl_samples; /* If there is nothing to expire try next DB ASAP. */ if ((num = dictSize(db->expires)) == 0) { db->avg_ttl = 0; break; } slots = dictSlots(db->expires); now = mstime(); /* When there are less than 1% filled slots getting random * keys is expensive, so stop here waiting for better times... * The dictionary will be resized asap. */ if (num && slots > DICT_HT_INITIAL_SIZE && (num*100/slots < 1)) break; /* The main collection cycle. Sample random keys among keys * with an expire set, checking for expired ones. */ expired = 0; ttl_sum = 0; ttl_samples = 0; if (num > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP) num = ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP; while (num--) { dictEntry *de; long long ttl; if ((de = dictGetRandomKey(db->expires)) == NULL) break; ttl = dictGetSignedIntegerVal(de)-now; if (activeExpireCycleTryExpire(db,de,now)) expired++; if (ttl > 0) { /* We want the average TTL of keys yet not expired. */ ttl_sum += ttl; ttl_samples++; } } /* Update the average TTL stats for this database. */ if (ttl_samples) { long long avg_ttl = ttl_sum/ttl_samples; /* Do a simple running average with a few samples. * We just use the current estimate with a weight of 2% * and the previous estimate with a weight of 98%. */ if (db->avg_ttl == 0) db->avg_ttl = avg_ttl; db->avg_ttl = (db->avg_ttl/50)*49 + (avg_ttl/50); } /* We can't block forever here even if there are many keys to * expire. So after a given amount of milliseconds return to the * caller waiting for the other active expire cycle. */ iteration++; if ((iteration & 0xf) == 0) { /* check once every 16 iterations. */ long long elapsed = ustime()-start; latencyAddSampleIfNeeded("expire-cycle",elapsed/1000); if (elapsed > timelimit) timelimit_exit = 1; } if (timelimit_exit) return; /* We don't repeat the cycle if there are less than 25% of keys * found expired in the current DB. */ } while (expired > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP/4); } } unsigned int getLRUClock(void) { return (mstime()/LRU_CLOCK_RESOLUTION) & LRU_CLOCK_MAX; } /* Add a sample to the operations per second array of samples. */ void trackInstantaneousMetric(int metric, long long current_reading) { long long t = mstime() - server.inst_metric[metric].last_sample_time; long long ops = current_reading - server.inst_metric[metric].last_sample_count; long long ops_sec; ops_sec = t > 0 ? (ops*1000/t) : 0; server.inst_metric[metric].samples[server.inst_metric[metric].idx] = ops_sec; server.inst_metric[metric].idx++; server.inst_metric[metric].idx %= STATS_METRIC_SAMPLES; server.inst_metric[metric].last_sample_time = mstime(); server.inst_metric[metric].last_sample_count = current_reading; } /* Return the mean of all the samples. */ long long getInstantaneousMetric(int metric) { int j; long long sum = 0; for (j = 0; j < STATS_METRIC_SAMPLES; j++) sum += server.inst_metric[metric].samples[j]; return sum / STATS_METRIC_SAMPLES; } /* Check for timeouts. Returns non-zero if the client was terminated. * The function gets the current time in milliseconds as argument since * it gets called multiple times in a loop, so calling gettimeofday() for * each iteration would be costly without any actual gain. */ int clientsCronHandleTimeout(client *c, mstime_t now_ms) { time_t now = now_ms/1000; if (server.maxidletime && !(c->flags & CLIENT_SLAVE) && /* no timeout for slaves */ !(c->flags & CLIENT_MASTER) && /* no timeout for masters */ !(c->flags & CLIENT_BLOCKED) && /* no timeout for BLPOP */ !(c->flags & CLIENT_PUBSUB) && /* no timeout for Pub/Sub clients */ (now - c->lastinteraction > server.maxidletime)) { serverLog(LL_VERBOSE,"Closing idle client"); freeClient(c); return 1; } else if (c->flags & CLIENT_BLOCKED) { /* Blocked OPS timeout is handled with milliseconds resolution. * However note that the actual resolution is limited by * server.hz. */ if (c->bpop.timeout != 0 && c->bpop.timeout < now_ms) { /* Handle blocking operation specific timeout. */ replyToBlockedClientTimedOut(c); unblockClient(c); } else if (server.cluster_enabled) { /* Cluster: handle unblock & redirect of clients blocked * into keys no longer served by this server. */ if (clusterRedirectBlockedClientIfNeeded(c)) unblockClient(c); } } return 0; } /* The client query buffer is an sds.c string that can end with a lot of * free space not used, this function reclaims space if needed. * * The function always returns 0 as it never terminates the client. */ int clientsCronResizeQueryBuffer(client *c) { size_t querybuf_size = sdsAllocSize(c->querybuf); time_t idletime = server.unixtime - c->lastinteraction; /* There are two conditions to resize the query buffer: * 1) Query buffer is > BIG_ARG and too big for latest peak. * 2) Client is inactive and the buffer is bigger than 1k. */ if (((querybuf_size > PROTO_MBULK_BIG_ARG) && (querybuf_size/(c->querybuf_peak+1)) > 2) || (querybuf_size > 1024 && idletime > 2)) { /* Only resize the query buffer if it is actually wasting space. */ if (sdsavail(c->querybuf) > 1024) { c->querybuf = sdsRemoveFreeSpace(c->querybuf); } } /* Reset the peak again to capture the peak memory usage in the next * cycle. */ c->querybuf_peak = 0; return 0; } #define CLIENTS_CRON_MIN_ITERATIONS 5 void clientsCron(void) { /* Make sure to process at least numclients/server.hz of clients * per call. Since this function is called server.hz times per second * we are sure that in the worst case we process all the clients in 1 * second. */ int numclients = listLength(server.clients); int iterations = numclients/server.hz; mstime_t now = mstime(); /* Process at least a few clients while we are at it, even if we need * to process less than CLIENTS_CRON_MIN_ITERATIONS to meet our contract * of processing each client once per second. */ if (iterations < CLIENTS_CRON_MIN_ITERATIONS) iterations = (numclients < CLIENTS_CRON_MIN_ITERATIONS) ? numclients : CLIENTS_CRON_MIN_ITERATIONS; while(listLength(server.clients) && iterations--) { client *c; listNode *head; /* Rotate the list, take the current head, process. * This way if the client must be removed from the list it's the * first element and we don't incur into O(N) computation. */ listRotate(server.clients); head = listFirst(server.clients); c = listNodeValue(head); /* The following functions do different service checks on the client. * The protocol is that they return non-zero if the client was * terminated. */ if (clientsCronHandleTimeout(c,now)) continue; if (clientsCronResizeQueryBuffer(c)) continue; } } /* This function handles 'background' operations we are required to do * incrementally in Redis databases, such as active key expiring, resizing, * rehashing. */ void databasesCron(void) { /* Expire keys by random sampling. Not required for slaves * as master will synthesize DELs for us. */ if (server.active_expire_enabled && server.masterhost == NULL) activeExpireCycle(ACTIVE_EXPIRE_CYCLE_SLOW); /* Perform hash tables rehashing if needed, but only if there are no * other processes saving the DB on disk. Otherwise rehashing is bad * as will cause a lot of copy-on-write of memory pages. */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) { /* We use global counters so if we stop the computation at a given * DB we'll be able to start from the successive in the next * cron loop iteration. */ static unsigned int resize_db = 0; static unsigned int rehash_db = 0; int dbs_per_call = CRON_DBS_PER_CALL; int j; /* Don't test more DBs than we have. */ if (dbs_per_call > server.dbnum) dbs_per_call = server.dbnum; /* Resize */ for (j = 0; j < dbs_per_call; j++) { tryResizeHashTables(resize_db % server.dbnum); resize_db++; } /* Rehash */ if (server.activerehashing) { for (j = 0; j < dbs_per_call; j++) { int work_done = incrementallyRehash(rehash_db % server.dbnum); rehash_db++; if (work_done) { /* If the function did some work, stop here, we'll do * more at the next cron loop. */ break; } } } } } /* We take a cached value of the unix time in the global state because with * virtual memory and aging there is to store the current time in objects at * every object access, and accuracy is not needed. To access a global var is * a lot faster than calling time(NULL) */ void updateCachedTime(void) { server.unixtime = time(NULL); server.mstime = mstime(); } /* This is our timer interrupt, called server.hz times per second. * Here is where we do a number of things that need to be done asynchronously. * For instance: * * - Active expired keys collection (it is also performed in a lazy way on * lookup). * - Software watchdog. * - Update some statistic. * - Incremental rehashing of the DBs hash tables. * - Triggering BGSAVE / AOF rewrite, and handling of terminated children. * - Clients timeout of different kinds. * - Replication reconnection. * - Many more... * * Everything directly called here will be called server.hz times per second, * so in order to throttle execution of things we want to do less frequently * a macro is used: run_with_period(milliseconds) { .... } */ int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) { int j; UNUSED(eventLoop); UNUSED(id); UNUSED(clientData); /* Software watchdog: deliver the SIGALRM that will reach the signal * handler if we don't return here fast enough. */ if (server.watchdog_period) watchdogScheduleSignal(server.watchdog_period); /* Update the time cache. */ updateCachedTime(); run_with_period(100) { trackInstantaneousMetric(STATS_METRIC_COMMAND,server.stat_numcommands); trackInstantaneousMetric(STATS_METRIC_NET_INPUT, server.stat_net_input_bytes); trackInstantaneousMetric(STATS_METRIC_NET_OUTPUT, server.stat_net_output_bytes); } /* We have just LRU_BITS bits per object for LRU information. * So we use an (eventually wrapping) LRU clock. * * Note that even if the counter wraps it's not a big problem, * everything will still work but some object will appear younger * to Redis. However for this to happen a given object should never be * touched for all the time needed to the counter to wrap, which is * not likely. * * Note that you can change the resolution altering the * LRU_CLOCK_RESOLUTION define. */ server.lruclock = getLRUClock(); /* Record the max memory used since the server was started. */ if (zmalloc_used_memory() > server.stat_peak_memory) server.stat_peak_memory = zmalloc_used_memory(); /* Sample the RSS here since this is a relatively slow call. */ server.resident_set_size = zmalloc_get_rss(); /* We received a SIGTERM, shutting down here in a safe way, as it is * not ok doing so inside the signal handler. */ if (server.shutdown_asap) { if (prepareForShutdown(SHUTDOWN_NOFLAGS) == C_OK) exit(0); serverLog(LL_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); server.shutdown_asap = 0; } /* Show some info about non-empty databases */ run_with_period(5000) { for (j = 0; j < server.dbnum; j++) { long long size, used, vkeys; size = dictSlots(server.db[j].dict); used = dictSize(server.db[j].dict); vkeys = dictSize(server.db[j].expires); if (used || vkeys) { serverLog(LL_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size); /* dictPrintStats(server.dict); */ } } } /* Show information about connected clients */ if (!server.sentinel_mode) { run_with_period(5000) { serverLog(LL_VERBOSE, "%lu clients connected (%lu slaves), %zu bytes in use", listLength(server.clients)-listLength(server.slaves), listLength(server.slaves), zmalloc_used_memory()); } } /* We need to do a few operations on clients asynchronously. */ clientsCron(); /* Handle background operations on Redis databases. */ databasesCron(); /* Start a scheduled AOF rewrite if this was requested by the user while * a BGSAVE was in progress. */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.aof_rewrite_scheduled) { rewriteAppendOnlyFileBackground(); } /* Check if a background saving or AOF rewrite in progress terminated. */ if (server.rdb_child_pid != -1 || server.aof_child_pid != -1 || ldbPendingChildren()) { int statloc; pid_t pid; if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) { int exitcode = WEXITSTATUS(statloc); int bysignal = 0; if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc); if (pid == -1) { serverLog(LL_WARNING,"wait3() returned an error: %s. " "rdb_child_pid = %d, aof_child_pid = %d", strerror(errno), (int) server.rdb_child_pid, (int) server.aof_child_pid); } else if (pid == server.rdb_child_pid) { backgroundSaveDoneHandler(exitcode,bysignal); } else if (pid == server.aof_child_pid) { backgroundRewriteDoneHandler(exitcode,bysignal); } else { if (!ldbRemoveChild(pid)) { serverLog(LL_WARNING, "Warning, detected child with unmatched pid: %ld", (long)pid); } } updateDictResizePolicy(); } } else { /* If there is not a background saving/rewrite in progress check if * we have to save/rewrite now */ for (j = 0; j < server.saveparamslen; j++) { struct saveparam *sp = server.saveparams+j; /* Save if we reached the given amount of changes, * the given amount of seconds, and if the latest bgsave was * successful or if, in case of an error, at least * CONFIG_BGSAVE_RETRY_DELAY seconds already elapsed. */ if (server.dirty >= sp->changes && server.unixtime-server.lastsave > sp->seconds && (server.unixtime-server.lastbgsave_try > CONFIG_BGSAVE_RETRY_DELAY || server.lastbgsave_status == C_OK)) { serverLog(LL_NOTICE,"%d changes in %d seconds. Saving...", sp->changes, (int)sp->seconds); rdbSaveBackground(server.rdb_filename); break; } } /* Trigger an AOF rewrite if needed */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.aof_rewrite_perc && server.aof_current_size > server.aof_rewrite_min_size) { long long base = server.aof_rewrite_base_size ? server.aof_rewrite_base_size : 1; long long growth = (server.aof_current_size*100/base) - 100; if (growth >= server.aof_rewrite_perc) { serverLog(LL_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth); rewriteAppendOnlyFileBackground(); } } } /* AOF postponed flush: Try at every cron cycle if the slow fsync * completed. */ if (server.aof_flush_postponed_start) flushAppendOnlyFile(0); /* AOF write errors: in this case we have a buffer to flush as well and * clear the AOF error in case of success to make the DB writable again, * however to try every second is enough in case of 'hz' is set to * an higher frequency. */ run_with_period(1000) { if (server.aof_last_write_status == C_ERR) flushAppendOnlyFile(0); } /* Close clients that need to be closed asynchronous */ freeClientsInAsyncFreeQueue(); /* Clear the paused clients flag if needed. */ clientsArePaused(); /* Don't check return value, just use the side effect. */ /* Replication cron function -- used to reconnect to master, * detect transfer failures, start background RDB transfers and so forth. */ run_with_period(1000) replicationCron(); /* Run the Redis Cluster cron. */ run_with_period(100) { if (server.cluster_enabled) clusterCron(); } /* Run the Sentinel timer if we are in sentinel mode. */ run_with_period(100) { if (server.sentinel_mode) sentinelTimer(); } /* Cleanup expired MIGRATE cached sockets. */ run_with_period(1000) { migrateCloseTimedoutSockets(); } /* Start a scheduled BGSAVE if the corresponding flag is set. This is * useful when we are forced to postpone a BGSAVE because an AOF * rewrite is in progress. * * Note: this code must be after the replicationCron() call above so * make sure when refactoring this file to keep this order. This is useful * because we want to give priority to RDB savings for replication. */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.rdb_bgsave_scheduled && (server.unixtime-server.lastbgsave_try > CONFIG_BGSAVE_RETRY_DELAY || server.lastbgsave_status == C_OK)) { if (rdbSaveBackground(server.rdb_filename) == C_OK) server.rdb_bgsave_scheduled = 0; } server.cronloops++; return 1000/server.hz; } /* This function gets called every time Redis is entering the * main loop of the event driven library, that is, before to sleep * for ready file descriptors. */ void beforeSleep(struct aeEventLoop *eventLoop) { UNUSED(eventLoop); /* Call the Redis Cluster before sleep function. Note that this function * may change the state of Redis Cluster (from ok to fail or vice versa), * so it's a good idea to call it before serving the unblocked clients * later in this function. */ if (server.cluster_enabled) clusterBeforeSleep(); /* Run a fast expire cycle (the called function will return * ASAP if a fast cycle is not needed). */ if (server.active_expire_enabled && server.masterhost == NULL) activeExpireCycle(ACTIVE_EXPIRE_CYCLE_FAST); /* Send all the slaves an ACK request if at least one client blocked * during the previous event loop iteration. */ if (server.get_ack_from_slaves) { robj *argv[3]; argv[0] = createStringObject("REPLCONF",8); argv[1] = createStringObject("GETACK",6); argv[2] = createStringObject("*",1); /* Not used argument. */ replicationFeedSlaves(server.slaves, server.slaveseldb, argv, 3); decrRefCount(argv[0]); decrRefCount(argv[1]); decrRefCount(argv[2]); server.get_ack_from_slaves = 0; } /* Unblock all the clients blocked for synchronous replication * in WAIT. */ if (listLength(server.clients_waiting_acks)) processClientsWaitingReplicas(); /* Try to process pending commands for clients that were just unblocked. */ if (listLength(server.unblocked_clients)) processUnblockedClients(); /* Write the AOF buffer on disk */ flushAppendOnlyFile(0); /* Handle writes with pending output buffers. */ handleClientsWithPendingWrites(); } /* =========================== Server initialization ======================== */ void createSharedObjects(void) { int j; shared.crlf = createObject(OBJ_STRING,sdsnew("\r\n")); shared.ok = createObject(OBJ_STRING,sdsnew("+OK\r\n")); shared.err = createObject(OBJ_STRING,sdsnew("-ERR\r\n")); shared.emptybulk = createObject(OBJ_STRING,sdsnew("$0\r\n\r\n")); shared.czero = createObject(OBJ_STRING,sdsnew(":0\r\n")); shared.cone = createObject(OBJ_STRING,sdsnew(":1\r\n")); shared.cnegone = createObject(OBJ_STRING,sdsnew(":-1\r\n")); shared.nullbulk = createObject(OBJ_STRING,sdsnew("$-1\r\n")); shared.nullmultibulk = createObject(OBJ_STRING,sdsnew("*-1\r\n")); shared.emptymultibulk = createObject(OBJ_STRING,sdsnew("*0\r\n")); shared.pong = createObject(OBJ_STRING,sdsnew("+PONG\r\n")); shared.queued = createObject(OBJ_STRING,sdsnew("+QUEUED\r\n")); shared.emptyscan = createObject(OBJ_STRING,sdsnew("*2\r\n$1\r\n0\r\n*0\r\n")); shared.wrongtypeerr = createObject(OBJ_STRING,sdsnew( "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n")); shared.nokeyerr = createObject(OBJ_STRING,sdsnew( "-ERR no such key\r\n")); shared.syntaxerr = createObject(OBJ_STRING,sdsnew( "-ERR syntax error\r\n")); shared.sameobjecterr = createObject(OBJ_STRING,sdsnew( "-ERR source and destination objects are the same\r\n")); shared.outofrangeerr = createObject(OBJ_STRING,sdsnew( "-ERR index out of range\r\n")); shared.noscripterr = createObject(OBJ_STRING,sdsnew( "-NOSCRIPT No matching script. Please use EVAL.\r\n")); shared.loadingerr = createObject(OBJ_STRING,sdsnew( "-LOADING Redis is loading the dataset in memory\r\n")); shared.slowscripterr = createObject(OBJ_STRING,sdsnew( "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n")); shared.masterdownerr = createObject(OBJ_STRING,sdsnew( "-MASTERDOWN Link with MASTER is down and slave-serve-stale-data is set to 'no'.\r\n")); shared.bgsaveerr = createObject(OBJ_STRING,sdsnew( "-MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.\r\n")); shared.roslaveerr = createObject(OBJ_STRING,sdsnew( "-READONLY You can't write against a read only slave.\r\n")); shared.noautherr = createObject(OBJ_STRING,sdsnew( "-NOAUTH Authentication required.\r\n")); shared.oomerr = createObject(OBJ_STRING,sdsnew( "-OOM command not allowed when used memory > 'maxmemory'.\r\n")); shared.execaborterr = createObject(OBJ_STRING,sdsnew( "-EXECABORT Transaction discarded because of previous errors.\r\n")); shared.noreplicaserr = createObject(OBJ_STRING,sdsnew( "-NOREPLICAS Not enough good slaves to write.\r\n")); shared.busykeyerr = createObject(OBJ_STRING,sdsnew( "-BUSYKEY Target key name already exists.\r\n")); shared.space = createObject(OBJ_STRING,sdsnew(" ")); shared.colon = createObject(OBJ_STRING,sdsnew(":")); shared.plus = createObject(OBJ_STRING,sdsnew("+")); for (j = 0; j < PROTO_SHARED_SELECT_CMDS; j++) { char dictid_str[64]; int dictid_len; dictid_len = ll2string(dictid_str,sizeof(dictid_str),j); shared.select[j] = createObject(OBJ_STRING, sdscatprintf(sdsempty(), "*2\r\n$6\r\nSELECT\r\n$%d\r\n%s\r\n", dictid_len, dictid_str)); } shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13); shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14); shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15); shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18); shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17); shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19); shared.del = createStringObject("DEL",3); shared.rpop = createStringObject("RPOP",4); shared.lpop = createStringObject("LPOP",4); shared.lpush = createStringObject("LPUSH",5); for (j = 0; j < OBJ_SHARED_INTEGERS; j++) { shared.integers[j] = createObject(OBJ_STRING,(void*)(long)j); shared.integers[j]->encoding = OBJ_ENCODING_INT; } for (j = 0; j < OBJ_SHARED_BULKHDR_LEN; j++) { shared.mbulkhdr[j] = createObject(OBJ_STRING, sdscatprintf(sdsempty(),"*%d\r\n",j)); shared.bulkhdr[j] = createObject(OBJ_STRING, sdscatprintf(sdsempty(),"$%d\r\n",j)); } /* The following two shared objects, minstring and maxstrings, are not * actually used for their value but as a special object meaning * respectively the minimum possible string and the maximum possible * string in string comparisons for the ZRANGEBYLEX command. */ shared.minstring = createStringObject("minstring",9); shared.maxstring = createStringObject("maxstring",9); } void initServerConfig(void) { int j; getRandomHexChars(server.runid,CONFIG_RUN_ID_SIZE); server.configfile = NULL; server.executable = NULL; server.hz = CONFIG_DEFAULT_HZ; server.runid[CONFIG_RUN_ID_SIZE] = '\0'; server.arch_bits = (sizeof(long) == 8) ? 64 : 32; server.port = CONFIG_DEFAULT_SERVER_PORT; server.tcp_backlog = CONFIG_DEFAULT_TCP_BACKLOG; server.bindaddr_count = 0; server.unixsocket = NULL; server.unixsocketperm = CONFIG_DEFAULT_UNIX_SOCKET_PERM; server.ipfd_count = 0; server.sofd = -1; server.protected_mode = CONFIG_DEFAULT_PROTECTED_MODE; server.dbnum = CONFIG_DEFAULT_DBNUM; server.verbosity = CONFIG_DEFAULT_VERBOSITY; server.maxidletime = CONFIG_DEFAULT_CLIENT_TIMEOUT; server.tcpkeepalive = CONFIG_DEFAULT_TCP_KEEPALIVE; server.active_expire_enabled = 1; server.client_max_querybuf_len = PROTO_MAX_QUERYBUF_LEN; server.saveparams = NULL; server.loading = 0; server.logfile = zstrdup(CONFIG_DEFAULT_LOGFILE); server.syslog_enabled = CONFIG_DEFAULT_SYSLOG_ENABLED; server.syslog_ident = zstrdup(CONFIG_DEFAULT_SYSLOG_IDENT); server.syslog_facility = LOG_LOCAL0; server.daemonize = CONFIG_DEFAULT_DAEMONIZE; server.supervised = 0; server.supervised_mode = SUPERVISED_NONE; server.aof_state = AOF_OFF; server.aof_fsync = CONFIG_DEFAULT_AOF_FSYNC; server.aof_no_fsync_on_rewrite = CONFIG_DEFAULT_AOF_NO_FSYNC_ON_REWRITE; server.aof_rewrite_perc = AOF_REWRITE_PERC; server.aof_rewrite_min_size = AOF_REWRITE_MIN_SIZE; server.aof_rewrite_base_size = 0; server.aof_rewrite_scheduled = 0; server.aof_last_fsync = time(NULL); server.aof_rewrite_time_last = -1; server.aof_rewrite_time_start = -1; server.aof_lastbgrewrite_status = C_OK; server.aof_delayed_fsync = 0; server.aof_fd = -1; server.aof_selected_db = -1; /* Make sure the first time will not match */ server.aof_flush_postponed_start = 0; server.aof_rewrite_incremental_fsync = CONFIG_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC; server.aof_load_truncated = CONFIG_DEFAULT_AOF_LOAD_TRUNCATED; server.pidfile = NULL; server.rdb_filename = zstrdup(CONFIG_DEFAULT_RDB_FILENAME); server.aof_filename = zstrdup(CONFIG_DEFAULT_AOF_FILENAME); server.requirepass = NULL; server.rdb_compression = CONFIG_DEFAULT_RDB_COMPRESSION; server.rdb_checksum = CONFIG_DEFAULT_RDB_CHECKSUM; server.stop_writes_on_bgsave_err = CONFIG_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR; server.activerehashing = CONFIG_DEFAULT_ACTIVE_REHASHING; server.notify_keyspace_events = 0; server.maxclients = CONFIG_DEFAULT_MAX_CLIENTS; server.bpop_blocked_clients = 0; server.maxmemory = CONFIG_DEFAULT_MAXMEMORY; server.maxmemory_policy = CONFIG_DEFAULT_MAXMEMORY_POLICY; server.maxmemory_samples = CONFIG_DEFAULT_MAXMEMORY_SAMPLES; server.hash_max_ziplist_entries = OBJ_HASH_MAX_ZIPLIST_ENTRIES; server.hash_max_ziplist_value = OBJ_HASH_MAX_ZIPLIST_VALUE; server.list_max_ziplist_size = OBJ_LIST_MAX_ZIPLIST_SIZE; server.list_compress_depth = OBJ_LIST_COMPRESS_DEPTH; server.set_max_intset_entries = OBJ_SET_MAX_INTSET_ENTRIES; server.zset_max_ziplist_entries = OBJ_ZSET_MAX_ZIPLIST_ENTRIES; server.zset_max_ziplist_value = OBJ_ZSET_MAX_ZIPLIST_VALUE; server.hll_sparse_max_bytes = CONFIG_DEFAULT_HLL_SPARSE_MAX_BYTES; server.shutdown_asap = 0; server.repl_ping_slave_period = CONFIG_DEFAULT_REPL_PING_SLAVE_PERIOD; server.repl_timeout = CONFIG_DEFAULT_REPL_TIMEOUT; server.repl_min_slaves_to_write = CONFIG_DEFAULT_MIN_SLAVES_TO_WRITE; server.repl_min_slaves_max_lag = CONFIG_DEFAULT_MIN_SLAVES_MAX_LAG; server.cluster_enabled = 0; server.cluster_node_timeout = CLUSTER_DEFAULT_NODE_TIMEOUT; server.cluster_migration_barrier = CLUSTER_DEFAULT_MIGRATION_BARRIER; server.cluster_slave_validity_factor = CLUSTER_DEFAULT_SLAVE_VALIDITY; server.cluster_require_full_coverage = CLUSTER_DEFAULT_REQUIRE_FULL_COVERAGE; server.cluster_configfile = zstrdup(CONFIG_DEFAULT_CLUSTER_CONFIG_FILE); server.migrate_cached_sockets = dictCreate(&migrateCacheDictType,NULL); server.next_client_id = 1; /* Client IDs, start from 1 .*/ server.loading_process_events_interval_bytes = (1024*1024*2); server.lruclock = getLRUClock(); resetServerSaveParams(); appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */ appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */ appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ /* Replication related */ server.masterauth = NULL; server.masterhost = NULL; server.masterport = 6379; server.master = NULL; server.cached_master = NULL; server.repl_master_initial_offset = -1; server.repl_state = REPL_STATE_NONE; server.repl_syncio_timeout = CONFIG_REPL_SYNCIO_TIMEOUT; server.repl_serve_stale_data = CONFIG_DEFAULT_SLAVE_SERVE_STALE_DATA; server.repl_slave_ro = CONFIG_DEFAULT_SLAVE_READ_ONLY; server.repl_down_since = 0; /* Never connected, repl is down since EVER. */ server.repl_disable_tcp_nodelay = CONFIG_DEFAULT_REPL_DISABLE_TCP_NODELAY; server.repl_diskless_sync = CONFIG_DEFAULT_REPL_DISKLESS_SYNC; server.repl_diskless_sync_delay = CONFIG_DEFAULT_REPL_DISKLESS_SYNC_DELAY; server.slave_priority = CONFIG_DEFAULT_SLAVE_PRIORITY; server.slave_announce_ip = CONFIG_DEFAULT_SLAVE_ANNOUNCE_IP; server.slave_announce_port = CONFIG_DEFAULT_SLAVE_ANNOUNCE_PORT; server.master_repl_offset = 0; /* Replication partial resync backlog */ server.repl_backlog = NULL; server.repl_backlog_size = CONFIG_DEFAULT_REPL_BACKLOG_SIZE; server.repl_backlog_histlen = 0; server.repl_backlog_idx = 0; server.repl_backlog_off = 0; server.repl_backlog_time_limit = CONFIG_DEFAULT_REPL_BACKLOG_TIME_LIMIT; server.repl_no_slaves_since = time(NULL); /* Client output buffer limits */ for (j = 0; j < CLIENT_TYPE_OBUF_COUNT; j++) server.client_obuf_limits[j] = clientBufferLimitsDefaults[j]; /* Double constants initialization */ R_Zero = 0.0; R_PosInf = 1.0/R_Zero; R_NegInf = -1.0/R_Zero; R_Nan = R_Zero/R_Zero; /* Command table -- we initiialize it here as it is part of the * initial configuration, since command names may be changed via * redis.conf using the rename-command directive. */ server.commands = dictCreate(&commandTableDictType,NULL); server.orig_commands = dictCreate(&commandTableDictType,NULL); populateCommandTable(); server.delCommand = lookupCommandByCString("del"); server.multiCommand = lookupCommandByCString("multi"); server.lpushCommand = lookupCommandByCString("lpush"); server.lpopCommand = lookupCommandByCString("lpop"); server.rpopCommand = lookupCommandByCString("rpop"); server.sremCommand = lookupCommandByCString("srem"); server.execCommand = lookupCommandByCString("exec"); /* Slow log */ server.slowlog_log_slower_than = CONFIG_DEFAULT_SLOWLOG_LOG_SLOWER_THAN; server.slowlog_max_len = CONFIG_DEFAULT_SLOWLOG_MAX_LEN; /* Latency monitor */ server.latency_monitor_threshold = CONFIG_DEFAULT_LATENCY_MONITOR_THRESHOLD; /* Debugging */ server.assert_failed = "<no assertion failed>"; server.assert_file = "<no file>"; server.assert_line = 0; server.bug_report_start = 0; server.watchdog_period = 0; } extern char **environ; /* Restart the server, executing the same executable that started this * instance, with the same arguments and configuration file. * * The function is designed to directly call execve() so that the new * server instance will retain the PID of the previous one. * * The list of flags, that may be bitwise ORed together, alter the * behavior of this function: * * RESTART_SERVER_NONE No flags. * RESTART_SERVER_GRACEFULLY Do a proper shutdown before restarting. * RESTART_SERVER_CONFIG_REWRITE Rewrite the config file before restarting. * * On success the function does not return, because the process turns into * a different process. On error C_ERR is returned. */ int restartServer(int flags, mstime_t delay) { int j; /* Check if we still have accesses to the executable that started this * server instance. */ if (access(server.executable,X_OK) == -1) return C_ERR; /* Config rewriting. */ if (flags & RESTART_SERVER_CONFIG_REWRITE && server.configfile && rewriteConfig(server.configfile) == -1) return C_ERR; /* Perform a proper shutdown. */ if (flags & RESTART_SERVER_GRACEFULLY && prepareForShutdown(SHUTDOWN_NOFLAGS) != C_OK) return C_ERR; /* Close all file descriptors, with the exception of stdin, stdout, strerr * which are useful if we restart a Redis server which is not daemonized. */ for (j = 3; j < (int)server.maxclients + 1024; j++) close(j); /* Execute the server with the original command line. */ if (delay) usleep(delay*1000); execve(server.executable,server.exec_argv,environ); /* If an error occurred here, there is nothing we can do, but exit. */ _exit(1); return C_ERR; /* Never reached. */ } /* This function will try to raise the max number of open files accordingly to * the configured max number of clients. It also reserves a number of file * descriptors (CONFIG_MIN_RESERVED_FDS) for extra operations of * persistence, listening sockets, log files and so forth. * * If it will not be possible to set the limit accordingly to the configured * max number of clients, the function will do the reverse setting * server.maxclients to the value that we can actually handle. */ void adjustOpenFilesLimit(void) { rlim_t maxfiles = server.maxclients+CONFIG_MIN_RESERVED_FDS; struct rlimit limit; if (getrlimit(RLIMIT_NOFILE,&limit) == -1) { serverLog(LL_WARNING,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.", strerror(errno)); server.maxclients = 1024-CONFIG_MIN_RESERVED_FDS; } else { rlim_t oldlimit = limit.rlim_cur; /* Set the max number of files if the current limit is not enough * for our needs. */ if (oldlimit < maxfiles) { rlim_t bestlimit; int setrlimit_error = 0; /* Try to set the file limit to match 'maxfiles' or at least * to the higher value supported less than maxfiles. */ bestlimit = maxfiles; while(bestlimit > oldlimit) { rlim_t decr_step = 16; limit.rlim_cur = bestlimit; limit.rlim_max = bestlimit; if (setrlimit(RLIMIT_NOFILE,&limit) != -1) break; setrlimit_error = errno; /* We failed to set file limit to 'bestlimit'. Try with a * smaller limit decrementing by a few FDs per iteration. */ if (bestlimit < decr_step) break; bestlimit -= decr_step; } /* Assume that the limit we get initially is still valid if * our last try was even lower. */ if (bestlimit < oldlimit) bestlimit = oldlimit; if (bestlimit < maxfiles) { int old_maxclients = server.maxclients; server.maxclients = bestlimit-CONFIG_MIN_RESERVED_FDS; if (server.maxclients < 1) { serverLog(LL_WARNING,"Your current 'ulimit -n' " "of %llu is not enough for the server to start. " "Please increase your open file limit to at least " "%llu. Exiting.", (unsigned long long) oldlimit, (unsigned long long) maxfiles); exit(1); } serverLog(LL_WARNING,"You requested maxclients of %d " "requiring at least %llu max file descriptors.", old_maxclients, (unsigned long long) maxfiles); serverLog(LL_WARNING,"Server can't set maximum open files " "to %llu because of OS error: %s.", (unsigned long long) maxfiles, strerror(setrlimit_error)); serverLog(LL_WARNING,"Current maximum open files is %llu. " "maxclients has been reduced to %d to compensate for " "low ulimit. " "If you need higher maxclients increase 'ulimit -n'.", (unsigned long long) bestlimit, server.maxclients); } else { serverLog(LL_NOTICE,"Increased maximum number of open files " "to %llu (it was originally set to %llu).", (unsigned long long) maxfiles, (unsigned long long) oldlimit); } } } } /* Check that server.tcp_backlog can be actually enforced in Linux according * to the value of /proc/sys/net/core/somaxconn, or warn about it. */ void checkTcpBacklogSettings(void) { #ifdef HAVE_PROC_SOMAXCONN FILE *fp = fopen("/proc/sys/net/core/somaxconn","r"); char buf[1024]; if (!fp) return; if (fgets(buf,sizeof(buf),fp) != NULL) { int somaxconn = atoi(buf); if (somaxconn > 0 && somaxconn < server.tcp_backlog) { serverLog(LL_WARNING,"WARNING: The TCP backlog setting of %d cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of %d.", server.tcp_backlog, somaxconn); } } fclose(fp); #endif } /* Initialize a set of file descriptors to listen to the specified 'port' * binding the addresses specified in the Redis server configuration. * * The listening file descriptors are stored in the integer array 'fds' * and their number is set in '*count'. * * The addresses to bind are specified in the global server.bindaddr array * and their number is server.bindaddr_count. If the server configuration * contains no specific addresses to bind, this function will try to * bind * (all addresses) for both the IPv4 and IPv6 protocols. * * On success the function returns C_OK. * * On error the function returns C_ERR. For the function to be on * error, at least one of the server.bindaddr addresses was * impossible to bind, or no bind addresses were specified in the server * configuration but the function is not able to bind * for at least * one of the IPv4 or IPv6 protocols. */ int listenToPort(int port, int *fds, int *count) { int j; /* Force binding of 0.0.0.0 if no bind address is specified, always * entering the loop if j == 0. */ if (server.bindaddr_count == 0) server.bindaddr[0] = NULL; for (j = 0; j < server.bindaddr_count || j == 0; j++) { if (server.bindaddr[j] == NULL) { int unsupported = 0; /* Bind * for both IPv6 and IPv4, we enter here only if * server.bindaddr_count == 0. */ fds[*count] = anetTcp6Server(server.neterr,port,NULL, server.tcp_backlog); if (fds[*count] != ANET_ERR) { anetNonBlock(NULL,fds[*count]); (*count)++; } else if (errno == EAFNOSUPPORT) { unsupported++; serverLog(LL_WARNING,"Not listening to IPv6: unsupproted"); } if (*count == 1 || unsupported) { /* Bind the IPv4 address as well. */ fds[*count] = anetTcpServer(server.neterr,port,NULL, server.tcp_backlog); if (fds[*count] != ANET_ERR) { anetNonBlock(NULL,fds[*count]); (*count)++; } else if (errno == EAFNOSUPPORT) { unsupported++; serverLog(LL_WARNING,"Not listening to IPv4: unsupproted"); } } /* Exit the loop if we were able to bind * on IPv4 and IPv6, * otherwise fds[*count] will be ANET_ERR and we'll print an * error and return to the caller with an error. */ if (*count + unsupported == 2) break; } else if (strchr(server.bindaddr[j],':')) { /* Bind IPv6 address. */ fds[*count] = anetTcp6Server(server.neterr,port,server.bindaddr[j], server.tcp_backlog); } else { /* Bind IPv4 address. */ fds[*count] = anetTcpServer(server.neterr,port,server.bindaddr[j], server.tcp_backlog); } if (fds[*count] == ANET_ERR) { serverLog(LL_WARNING, "Creating Server TCP listening socket %s:%d: %s", server.bindaddr[j] ? server.bindaddr[j] : "*", port, server.neterr); return C_ERR; } anetNonBlock(NULL,fds[*count]); (*count)++; } return C_OK; } /* Resets the stats that we expose via INFO or other means that we want * to reset via CONFIG RESETSTAT. The function is also used in order to * initialize these fields in initServer() at server startup. */ void resetServerStats(void) { int j; server.stat_numcommands = 0; server.stat_numconnections = 0; server.stat_expiredkeys = 0; server.stat_evictedkeys = 0; server.stat_keyspace_misses = 0; server.stat_keyspace_hits = 0; server.stat_fork_time = 0; server.stat_fork_rate = 0; server.stat_rejected_conn = 0; server.stat_sync_full = 0; server.stat_sync_partial_ok = 0; server.stat_sync_partial_err = 0; for (j = 0; j < STATS_METRIC_COUNT; j++) { server.inst_metric[j].idx = 0; server.inst_metric[j].last_sample_time = mstime(); server.inst_metric[j].last_sample_count = 0; memset(server.inst_metric[j].samples,0, sizeof(server.inst_metric[j].samples)); } server.stat_net_input_bytes = 0; server.stat_net_output_bytes = 0; server.aof_delayed_fsync = 0; } void initServer(void) { int j; signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); setupSignalHandlers(); if (server.syslog_enabled) { openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT, server.syslog_facility); } server.pid = getpid(); server.current_client = NULL; server.clients = listCreate(); server.clients_to_close = listCreate(); server.slaves = listCreate(); server.monitors = listCreate(); server.clients_pending_write = listCreate(); server.slaveseldb = -1; /* Force to emit the first SELECT command. */ server.unblocked_clients = listCreate(); server.ready_keys = listCreate(); server.clients_waiting_acks = listCreate(); server.get_ack_from_slaves = 0; server.clients_paused = 0; server.system_memory_size = zmalloc_get_memory_size(); createSharedObjects(); adjustOpenFilesLimit(); server.el = aeCreateEventLoop(server.maxclients+CONFIG_FDSET_INCR); server.db = zmalloc(sizeof(redisDb)*server.dbnum); /* Open the TCP listening socket for the user commands. */ if (server.port != 0 && listenToPort(server.port,server.ipfd,&server.ipfd_count) == C_ERR) exit(1); /* Open the listening Unix domain socket. */ if (server.unixsocket != NULL) { unlink(server.unixsocket); /* don't care if this fails */ server.sofd = anetUnixServer(server.neterr,server.unixsocket, server.unixsocketperm, server.tcp_backlog); if (server.sofd == ANET_ERR) { serverLog(LL_WARNING, "Opening Unix socket: %s", server.neterr); exit(1); } anetNonBlock(NULL,server.sofd); } /* Abort if there are no listening sockets at all. */ if (server.ipfd_count == 0 && server.sofd < 0) { serverLog(LL_WARNING, "Configured to not listen anywhere, exiting."); exit(1); } /* Create the Redis databases, and initialize other internal state. */ for (j = 0; j < server.dbnum; j++) { server.db[j].dict = dictCreate(&dbDictType,NULL); server.db[j].expires = dictCreate(&keyptrDictType,NULL); server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL); server.db[j].ready_keys = dictCreate(&setDictType,NULL); server.db[j].watched_keys = dictCreate(&keylistDictType,NULL); server.db[j].eviction_pool = evictionPoolAlloc(); server.db[j].id = j; server.db[j].avg_ttl = 0; } server.pubsub_channels = dictCreate(&keylistDictType,NULL); server.pubsub_patterns = listCreate(); listSetFreeMethod(server.pubsub_patterns,freePubsubPattern); listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern); server.cronloops = 0; server.rdb_child_pid = -1; server.aof_child_pid = -1; server.rdb_child_type = RDB_CHILD_TYPE_NONE; server.rdb_bgsave_scheduled = 0; aofRewriteBufferReset(); server.aof_buf = sdsempty(); server.lastsave = time(NULL); /* At startup we consider the DB saved. */ server.lastbgsave_try = 0; /* At startup we never tried to BGSAVE. */ server.rdb_save_time_last = -1; server.rdb_save_time_start = -1; server.dirty = 0; resetServerStats(); /* A few stats we don't want to reset: server startup time, and peak mem. */ server.stat_starttime = time(NULL); server.stat_peak_memory = 0; server.resident_set_size = 0; server.lastbgsave_status = C_OK; server.aof_last_write_status = C_OK; server.aof_last_write_errno = 0; server.repl_good_slaves_count = 0; updateCachedTime(); /* Create the serverCron() time event, that's our main way to process * background operations. */ if(aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL) == AE_ERR) { serverPanic("Can't create the serverCron time event."); exit(1); } /* Create an event handler for accepting new connections in TCP and Unix * domain sockets. */ for (j = 0; j < server.ipfd_count; j++) { if (aeCreateFileEvent(server.el, server.ipfd[j], AE_READABLE, acceptTcpHandler,NULL) == AE_ERR) { serverPanic( "Unrecoverable error creating server.ipfd file event."); } } if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE, acceptUnixHandler,NULL) == AE_ERR) serverPanic("Unrecoverable error creating server.sofd file event."); /* Open the AOF file if needed. */ if (server.aof_state == AOF_ON) { server.aof_fd = open(server.aof_filename, O_WRONLY|O_APPEND|O_CREAT,0644); if (server.aof_fd == -1) { serverLog(LL_WARNING, "Can't open the append-only file: %s", strerror(errno)); exit(1); } } /* 32 bit instances are limited to 4GB of address space, so if there is * no explicit limit in the user provided configuration we set a limit * at 3 GB using maxmemory with 'noeviction' policy'. This avoids * useless crashes of the Redis instance for out of memory. */ if (server.arch_bits == 32 && server.maxmemory == 0) { serverLog(LL_WARNING,"Warning: 32 bit instance detected but no memory limit set. Setting 3 GB maxmemory limit with 'noeviction' policy now."); server.maxmemory = 3072LL*(1024*1024); /* 3 GB */ server.maxmemory_policy = MAXMEMORY_NO_EVICTION; } if (server.cluster_enabled) clusterInit(); replicationScriptCacheInit(); scriptingInit(1); slowlogInit(); latencyMonitorInit(); bioInit(); } /* Populates the Redis Command Table starting from the hard coded list * we have on top of redis.c file. */ void populateCommandTable(void) { int j; int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; char *f = c->sflags; int retval1, retval2; while(*f != '\0') { switch(*f) { case 'w': c->flags |= CMD_WRITE; break; case 'r': c->flags |= CMD_READONLY; break; case 'm': c->flags |= CMD_DENYOOM; break; case 'a': c->flags |= CMD_ADMIN; break; case 'p': c->flags |= CMD_PUBSUB; break; case 's': c->flags |= CMD_NOSCRIPT; break; case 'R': c->flags |= CMD_RANDOM; break; case 'S': c->flags |= CMD_SORT_FOR_SCRIPT; break; case 'l': c->flags |= CMD_LOADING; break; case 't': c->flags |= CMD_STALE; break; case 'M': c->flags |= CMD_SKIP_MONITOR; break; case 'k': c->flags |= CMD_ASKING; break; case 'F': c->flags |= CMD_FAST; break; default: serverPanic("Unsupported command flag"); break; } f++; } retval1 = dictAdd(server.commands, sdsnew(c->name), c); /* Populate an additional dictionary that will be unaffected * by rename-command statements in redis.conf. */ retval2 = dictAdd(server.orig_commands, sdsnew(c->name), c); serverAssert(retval1 == DICT_OK && retval2 == DICT_OK); } } void resetCommandTableStats(void) { int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); int j; for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; c->microseconds = 0; c->calls = 0; } } /* ========================== Redis OP Array API ============================ */ void redisOpArrayInit(redisOpArray *oa) { oa->ops = NULL; oa->numops = 0; } int redisOpArrayAppend(redisOpArray *oa, struct redisCommand *cmd, int dbid, robj **argv, int argc, int target) { redisOp *op; oa->ops = zrealloc(oa->ops,sizeof(redisOp)*(oa->numops+1)); op = oa->ops+oa->numops; op->cmd = cmd; op->dbid = dbid; op->argv = argv; op->argc = argc; op->target = target; oa->numops++; return oa->numops; } void redisOpArrayFree(redisOpArray *oa) { while(oa->numops) { int j; redisOp *op; oa->numops--; op = oa->ops+oa->numops; for (j = 0; j < op->argc; j++) decrRefCount(op->argv[j]); zfree(op->argv); } zfree(oa->ops); } /* ====================== Commands lookup and execution ===================== */ struct redisCommand *lookupCommand(sds name) { return dictFetchValue(server.commands, name); } struct redisCommand *lookupCommandByCString(char *s) { struct redisCommand *cmd; sds name = sdsnew(s); cmd = dictFetchValue(server.commands, name); sdsfree(name); return cmd; } /* Lookup the command in the current table, if not found also check in * the original table containing the original command names unaffected by * redis.conf rename-command statement. * * This is used by functions rewriting the argument vector such as * rewriteClientCommandVector() in order to set client->cmd pointer * correctly even if the command was renamed. */ struct redisCommand *lookupCommandOrOriginal(sds name) { struct redisCommand *cmd = dictFetchValue(server.commands, name); if (!cmd) cmd = dictFetchValue(server.orig_commands,name); return cmd; } /* Propagate the specified command (in the context of the specified database id) * to AOF and Slaves. * * flags are an xor between: * + PROPAGATE_NONE (no propagation of command at all) * + PROPAGATE_AOF (propagate into the AOF file if is enabled) * + PROPAGATE_REPL (propagate into the replication link) * * This should not be used inside commands implementation. Use instead * alsoPropagate(), preventCommandPropagation(), forceCommandPropagation(). */ void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int flags) { if (server.aof_state != AOF_OFF && flags & PROPAGATE_AOF) feedAppendOnlyFile(cmd,dbid,argv,argc); if (flags & PROPAGATE_REPL) replicationFeedSlaves(server.slaves,dbid,argv,argc); } /* Used inside commands to schedule the propagation of additional commands * after the current command is propagated to AOF / Replication. * * 'cmd' must be a pointer to the Redis command to replicate, dbid is the * database ID the command should be propagated into. * Arguments of the command to propagte are passed as an array of redis * objects pointers of len 'argc', using the 'argv' vector. * * The function does not take a reference to the passed 'argv' vector, * so it is up to the caller to release the passed argv (but it is usually * stack allocated). The function autoamtically increments ref count of * passed objects, so the caller does not need to. */ void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int target) { robj **argvcopy; int j; if (server.loading) return; /* No propagation during loading. */ argvcopy = zmalloc(sizeof(robj*)*argc); for (j = 0; j < argc; j++) { argvcopy[j] = argv[j]; incrRefCount(argv[j]); } redisOpArrayAppend(&server.also_propagate,cmd,dbid,argvcopy,argc,target); } /* It is possible to call the function forceCommandPropagation() inside a * Redis command implementation in order to to force the propagation of a * specific command execution into AOF / Replication. */ void forceCommandPropagation(client *c, int flags) { if (flags & PROPAGATE_REPL) c->flags |= CLIENT_FORCE_REPL; if (flags & PROPAGATE_AOF) c->flags |= CLIENT_FORCE_AOF; } /* Avoid that the executed command is propagated at all. This way we * are free to just propagate what we want using the alsoPropagate() * API. */ void preventCommandPropagation(client *c) { c->flags |= CLIENT_PREVENT_PROP; } /* AOF specific version of preventCommandPropagation(). */ void preventCommandAOF(client *c) { c->flags |= CLIENT_PREVENT_AOF_PROP; } /* Replication specific version of preventCommandPropagation(). */ void preventCommandReplication(client *c) { c->flags |= CLIENT_PREVENT_REPL_PROP; } /* Call() is the core of Redis execution of a command. * * The following flags can be passed: * CMD_CALL_NONE No flags. * CMD_CALL_SLOWLOG Check command speed and log in the slow log if needed. * CMD_CALL_STATS Populate command stats. * CMD_CALL_PROPAGATE_AOF Append command to AOF if it modified the dataset * or if the client flags are forcing propagation. * CMD_CALL_PROPAGATE_REPL Send command to salves if it modified the dataset * or if the client flags are forcing propagation. * CMD_CALL_PROPAGATE Alias for PROPAGATE_AOF|PROPAGATE_REPL. * CMD_CALL_FULL Alias for SLOWLOG|STATS|PROPAGATE. * * The exact propagation behavior depends on the client flags. * Specifically: * * 1. If the client flags CLIENT_FORCE_AOF or CLIENT_FORCE_REPL are set * and assuming the corresponding CMD_CALL_PROPAGATE_AOF/REPL is set * in the call flags, then the command is propagated even if the * dataset was not affected by the command. * 2. If the client flags CLIENT_PREVENT_REPL_PROP or CLIENT_PREVENT_AOF_PROP * are set, the propagation into AOF or to slaves is not performed even * if the command modified the dataset. * * Note that regardless of the client flags, if CMD_CALL_PROPAGATE_AOF * or CMD_CALL_PROPAGATE_REPL are not set, then respectively AOF or * slaves propagation will never occur. * * Client flags are modified by the implementation of a given command * using the following API: * * forceCommandPropagation(client *c, int flags); * preventCommandPropagation(client *c); * preventCommandAOF(client *c); * preventCommandReplication(client *c); * */ void call(client *c, int flags) { long long dirty, start, duration; int client_old_flags = c->flags; /* Sent the command to clients in MONITOR mode, only if the commands are * not generated from reading an AOF. */ if (listLength(server.monitors) && !server.loading && !(c->cmd->flags & (CMD_SKIP_MONITOR|CMD_ADMIN))) { replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc); } /* Initialization: clear the flags that must be set by the command on * demand, and initialize the array for additional commands propagation. */ c->flags &= ~(CLIENT_FORCE_AOF|CLIENT_FORCE_REPL|CLIENT_PREVENT_PROP); redisOpArrayInit(&server.also_propagate); /* Call the command. */ dirty = server.dirty; start = ustime(); c->cmd->proc(c); duration = ustime()-start; dirty = server.dirty-dirty; if (dirty < 0) dirty = 0; /* When EVAL is called loading the AOF we don't want commands called * from Lua to go into the slowlog or to populate statistics. */ if (server.loading && c->flags & CLIENT_LUA) flags &= ~(CMD_CALL_SLOWLOG | CMD_CALL_STATS); /* If the caller is Lua, we want to force the EVAL caller to propagate * the script if the command flag or client flag are forcing the * propagation. */ if (c->flags & CLIENT_LUA && server.lua_caller) { if (c->flags & CLIENT_FORCE_REPL) server.lua_caller->flags |= CLIENT_FORCE_REPL; if (c->flags & CLIENT_FORCE_AOF) server.lua_caller->flags |= CLIENT_FORCE_AOF; } /* Log the command into the Slow log if needed, and populate the * per-command statistics that we show in INFO commandstats. */ if (flags & CMD_CALL_SLOWLOG && c->cmd->proc != execCommand) { char *latency_event = (c->cmd->flags & CMD_FAST) ? "fast-command" : "command"; latencyAddSampleIfNeeded(latency_event,duration/1000); slowlogPushEntryIfNeeded(c->argv,c->argc,duration); } if (flags & CMD_CALL_STATS) { c->lastcmd->microseconds += duration; c->lastcmd->calls++; } /* Propagate the command into the AOF and replication link */ if (flags & CMD_CALL_PROPAGATE && (c->flags & CLIENT_PREVENT_PROP) != CLIENT_PREVENT_PROP) { int propagate_flags = PROPAGATE_NONE; /* Check if the command operated changes in the data set. If so * set for replication / AOF propagation. */ if (dirty) propagate_flags |= (PROPAGATE_AOF|PROPAGATE_REPL); /* If the client forced AOF / replication of the command, set * the flags regardless of the command effects on the data set. */ if (c->flags & CLIENT_FORCE_REPL) propagate_flags |= PROPAGATE_REPL; if (c->flags & CLIENT_FORCE_AOF) propagate_flags |= PROPAGATE_AOF; /* However prevent AOF / replication propagation if the command * implementatino called preventCommandPropagation() or similar, * or if we don't have the call() flags to do so. */ if (c->flags & CLIENT_PREVENT_REPL_PROP || !(flags & CMD_CALL_PROPAGATE_REPL)) propagate_flags &= ~PROPAGATE_REPL; if (c->flags & CLIENT_PREVENT_AOF_PROP || !(flags & CMD_CALL_PROPAGATE_AOF)) propagate_flags &= ~PROPAGATE_AOF; /* Call propagate() only if at least one of AOF / replication * propagation is needed. */ if (propagate_flags != PROPAGATE_NONE) propagate(c->cmd,c->db->id,c->argv,c->argc,propagate_flags); } /* Restore the old replication flags, since call() can be executed * recursively. */ c->flags &= ~(CLIENT_FORCE_AOF|CLIENT_FORCE_REPL|CLIENT_PREVENT_PROP); c->flags |= client_old_flags & (CLIENT_FORCE_AOF|CLIENT_FORCE_REPL|CLIENT_PREVENT_PROP); /* Handle the alsoPropagate() API to handle commands that want to propagate * multiple separated commands. Note that alsoPropagate() is not affected * by CLIENT_PREVENT_PROP flag. */ if (server.also_propagate.numops) { int j; redisOp *rop; if (flags & CMD_CALL_PROPAGATE) { for (j = 0; j < server.also_propagate.numops; j++) { rop = &server.also_propagate.ops[j]; int target = rop->target; /* Whatever the command wish is, we honor the call() flags. */ if (!(flags&CMD_CALL_PROPAGATE_AOF)) target &= ~PROPAGATE_AOF; if (!(flags&CMD_CALL_PROPAGATE_REPL)) target &= ~PROPAGATE_REPL; if (target) propagate(rop->cmd,rop->dbid,rop->argv,rop->argc,target); } } redisOpArrayFree(&server.also_propagate); } server.stat_numcommands++; } /* If this function gets called we already read a whole * command, arguments are in the client argv/argc fields. * processCommand() execute the command or prepare the * server for a bulk read from the client. * * If C_OK is returned the client is still alive and valid and * other operations can be performed by the caller. Otherwise * if C_ERR is returned the client was destroyed (i.e. after QUIT). */ int processCommand(client *c) { /* The QUIT command is handled separately. Normal command procs will * go through checking for replication and QUIT will cause trouble * when FORCE_REPLICATION is enabled and would be implemented in * a regular command proc. */ if (!strcasecmp(c->argv[0]->ptr,"quit")) { addReply(c,shared.ok); c->flags |= CLIENT_CLOSE_AFTER_REPLY; return C_ERR; } /* Now lookup the command and check ASAP about trivial error conditions * such as wrong arity, bad command name and so forth. */ c->cmd = c->lastcmd = lookupCommand(c->argv[0]->ptr); if (!c->cmd) { flagTransaction(c); addReplyErrorFormat(c,"unknown command '%s'", (char*)c->argv[0]->ptr); return C_OK; } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) || (c->argc < -c->cmd->arity)) { flagTransaction(c); addReplyErrorFormat(c,"wrong number of arguments for '%s' command", c->cmd->name); return C_OK; } /* Check if the user is authenticated */ if (server.requirepass && !c->authenticated && c->cmd->proc != authCommand) { flagTransaction(c); addReply(c,shared.noautherr); return C_OK; } /* If cluster is enabled perform the cluster redirection here. * However we don't perform the redirection if: * 1) The sender of this command is our master. * 2) The command has no key arguments. */ if (server.cluster_enabled && !(c->flags & CLIENT_MASTER) && !(c->flags & CLIENT_LUA && server.lua_caller->flags & CLIENT_MASTER) && !(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0 && c->cmd->proc != execCommand)) { int hashslot; int error_code; clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc, &hashslot,&error_code); if (n == NULL || n != server.cluster->myself) { if (c->cmd->proc == execCommand) { discardTransaction(c); } else { flagTransaction(c); } clusterRedirectClient(c,n,hashslot,error_code); return C_OK; } } /* Handle the maxmemory directive. * * First we try to free some memory if possible (if there are volatile * keys in the dataset). If there are not the only thing we can do * is returning an error. */ if (server.maxmemory) { int retval = freeMemoryIfNeeded(); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) return C_ERR; /* It was impossible to free enough memory, and the command the client * is trying to execute is denied during OOM conditions? Error. */ if ((c->cmd->flags & CMD_DENYOOM) && retval == C_ERR) { flagTransaction(c); addReply(c, shared.oomerr); return C_OK; } } /* Don't accept write commands if there are problems persisting on disk * and if this is a master instance. */ if (((server.stop_writes_on_bgsave_err && server.saveparamslen > 0 && server.lastbgsave_status == C_ERR) || server.aof_last_write_status == C_ERR) && server.masterhost == NULL && (c->cmd->flags & CMD_WRITE || c->cmd->proc == pingCommand)) { flagTransaction(c); if (server.aof_last_write_status == C_OK) addReply(c, shared.bgsaveerr); else addReplySds(c, sdscatprintf(sdsempty(), "-MISCONF Errors writing to the AOF file: %s\r\n", strerror(server.aof_last_write_errno))); return C_OK; } /* Don't accept write commands if there are not enough good slaves and * user configured the min-slaves-to-write option. */ if (server.masterhost == NULL && server.repl_min_slaves_to_write && server.repl_min_slaves_max_lag && c->cmd->flags & CMD_WRITE && server.repl_good_slaves_count < server.repl_min_slaves_to_write) { flagTransaction(c); addReply(c, shared.noreplicaserr); return C_OK; } /* Don't accept write commands if this is a read only slave. But * accept write commands if this is our master. */ if (server.masterhost && server.repl_slave_ro && !(c->flags & CLIENT_MASTER) && c->cmd->flags & CMD_WRITE) { addReply(c, shared.roslaveerr); return C_OK; } /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */ if (c->flags & CLIENT_PUBSUB && c->cmd->proc != pingCommand && c->cmd->proc != subscribeCommand && c->cmd->proc != unsubscribeCommand && c->cmd->proc != psubscribeCommand && c->cmd->proc != punsubscribeCommand) { addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context"); return C_OK; } /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and * we are a slave with a broken link with master. */ if (server.masterhost && server.repl_state != REPL_STATE_CONNECTED && server.repl_serve_stale_data == 0 && !(c->cmd->flags & CMD_STALE)) { flagTransaction(c); addReply(c, shared.masterdownerr); return C_OK; } /* Loading DB? Return an error if the command has not the * CMD_LOADING flag. */ if (server.loading && !(c->cmd->flags & CMD_LOADING)) { addReply(c, shared.loadingerr); return C_OK; } /* Lua script too slow? Only allow a limited number of commands. */ if (server.lua_timedout && c->cmd->proc != authCommand && c->cmd->proc != replconfCommand && !(c->cmd->proc == shutdownCommand && c->argc == 2 && tolower(((char*)c->argv[1]->ptr)[0]) == 'n') && !(c->cmd->proc == scriptCommand && c->argc == 2 && tolower(((char*)c->argv[1]->ptr)[0]) == 'k')) { flagTransaction(c); addReply(c, shared.slowscripterr); return C_OK; } /* Exec the command */ if (c->flags & CLIENT_MULTI && c->cmd->proc != execCommand && c->cmd->proc != discardCommand && c->cmd->proc != multiCommand && c->cmd->proc != watchCommand) { queueMultiCommand(c); addReply(c,shared.queued); } else { call(c,CMD_CALL_FULL); c->woff = server.master_repl_offset; if (listLength(server.ready_keys)) handleClientsBlockedOnLists(); } return C_OK; } /*================================== Shutdown =============================== */ /* Close listening sockets. Also unlink the unix domain socket if * unlink_unix_socket is non-zero. */ void closeListeningSockets(int unlink_unix_socket) { int j; for (j = 0; j < server.ipfd_count; j++) close(server.ipfd[j]); if (server.sofd != -1) close(server.sofd); if (server.cluster_enabled) for (j = 0; j < server.cfd_count; j++) close(server.cfd[j]); if (unlink_unix_socket && server.unixsocket) { serverLog(LL_NOTICE,"Removing the unix socket file."); unlink(server.unixsocket); /* don't care if this fails */ } } int prepareForShutdown(int flags) { int save = flags & SHUTDOWN_SAVE; int nosave = flags & SHUTDOWN_NOSAVE; serverLog(LL_WARNING,"User requested shutdown..."); /* Kill all the Lua debugger forked sessions. */ ldbKillForkedSessions(); /* Kill the saving child if there is a background saving in progress. We want to avoid race conditions, for instance our saving child may overwrite the synchronous saving did by SHUTDOWN. */ if (server.rdb_child_pid != -1) { serverLog(LL_WARNING,"There is a child saving an .rdb. Killing it!"); kill(server.rdb_child_pid,SIGUSR1); rdbRemoveTempFile(server.rdb_child_pid); } if (server.aof_state != AOF_OFF) { /* Kill the AOF saving child as the AOF we already have may be longer * but contains the full dataset anyway. */ if (server.aof_child_pid != -1) { /* If we have AOF enabled but haven't written the AOF yet, don't * shutdown or else the dataset will be lost. */ if (server.aof_state == AOF_WAIT_REWRITE) { serverLog(LL_WARNING, "Writing initial AOF, can't exit."); return C_ERR; } serverLog(LL_WARNING, "There is a child rewriting the AOF. Killing it!"); kill(server.aof_child_pid,SIGUSR1); } /* Append only file: fsync() the AOF and exit */ serverLog(LL_NOTICE,"Calling fsync() on the AOF file."); aof_fsync(server.aof_fd); } /* Create a new RDB file before exiting. */ if ((server.saveparamslen > 0 && !nosave) || save) { serverLog(LL_NOTICE,"Saving the final RDB snapshot before exiting."); /* Snapshotting. Perform a SYNC SAVE and exit */ if (rdbSave(server.rdb_filename) != C_OK) { /* Ooops.. error saving! The best we can do is to continue * operating. Note that if there was a background saving process, * in the next cron() Redis will be notified that the background * saving aborted, handling special stuff like slaves pending for * synchronization... */ serverLog(LL_WARNING,"Error trying to save the DB, can't exit."); return C_ERR; } } /* Remove the pid file if possible and needed. */ if (server.daemonize || server.pidfile) { serverLog(LL_NOTICE,"Removing the pid file."); unlink(server.pidfile); } /* Best effort flush of slave output buffers, so that we hopefully * send them pending writes. */ flushSlavesOutputBuffers(); /* Close the listening sockets. Apparently this allows faster restarts. */ closeListeningSockets(1); serverLog(LL_WARNING,"%s is now ready to exit, bye bye...", server.sentinel_mode ? "Sentinel" : "Redis"); return C_OK; } /*================================== Commands =============================== */ /* Return zero if strings are the same, non-zero if they are not. * The comparison is performed in a way that prevents an attacker to obtain * information about the nature of the strings just monitoring the execution * time of the function. * * Note that limiting the comparison length to strings up to 512 bytes we * can avoid leaking any information about the password length and any * possible branch misprediction related leak. */ int time_independent_strcmp(char *a, char *b) { char bufa[CONFIG_AUTHPASS_MAX_LEN], bufb[CONFIG_AUTHPASS_MAX_LEN]; /* The above two strlen perform len(a) + len(b) operations where either * a or b are fixed (our password) length, and the difference is only * relative to the length of the user provided string, so no information * leak is possible in the following two lines of code. */ unsigned int alen = strlen(a); unsigned int blen = strlen(b); unsigned int j; int diff = 0; /* We can't compare strings longer than our static buffers. * Note that this will never pass the first test in practical circumstances * so there is no info leak. */ if (alen > sizeof(bufa) || blen > sizeof(bufb)) return 1; memset(bufa,0,sizeof(bufa)); /* Constant time. */ memset(bufb,0,sizeof(bufb)); /* Constant time. */ /* Again the time of the following two copies is proportional to * len(a) + len(b) so no info is leaked. */ memcpy(bufa,a,alen); memcpy(bufb,b,blen); /* Always compare all the chars in the two buffers without * conditional expressions. */ for (j = 0; j < sizeof(bufa); j++) { diff |= (bufa[j] ^ bufb[j]); } /* Length must be equal as well. */ diff |= alen ^ blen; return diff; /* If zero strings are the same. */ } void authCommand(client *c) { if (!server.requirepass) { addReplyError(c,"Client sent AUTH, but no password is set"); } else if (!time_independent_strcmp(c->argv[1]->ptr, server.requirepass)) { c->authenticated = 1; addReply(c,shared.ok); } else { c->authenticated = 0; addReplyError(c,"invalid password"); } } /* The PING command. It works in a different way if the client is in * in Pub/Sub mode. */ void pingCommand(client *c) { /* The command takes zero or one arguments. */ if (c->argc > 2) { addReplyErrorFormat(c,"wrong number of arguments for '%s' command", c->cmd->name); return; } if (c->flags & CLIENT_PUBSUB) { addReply(c,shared.mbulkhdr[2]); addReplyBulkCBuffer(c,"pong",4); if (c->argc == 1) addReplyBulkCBuffer(c,"",0); else addReplyBulk(c,c->argv[1]); } else { if (c->argc == 1) addReply(c,shared.pong); else addReplyBulk(c,c->argv[1]); } } void echoCommand(client *c) { addReplyBulk(c,c->argv[1]); } void timeCommand(client *c) { struct timeval tv; /* gettimeofday() can only fail if &tv is a bad address so we * don't check for errors. */ gettimeofday(&tv,NULL); addReplyMultiBulkLen(c,2); addReplyBulkLongLong(c,tv.tv_sec); addReplyBulkLongLong(c,tv.tv_usec); } /* Helper function for addReplyCommand() to output flags. */ int addReplyCommandFlag(client *c, struct redisCommand *cmd, int f, char *reply) { if (cmd->flags & f) { addReplyStatus(c, reply); return 1; } return 0; } /* Output the representation of a Redis command. Used by the COMMAND command. */ void addReplyCommand(client *c, struct redisCommand *cmd) { if (!cmd) { addReply(c, shared.nullbulk); } else { /* We are adding: command name, arg count, flags, first, last, offset */ addReplyMultiBulkLen(c, 6); addReplyBulkCString(c, cmd->name); addReplyLongLong(c, cmd->arity); int flagcount = 0; void *flaglen = addDeferredMultiBulkLength(c); flagcount += addReplyCommandFlag(c,cmd,CMD_WRITE, "write"); flagcount += addReplyCommandFlag(c,cmd,CMD_READONLY, "readonly"); flagcount += addReplyCommandFlag(c,cmd,CMD_DENYOOM, "denyoom"); flagcount += addReplyCommandFlag(c,cmd,CMD_ADMIN, "admin"); flagcount += addReplyCommandFlag(c,cmd,CMD_PUBSUB, "pubsub"); flagcount += addReplyCommandFlag(c,cmd,CMD_NOSCRIPT, "noscript"); flagcount += addReplyCommandFlag(c,cmd,CMD_RANDOM, "random"); flagcount += addReplyCommandFlag(c,cmd,CMD_SORT_FOR_SCRIPT,"sort_for_script"); flagcount += addReplyCommandFlag(c,cmd,CMD_LOADING, "loading"); flagcount += addReplyCommandFlag(c,cmd,CMD_STALE, "stale"); flagcount += addReplyCommandFlag(c,cmd,CMD_SKIP_MONITOR, "skip_monitor"); flagcount += addReplyCommandFlag(c,cmd,CMD_ASKING, "asking"); flagcount += addReplyCommandFlag(c,cmd,CMD_FAST, "fast"); if (cmd->getkeys_proc) { addReplyStatus(c, "movablekeys"); flagcount += 1; } setDeferredMultiBulkLength(c, flaglen, flagcount); addReplyLongLong(c, cmd->firstkey); addReplyLongLong(c, cmd->lastkey); addReplyLongLong(c, cmd->keystep); } } /* COMMAND <subcommand> <args> */ void commandCommand(client *c) { dictIterator *di; dictEntry *de; if (c->argc == 1) { addReplyMultiBulkLen(c, dictSize(server.commands)); di = dictGetIterator(server.commands); while ((de = dictNext(di)) != NULL) { addReplyCommand(c, dictGetVal(de)); } dictReleaseIterator(di); } else if (!strcasecmp(c->argv[1]->ptr, "info")) { int i; addReplyMultiBulkLen(c, c->argc-2); for (i = 2; i < c->argc; i++) { addReplyCommand(c, dictFetchValue(server.commands, c->argv[i]->ptr)); } } else if (!strcasecmp(c->argv[1]->ptr, "count") && c->argc == 2) { addReplyLongLong(c, dictSize(server.commands)); } else if (!strcasecmp(c->argv[1]->ptr,"getkeys") && c->argc >= 3) { struct redisCommand *cmd = lookupCommand(c->argv[2]->ptr); int *keys, numkeys, j; if (!cmd) { addReplyErrorFormat(c,"Invalid command specified"); return; } else if ((cmd->arity > 0 && cmd->arity != c->argc-2) || ((c->argc-2) < -cmd->arity)) { addReplyError(c,"Invalid number of arguments specified for command"); return; } keys = getKeysFromCommand(cmd,c->argv+2,c->argc-2,&numkeys); addReplyMultiBulkLen(c,numkeys); for (j = 0; j < numkeys; j++) addReplyBulk(c,c->argv[keys[j]+2]); getKeysFreeResult(keys); } else { addReplyError(c, "Unknown subcommand or wrong number of arguments."); return; } } /* Convert an amount of bytes into a human readable string in the form * of 100B, 2G, 100M, 4K, and so forth. */ void bytesToHuman(char *s, unsigned long long n) { double d; if (n < 1024) { /* Bytes */ sprintf(s,"%lluB",n); return; } else if (n < (1024*1024)) { d = (double)n/(1024); sprintf(s,"%.2fK",d); } else if (n < (1024LL*1024*1024)) { d = (double)n/(1024*1024); sprintf(s,"%.2fM",d); } else if (n < (1024LL*1024*1024*1024)) { d = (double)n/(1024LL*1024*1024); sprintf(s,"%.2fG",d); } else if (n < (1024LL*1024*1024*1024*1024)) { d = (double)n/(1024LL*1024*1024*1024); sprintf(s,"%.2fT",d); } else if (n < (1024LL*1024*1024*1024*1024*1024)) { d = (double)n/(1024LL*1024*1024*1024*1024); sprintf(s,"%.2fP",d); } else { /* Let's hope we never need this */ sprintf(s,"%lluB",n); } } /* Create the string returned by the INFO command. This is decoupled * by the INFO command itself as we need to report the same information * on memory corruption problems. */ sds genRedisInfoString(char *section) { sds info = sdsempty(); time_t uptime = server.unixtime-server.stat_starttime; int j, numcommands; struct rusage self_ru, c_ru; unsigned long lol, bib; int allsections = 0, defsections = 0; int sections = 0; if (section == NULL) section = "default"; allsections = strcasecmp(section,"all") == 0; defsections = strcasecmp(section,"default") == 0; getrusage(RUSAGE_SELF, &self_ru); getrusage(RUSAGE_CHILDREN, &c_ru); getClientsMaxBuffers(&lol,&bib); /* Server */ if (allsections || defsections || !strcasecmp(section,"server")) { static int call_uname = 1; static struct utsname name; char *mode; if (server.cluster_enabled) mode = "cluster"; else if (server.sentinel_mode) mode = "sentinel"; else mode = "standalone"; if (sections++) info = sdscat(info,"\r\n"); if (call_uname) { /* Uname can be slow and is always the same output. Cache it. */ uname(&name); call_uname = 0; } info = sdscatprintf(info, "# Server\r\n" "redis_version:%s\r\n" "redis_git_sha1:%s\r\n" "redis_git_dirty:%d\r\n" "redis_build_id:%llx\r\n" "redis_mode:%s\r\n" "os:%s %s %s\r\n" "arch_bits:%d\r\n" "multiplexing_api:%s\r\n" "gcc_version:%d.%d.%d\r\n" "process_id:%ld\r\n" "run_id:%s\r\n" "tcp_port:%d\r\n" "uptime_in_seconds:%jd\r\n" "uptime_in_days:%jd\r\n" "hz:%d\r\n" "lru_clock:%ld\r\n" "executable:%s\r\n" "config_file:%s\r\n", REDIS_VERSION, redisGitSHA1(), strtol(redisGitDirty(),NULL,10) > 0, (unsigned long long) redisBuildId(), mode, name.sysname, name.release, name.machine, server.arch_bits, aeGetApiName(), #ifdef __GNUC__ __GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__, #else 0,0,0, #endif (long) getpid(), server.runid, server.port, (intmax_t)uptime, (intmax_t)(uptime/(3600*24)), server.hz, (unsigned long) server.lruclock, server.executable ? server.executable : "", server.configfile ? server.configfile : ""); } /* Clients */ if (allsections || defsections || !strcasecmp(section,"clients")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Clients\r\n" "connected_clients:%lu\r\n" "client_longest_output_list:%lu\r\n" "client_biggest_input_buf:%lu\r\n" "blocked_clients:%d\r\n", listLength(server.clients)-listLength(server.slaves), lol, bib, server.bpop_blocked_clients); } /* Memory */ if (allsections || defsections || !strcasecmp(section,"memory")) { char hmem[64]; char peak_hmem[64]; char total_system_hmem[64]; char used_memory_lua_hmem[64]; char used_memory_rss_hmem[64]; char maxmemory_hmem[64]; size_t zmalloc_used = zmalloc_used_memory(); size_t total_system_mem = server.system_memory_size; const char *evict_policy = evictPolicyToString(); long long memory_lua = (long long)lua_gc(server.lua,LUA_GCCOUNT,0)*1024; /* Peak memory is updated from time to time by serverCron() so it * may happen that the instantaneous value is slightly bigger than * the peak value. This may confuse users, so we update the peak * if found smaller than the current memory usage. */ if (zmalloc_used > server.stat_peak_memory) server.stat_peak_memory = zmalloc_used; bytesToHuman(hmem,zmalloc_used); bytesToHuman(peak_hmem,server.stat_peak_memory); bytesToHuman(total_system_hmem,total_system_mem); bytesToHuman(used_memory_lua_hmem,memory_lua); bytesToHuman(used_memory_rss_hmem,server.resident_set_size); bytesToHuman(maxmemory_hmem,server.maxmemory); if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Memory\r\n" "used_memory:%zu\r\n" "used_memory_human:%s\r\n" "used_memory_rss:%zu\r\n" "used_memory_rss_human:%s\r\n" "used_memory_peak:%zu\r\n" "used_memory_peak_human:%s\r\n" "total_system_memory:%lu\r\n" "total_system_memory_human:%s\r\n" "used_memory_lua:%lld\r\n" "used_memory_lua_human:%s\r\n" "maxmemory:%lld\r\n" "maxmemory_human:%s\r\n" "maxmemory_policy:%s\r\n" "mem_fragmentation_ratio:%.2f\r\n" "mem_allocator:%s\r\n", zmalloc_used, hmem, server.resident_set_size, used_memory_rss_hmem, server.stat_peak_memory, peak_hmem, (unsigned long)total_system_mem, total_system_hmem, memory_lua, used_memory_lua_hmem, server.maxmemory, maxmemory_hmem, evict_policy, zmalloc_get_fragmentation_ratio(server.resident_set_size), ZMALLOC_LIB ); } /* Persistence */ if (allsections || defsections || !strcasecmp(section,"persistence")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Persistence\r\n" "loading:%d\r\n" "rdb_changes_since_last_save:%lld\r\n" "rdb_bgsave_in_progress:%d\r\n" "rdb_last_save_time:%jd\r\n" "rdb_last_bgsave_status:%s\r\n" "rdb_last_bgsave_time_sec:%jd\r\n" "rdb_current_bgsave_time_sec:%jd\r\n" "aof_enabled:%d\r\n" "aof_rewrite_in_progress:%d\r\n" "aof_rewrite_scheduled:%d\r\n" "aof_last_rewrite_time_sec:%jd\r\n" "aof_current_rewrite_time_sec:%jd\r\n" "aof_last_bgrewrite_status:%s\r\n" "aof_last_write_status:%s\r\n", server.loading, server.dirty, server.rdb_child_pid != -1, (intmax_t)server.lastsave, (server.lastbgsave_status == C_OK) ? "ok" : "err", (intmax_t)server.rdb_save_time_last, (intmax_t)((server.rdb_child_pid == -1) ? -1 : time(NULL)-server.rdb_save_time_start), server.aof_state != AOF_OFF, server.aof_child_pid != -1, server.aof_rewrite_scheduled, (intmax_t)server.aof_rewrite_time_last, (intmax_t)((server.aof_child_pid == -1) ? -1 : time(NULL)-server.aof_rewrite_time_start), (server.aof_lastbgrewrite_status == C_OK) ? "ok" : "err", (server.aof_last_write_status == C_OK) ? "ok" : "err"); if (server.aof_state != AOF_OFF) { info = sdscatprintf(info, "aof_current_size:%lld\r\n" "aof_base_size:%lld\r\n" "aof_pending_rewrite:%d\r\n" "aof_buffer_length:%zu\r\n" "aof_rewrite_buffer_length:%lu\r\n" "aof_pending_bio_fsync:%llu\r\n" "aof_delayed_fsync:%lu\r\n", (long long) server.aof_current_size, (long long) server.aof_rewrite_base_size, server.aof_rewrite_scheduled, sdslen(server.aof_buf), aofRewriteBufferSize(), bioPendingJobsOfType(BIO_AOF_FSYNC), server.aof_delayed_fsync); } if (server.loading) { double perc; time_t eta, elapsed; off_t remaining_bytes = server.loading_total_bytes- server.loading_loaded_bytes; perc = ((double)server.loading_loaded_bytes / (server.loading_total_bytes+1)) * 100; elapsed = time(NULL)-server.loading_start_time; if (elapsed == 0) { eta = 1; /* A fake 1 second figure if we don't have enough info */ } else { eta = (elapsed*remaining_bytes)/(server.loading_loaded_bytes+1); } info = sdscatprintf(info, "loading_start_time:%jd\r\n" "loading_total_bytes:%llu\r\n" "loading_loaded_bytes:%llu\r\n" "loading_loaded_perc:%.2f\r\n" "loading_eta_seconds:%jd\r\n", (intmax_t) server.loading_start_time, (unsigned long long) server.loading_total_bytes, (unsigned long long) server.loading_loaded_bytes, perc, (intmax_t)eta ); } } /* Stats */ if (allsections || defsections || !strcasecmp(section,"stats")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Stats\r\n" "total_connections_received:%lld\r\n" "total_commands_processed:%lld\r\n" "instantaneous_ops_per_sec:%lld\r\n" "total_net_input_bytes:%lld\r\n" "total_net_output_bytes:%lld\r\n" "instantaneous_input_kbps:%.2f\r\n" "instantaneous_output_kbps:%.2f\r\n" "rejected_connections:%lld\r\n" "sync_full:%lld\r\n" "sync_partial_ok:%lld\r\n" "sync_partial_err:%lld\r\n" "expired_keys:%lld\r\n" "evicted_keys:%lld\r\n" "keyspace_hits:%lld\r\n" "keyspace_misses:%lld\r\n" "pubsub_channels:%ld\r\n" "pubsub_patterns:%lu\r\n" "latest_fork_usec:%lld\r\n" "migrate_cached_sockets:%ld\r\n", server.stat_numconnections, server.stat_numcommands, getInstantaneousMetric(STATS_METRIC_COMMAND), server.stat_net_input_bytes, server.stat_net_output_bytes, (float)getInstantaneousMetric(STATS_METRIC_NET_INPUT)/1024, (float)getInstantaneousMetric(STATS_METRIC_NET_OUTPUT)/1024, server.stat_rejected_conn, server.stat_sync_full, server.stat_sync_partial_ok, server.stat_sync_partial_err, server.stat_expiredkeys, server.stat_evictedkeys, server.stat_keyspace_hits, server.stat_keyspace_misses, dictSize(server.pubsub_channels), listLength(server.pubsub_patterns), server.stat_fork_time, dictSize(server.migrate_cached_sockets)); } /* Replication */ if (allsections || defsections || !strcasecmp(section,"replication")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Replication\r\n" "role:%s\r\n", server.masterhost == NULL ? "master" : "slave"); if (server.masterhost) { long long slave_repl_offset = 1; if (server.master) slave_repl_offset = server.master->reploff; else if (server.cached_master) slave_repl_offset = server.cached_master->reploff; info = sdscatprintf(info, "master_host:%s\r\n" "master_port:%d\r\n" "master_link_status:%s\r\n" "master_last_io_seconds_ago:%d\r\n" "master_sync_in_progress:%d\r\n" "slave_repl_offset:%lld\r\n" ,server.masterhost, server.masterport, (server.repl_state == REPL_STATE_CONNECTED) ? "up" : "down", server.master ? ((int)(server.unixtime-server.master->lastinteraction)) : -1, server.repl_state == REPL_STATE_TRANSFER, slave_repl_offset ); if (server.repl_state == REPL_STATE_TRANSFER) { info = sdscatprintf(info, "master_sync_left_bytes:%lld\r\n" "master_sync_last_io_seconds_ago:%d\r\n" , (long long) (server.repl_transfer_size - server.repl_transfer_read), (int)(server.unixtime-server.repl_transfer_lastio) ); } if (server.repl_state != REPL_STATE_CONNECTED) { info = sdscatprintf(info, "master_link_down_since_seconds:%jd\r\n", (intmax_t)server.unixtime-server.repl_down_since); } info = sdscatprintf(info, "slave_priority:%d\r\n" "slave_read_only:%d\r\n", server.slave_priority, server.repl_slave_ro); } info = sdscatprintf(info, "connected_slaves:%lu\r\n", listLength(server.slaves)); /* If min-slaves-to-write is active, write the number of slaves * currently considered 'good'. */ if (server.repl_min_slaves_to_write && server.repl_min_slaves_max_lag) { info = sdscatprintf(info, "min_slaves_good_slaves:%d\r\n", server.repl_good_slaves_count); } if (listLength(server.slaves)) { int slaveid = 0; listNode *ln; listIter li; listRewind(server.slaves,&li); while((ln = listNext(&li))) { client *slave = listNodeValue(ln); char *state = NULL; char ip[NET_IP_STR_LEN], *slaveip = slave->slave_ip; int port; long lag = 0; if (slaveip[0] == '\0') { if (anetPeerToString(slave->fd,ip,sizeof(ip),&port) == -1) continue; slaveip = ip; } switch(slave->replstate) { case SLAVE_STATE_WAIT_BGSAVE_START: case SLAVE_STATE_WAIT_BGSAVE_END: state = "wait_bgsave"; break; case SLAVE_STATE_SEND_BULK: state = "send_bulk"; break; case SLAVE_STATE_ONLINE: state = "online"; break; } if (state == NULL) continue; if (slave->replstate == SLAVE_STATE_ONLINE) lag = time(NULL) - slave->repl_ack_time; info = sdscatprintf(info, "slave%d:ip=%s,port=%d,state=%s," "offset=%lld,lag=%ld\r\n", slaveid,slaveip,slave->slave_listening_port,state, slave->repl_ack_off, lag); slaveid++; } } info = sdscatprintf(info, "master_repl_offset:%lld\r\n" "repl_backlog_active:%d\r\n" "repl_backlog_size:%lld\r\n" "repl_backlog_first_byte_offset:%lld\r\n" "repl_backlog_histlen:%lld\r\n", server.master_repl_offset, server.repl_backlog != NULL, server.repl_backlog_size, server.repl_backlog_off, server.repl_backlog_histlen); } /* CPU */ if (allsections || defsections || !strcasecmp(section,"cpu")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# CPU\r\n" "used_cpu_sys:%.2f\r\n" "used_cpu_user:%.2f\r\n" "used_cpu_sys_children:%.2f\r\n" "used_cpu_user_children:%.2f\r\n", (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000, (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000, (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000, (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000); } /* cmdtime */ if (allsections || !strcasecmp(section,"commandstats")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Commandstats\r\n"); numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; if (!c->calls) continue; info = sdscatprintf(info, "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n", c->name, c->calls, c->microseconds, (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls)); } } /* Cluster */ if (allsections || defsections || !strcasecmp(section,"cluster")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Cluster\r\n" "cluster_enabled:%d\r\n", server.cluster_enabled); } /* Key space */ if (allsections || defsections || !strcasecmp(section,"keyspace")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Keyspace\r\n"); for (j = 0; j < server.dbnum; j++) { long long keys, vkeys; keys = dictSize(server.db[j].dict); vkeys = dictSize(server.db[j].expires); if (keys || vkeys) { info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld,avg_ttl=%lld\r\n", j, keys, vkeys, server.db[j].avg_ttl); } } } return info; } void infoCommand(client *c) { char *section = c->argc == 2 ? c->argv[1]->ptr : "default"; if (c->argc > 2) { addReply(c,shared.syntaxerr); return; } addReplyBulkSds(c, genRedisInfoString(section)); } void monitorCommand(client *c) { /* ignore MONITOR if already slave or in monitor mode */ if (c->flags & CLIENT_SLAVE) return; c->flags |= (CLIENT_SLAVE|CLIENT_MONITOR); listAddNodeTail(server.monitors,c); addReply(c,shared.ok); } /* ============================ Maxmemory directive ======================== */ /* freeMemoryIfNeeded() gets called when 'maxmemory' is set on the config * file to limit the max memory used by the server, before processing a * command. * * The goal of the function is to free enough memory to keep Redis under the * configured memory limit. * * The function starts calculating how many bytes should be freed to keep * Redis under the limit, and enters a loop selecting the best keys to * evict accordingly to the configured policy. * * If all the bytes needed to return back under the limit were freed the * function returns C_OK, otherwise C_ERR is returned, and the caller * should block the execution of commands that will result in more memory * used by the server. * * ------------------------------------------------------------------------ * * LRU approximation algorithm * * Redis uses an approximation of the LRU algorithm that runs in constant * memory. Every time there is a key to expire, we sample N keys (with * N very small, usually in around 5) to populate a pool of best keys to * evict of M keys (the pool size is defined by MAXMEMORY_EVICTION_POOL_SIZE). * * The N keys sampled are added in the pool of good keys to expire (the one * with an old access time) if they are better than one of the current keys * in the pool. * * After the pool is populated, the best key we have in the pool is expired. * However note that we don't remove keys from the pool when they are deleted * so the pool may contain keys that no longer exist. * * When we try to evict a key, and all the entries in the pool don't exist * we populate it again. This time we'll be sure that the pool has at least * one key that can be evicted, if there is at least one key that can be * evicted in the whole database. */ /* Create a new eviction pool. */ struct evictionPoolEntry *evictionPoolAlloc(void) { struct evictionPoolEntry *ep; int j; ep = zmalloc(sizeof(*ep)*MAXMEMORY_EVICTION_POOL_SIZE); for (j = 0; j < MAXMEMORY_EVICTION_POOL_SIZE; j++) { ep[j].idle = 0; ep[j].key = NULL; } return ep; } /* This is an helper function for freeMemoryIfNeeded(), it is used in order * to populate the evictionPool with a few entries every time we want to * expire a key. Keys with idle time smaller than one of the current * keys are added. Keys are always added if there are free entries. * * We insert keys on place in ascending order, so keys with the smaller * idle time are on the left, and keys with the higher idle time on the * right. */ #define EVICTION_SAMPLES_ARRAY_SIZE 16 void evictionPoolPopulate(dict *sampledict, dict *keydict, struct evictionPoolEntry *pool) { int j, k, count; dictEntry *_samples[EVICTION_SAMPLES_ARRAY_SIZE]; dictEntry **samples; /* Try to use a static buffer: this function is a big hit... * Note: it was actually measured that this helps. */ if (server.maxmemory_samples <= EVICTION_SAMPLES_ARRAY_SIZE) { samples = _samples; } else { samples = zmalloc(sizeof(samples[0])*server.maxmemory_samples); } count = dictGetSomeKeys(sampledict,samples,server.maxmemory_samples); for (j = 0; j < count; j++) { unsigned long long idle; sds key; robj *o; dictEntry *de; de = samples[j]; key = dictGetKey(de); /* If the dictionary we are sampling from is not the main * dictionary (but the expires one) we need to lookup the key * again in the key dictionary to obtain the value object. */ if (sampledict != keydict) de = dictFind(keydict, key); o = dictGetVal(de); idle = estimateObjectIdleTime(o); /* Insert the element inside the pool. * First, find the first empty bucket or the first populated * bucket that has an idle time smaller than our idle time. */ k = 0; while (k < MAXMEMORY_EVICTION_POOL_SIZE && pool[k].key && pool[k].idle < idle) k++; if (k == 0 && pool[MAXMEMORY_EVICTION_POOL_SIZE-1].key != NULL) { /* Can't insert if the element is < the worst element we have * and there are no empty buckets. */ continue; } else if (k < MAXMEMORY_EVICTION_POOL_SIZE && pool[k].key == NULL) { /* Inserting into empty position. No setup needed before insert. */ } else { /* Inserting in the middle. Now k points to the first element * greater than the element to insert. */ if (pool[MAXMEMORY_EVICTION_POOL_SIZE-1].key == NULL) { /* Free space on the right? Insert at k shifting * all the elements from k to end to the right. */ memmove(pool+k+1,pool+k, sizeof(pool[0])*(MAXMEMORY_EVICTION_POOL_SIZE-k-1)); } else { /* No free space on right? Insert at k-1 */ k--; /* Shift all elements on the left of k (included) to the * left, so we discard the element with smaller idle time. */ sdsfree(pool[0].key); memmove(pool,pool+1,sizeof(pool[0])*k); } } pool[k].key = sdsdup(key); pool[k].idle = idle; } if (samples != _samples) zfree(samples); } int freeMemoryIfNeeded(void) { size_t mem_used, mem_tofree, mem_freed; int slaves = listLength(server.slaves); mstime_t latency, eviction_latency; /* Remove the size of slaves output buffers and AOF buffer from the * count of used memory. */ mem_used = zmalloc_used_memory(); if (slaves) { listIter li; listNode *ln; listRewind(server.slaves,&li); while((ln = listNext(&li))) { client *slave = listNodeValue(ln); unsigned long obuf_bytes = getClientOutputBufferMemoryUsage(slave); if (obuf_bytes > mem_used) mem_used = 0; else mem_used -= obuf_bytes; } } if (server.aof_state != AOF_OFF) { mem_used -= sdslen(server.aof_buf); mem_used -= aofRewriteBufferSize(); } /* Check if we are over the memory limit. */ if (mem_used <= server.maxmemory) return C_OK; if (server.maxmemory_policy == MAXMEMORY_NO_EVICTION) return C_ERR; /* We need to free memory, but policy forbids. */ /* Compute how much memory we need to free. */ mem_tofree = mem_used - server.maxmemory; mem_freed = 0; latencyStartMonitor(latency); while (mem_freed < mem_tofree) { int j, k, keys_freed = 0; for (j = 0; j < server.dbnum; j++) { long bestval = 0; /* just to prevent warning */ sds bestkey = NULL; dictEntry *de; redisDb *db = server.db+j; dict *dict; if (server.maxmemory_policy == MAXMEMORY_ALLKEYS_LRU || server.maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM) { dict = server.db[j].dict; } else { dict = server.db[j].expires; } if (dictSize(dict) == 0) continue; /* volatile-random and allkeys-random policy */ if (server.maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM || server.maxmemory_policy == MAXMEMORY_VOLATILE_RANDOM) { de = dictGetRandomKey(dict); bestkey = dictGetKey(de); } /* volatile-lru and allkeys-lru policy */ else if (server.maxmemory_policy == MAXMEMORY_ALLKEYS_LRU || server.maxmemory_policy == MAXMEMORY_VOLATILE_LRU) { struct evictionPoolEntry *pool = db->eviction_pool; while(bestkey == NULL) { evictionPoolPopulate(dict, db->dict, db->eviction_pool); /* Go backward from best to worst element to evict. */ for (k = MAXMEMORY_EVICTION_POOL_SIZE-1; k >= 0; k--) { if (pool[k].key == NULL) continue; de = dictFind(dict,pool[k].key); /* Remove the entry from the pool. */ sdsfree(pool[k].key); /* Shift all elements on its right to left. */ memmove(pool+k,pool+k+1, sizeof(pool[0])*(MAXMEMORY_EVICTION_POOL_SIZE-k-1)); /* Clear the element on the right which is empty * since we shifted one position to the left. */ pool[MAXMEMORY_EVICTION_POOL_SIZE-1].key = NULL; pool[MAXMEMORY_EVICTION_POOL_SIZE-1].idle = 0; /* If the key exists, is our pick. Otherwise it is * a ghost and we need to try the next element. */ if (de) { bestkey = dictGetKey(de); break; } else { /* Ghost... */ continue; } } } } /* volatile-ttl */ else if (server.maxmemory_policy == MAXMEMORY_VOLATILE_TTL) { for (k = 0; k < server.maxmemory_samples; k++) { sds thiskey; long thisval; de = dictGetRandomKey(dict); thiskey = dictGetKey(de); thisval = (long) dictGetVal(de); /* Expire sooner (minor expire unix timestamp) is better * candidate for deletion */ if (bestkey == NULL || thisval < bestval) { bestkey = thiskey; bestval = thisval; } } } /* Finally remove the selected key. */ if (bestkey) { long long delta; robj *keyobj = createStringObject(bestkey,sdslen(bestkey)); propagateExpire(db,keyobj); /* We compute the amount of memory freed by dbDelete() alone. * It is possible that actually the memory needed to propagate * the DEL in AOF and replication link is greater than the one * we are freeing removing the key, but we can't account for * that otherwise we would never exit the loop. * * AOF and Output buffer memory will be freed eventually so * we only care about memory used by the key space. */ delta = (long long) zmalloc_used_memory(); latencyStartMonitor(eviction_latency); dbDelete(db,keyobj); latencyEndMonitor(eviction_latency); latencyAddSampleIfNeeded("eviction-del",eviction_latency); latencyRemoveNestedEvent(latency,eviction_latency); delta -= (long long) zmalloc_used_memory(); mem_freed += delta; server.stat_evictedkeys++; notifyKeyspaceEvent(NOTIFY_EVICTED, "evicted", keyobj, db->id); decrRefCount(keyobj); keys_freed++; /* When the memory to free starts to be big enough, we may * start spending so much time here that is impossible to * deliver data to the slaves fast enough, so we force the * transmission here inside the loop. */ if (slaves) flushSlavesOutputBuffers(); } } if (!keys_freed) { latencyEndMonitor(latency); latencyAddSampleIfNeeded("eviction-cycle",latency); return C_ERR; /* nothing to free... */ } } latencyEndMonitor(latency); latencyAddSampleIfNeeded("eviction-cycle",latency); return C_OK; } /* =================================== Main! ================================ */ #ifdef __linux__ int linuxOvercommitMemoryValue(void) { FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r"); char buf[64]; if (!fp) return -1; if (fgets(buf,64,fp) == NULL) { fclose(fp); return -1; } fclose(fp); return atoi(buf); } void linuxMemoryWarnings(void) { if (linuxOvercommitMemoryValue() == 0) { serverLog(LL_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect."); } if (THPIsEnabled()) { serverLog(LL_WARNING,"WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled."); } } #endif /* __linux__ */ void createPidFile(void) { /* If pidfile requested, but no pidfile defined, use * default pidfile path */ if (!server.pidfile) server.pidfile = zstrdup(CONFIG_DEFAULT_PID_FILE); /* Try to write the pid file in a best-effort way. */ FILE *fp = fopen(server.pidfile,"w"); if (fp) { fprintf(fp,"%d\n",(int)getpid()); fclose(fp); } } void daemonize(void) { int fd; if (fork() != 0) exit(0); /* parent exits */ setsid(); /* create a new session */ /* Every output goes to /dev/null. If Redis is daemonized but * the 'logfile' is set to 'stdout' in the configuration file * it will not log at all. */ if ((fd = open("/dev/null", O_RDWR, 0)) != -1) { dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); if (fd > STDERR_FILENO) close(fd); } } void version(void) { printf("Redis server v=%s sha=%s:%d malloc=%s bits=%d build=%llx\n", REDIS_VERSION, redisGitSHA1(), atoi(redisGitDirty()) > 0, ZMALLOC_LIB, sizeof(long) == 4 ? 32 : 64, (unsigned long long) redisBuildId()); exit(0); } void usage(void) { fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf] [options]\n"); fprintf(stderr," ./redis-server - (read config from stdin)\n"); fprintf(stderr," ./redis-server -v or --version\n"); fprintf(stderr," ./redis-server -h or --help\n"); fprintf(stderr," ./redis-server --test-memory <megabytes>\n\n"); fprintf(stderr,"Examples:\n"); fprintf(stderr," ./redis-server (run the server with default conf)\n"); fprintf(stderr," ./redis-server /etc/redis/6379.conf\n"); fprintf(stderr," ./redis-server --port 7777\n"); fprintf(stderr," ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n"); fprintf(stderr," ./redis-server /etc/myredis.conf --loglevel verbose\n\n"); fprintf(stderr,"Sentinel mode:\n"); fprintf(stderr," ./redis-server /etc/sentinel.conf --sentinel\n"); exit(1); } void redisAsciiArt(void) { #include "asciilogo.h" char *buf = zmalloc(1024*16); char *mode; if (server.cluster_enabled) mode = "cluster"; else if (server.sentinel_mode) mode = "sentinel"; else mode = "standalone"; if (server.syslog_enabled) { serverLog(LL_NOTICE, "Redis %s (%s/%d) %s bit, %s mode, port %d, pid %ld ready to start.", REDIS_VERSION, redisGitSHA1(), strtol(redisGitDirty(),NULL,10) > 0, (sizeof(long) == 8) ? "64" : "32", mode, server.port, (long) getpid() ); } else { snprintf(buf,1024*16,ascii_logo, REDIS_VERSION, redisGitSHA1(), strtol(redisGitDirty(),NULL,10) > 0, (sizeof(long) == 8) ? "64" : "32", mode, server.port, (long) getpid() ); serverLogRaw(LL_NOTICE|LL_RAW,buf); } zfree(buf); } static void sigShutdownHandler(int sig) { char *msg; switch (sig) { case SIGINT: msg = "Received SIGINT scheduling shutdown..."; break; case SIGTERM: msg = "Received SIGTERM scheduling shutdown..."; break; default: msg = "Received shutdown signal, scheduling shutdown..."; }; /* SIGINT is often delivered via Ctrl+C in an interactive session. * If we receive the signal the second time, we interpret this as * the user really wanting to quit ASAP without waiting to persist * on disk. */ if (server.shutdown_asap && sig == SIGINT) { serverLogFromHandler(LL_WARNING, "You insist... exiting now."); rdbRemoveTempFile(getpid()); exit(1); /* Exit with an error since this was not a clean shutdown. */ } else if (server.loading) { exit(0); } serverLogFromHandler(LL_WARNING, msg); server.shutdown_asap = 1; } void setupSignalHandlers(void) { struct sigaction act; /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used. * Otherwise, sa_handler is used. */ sigemptyset(&act.sa_mask); act.sa_flags = 0; act.sa_handler = sigShutdownHandler; sigaction(SIGTERM, &act, NULL); sigaction(SIGINT, &act, NULL); #ifdef HAVE_BACKTRACE sigemptyset(&act.sa_mask); act.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO; act.sa_sigaction = sigsegvHandler; sigaction(SIGSEGV, &act, NULL); sigaction(SIGBUS, &act, NULL); sigaction(SIGFPE, &act, NULL); sigaction(SIGILL, &act, NULL); #endif return; } void memtest(size_t megabytes, int passes); /* Returns 1 if there is --sentinel among the arguments or if * argv[0] is exactly "redis-sentinel". */ int checkForSentinelMode(int argc, char **argv) { int j; if (strstr(argv[0],"redis-sentinel") != NULL) return 1; for (j = 1; j < argc; j++) if (!strcmp(argv[j],"--sentinel")) return 1; return 0; } /* Function called at startup to load RDB or AOF file in memory. */ void loadDataFromDisk(void) { long long start = ustime(); if (server.aof_state == AOF_ON) { if (loadAppendOnlyFile(server.aof_filename) == C_OK) serverLog(LL_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000); } else { if (rdbLoad(server.rdb_filename) == C_OK) { serverLog(LL_NOTICE,"DB loaded from disk: %.3f seconds", (float)(ustime()-start)/1000000); } else if (errno != ENOENT) { serverLog(LL_WARNING,"Fatal error loading the DB: %s. Exiting.",strerror(errno)); exit(1); } } } void redisOutOfMemoryHandler(size_t allocation_size) { serverLog(LL_WARNING,"Out Of Memory allocating %zu bytes!", allocation_size); serverPanic("Redis aborting for OUT OF MEMORY"); } void redisSetProcTitle(char *title) { #ifdef USE_SETPROCTITLE char *server_mode = ""; if (server.cluster_enabled) server_mode = " [cluster]"; else if (server.sentinel_mode) server_mode = " [sentinel]"; setproctitle("%s %s:%d%s", title, server.bindaddr_count ? server.bindaddr[0] : "*", server.port, server_mode); #else UNUSED(title); #endif } /* * Check whether systemd or upstart have been used to start redis. */ int redisSupervisedUpstart(void) { const char *upstart_job = getenv("UPSTART_JOB"); if (!upstart_job) { serverLog(LL_WARNING, "upstart supervision requested, but UPSTART_JOB not found"); return 0; } serverLog(LL_NOTICE, "supervised by upstart, will stop to signal readiness"); raise(SIGSTOP); unsetenv("UPSTART_JOB"); return 1; } int redisSupervisedSystemd(void) { const char *notify_socket = getenv("NOTIFY_SOCKET"); int fd = 1; struct sockaddr_un su; struct iovec iov; struct msghdr hdr; int sendto_flags = 0; if (!notify_socket) { serverLog(LL_WARNING, "systemd supervision requested, but NOTIFY_SOCKET not found"); return 0; } if ((strchr("@/", notify_socket[0])) == NULL || strlen(notify_socket) < 2) { return 0; } serverLog(LL_NOTICE, "supervised by systemd, will signal readiness"); if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) { serverLog(LL_WARNING, "Can't connect to systemd socket %s", notify_socket); return 0; } memset(&su, 0, sizeof(su)); su.sun_family = AF_UNIX; strncpy (su.sun_path, notify_socket, sizeof(su.sun_path) -1); su.sun_path[sizeof(su.sun_path) - 1] = '\0'; if (notify_socket[0] == '@') su.sun_path[0] = '\0'; memset(&iov, 0, sizeof(iov)); iov.iov_base = "READY=1"; iov.iov_len = strlen("READY=1"); memset(&hdr, 0, sizeof(hdr)); hdr.msg_name = &su; hdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + strlen(notify_socket); hdr.msg_iov = &iov; hdr.msg_iovlen = 1; unsetenv("NOTIFY_SOCKET"); #ifdef HAVE_MSG_NOSIGNAL sendto_flags |= MSG_NOSIGNAL; #endif if (sendmsg(fd, &hdr, sendto_flags) < 0) { serverLog(LL_WARNING, "Can't send notification to systemd"); close(fd); return 0; } close(fd); return 1; } int redisIsSupervised(int mode) { if (mode == SUPERVISED_AUTODETECT) { const char *upstart_job = getenv("UPSTART_JOB"); const char *notify_socket = getenv("NOTIFY_SOCKET"); if (upstart_job) { redisSupervisedUpstart(); } else if (notify_socket) { redisSupervisedSystemd(); } } else if (mode == SUPERVISED_UPSTART) { return redisSupervisedUpstart(); } else if (mode == SUPERVISED_SYSTEMD) { return redisSupervisedSystemd(); } return 0; } int main(int argc, char **argv) { struct timeval tv; int j; #ifdef REDIS_TEST if (argc == 3 && !strcasecmp(argv[1], "test")) { if (!strcasecmp(argv[2], "ziplist")) { return ziplistTest(argc, argv); } else if (!strcasecmp(argv[2], "quicklist")) { quicklistTest(argc, argv); } else if (!strcasecmp(argv[2], "intset")) { return intsetTest(argc, argv); } else if (!strcasecmp(argv[2], "zipmap")) { return zipmapTest(argc, argv); } else if (!strcasecmp(argv[2], "sha1test")) { return sha1Test(argc, argv); } else if (!strcasecmp(argv[2], "util")) { return utilTest(argc, argv); } else if (!strcasecmp(argv[2], "sds")) { return sdsTest(argc, argv); } else if (!strcasecmp(argv[2], "endianconv")) { return endianconvTest(argc, argv); } else if (!strcasecmp(argv[2], "crc64")) { return crc64Test(argc, argv); } return -1; /* test not found */ } #endif /* We need to initialize our libraries, and the server configuration. */ #ifdef INIT_SETPROCTITLE_REPLACEMENT spt_init(argc, argv); #endif setlocale(LC_COLLATE,""); zmalloc_enable_thread_safeness(); zmalloc_set_oom_handler(redisOutOfMemoryHandler); srand(time(NULL)^getpid()); gettimeofday(&tv,NULL); dictSetHashFunctionSeed(tv.tv_sec^tv.tv_usec^getpid()); server.sentinel_mode = checkForSentinelMode(argc,argv); initServerConfig(); /* Store the executable path and arguments in a safe place in order * to be able to restart the server later. */ server.executable = getAbsolutePath(argv[0]); server.exec_argv = zmalloc(sizeof(char*)*(argc+1)); server.exec_argv[argc] = NULL; for (j = 0; j < argc; j++) server.exec_argv[j] = zstrdup(argv[j]); /* We need to init sentinel right now as parsing the configuration file * in sentinel mode will have the effect of populating the sentinel * data structures with master nodes to monitor. */ if (server.sentinel_mode) { initSentinelConfig(); initSentinel(); } /* Check if we need to start in redis-check-rdb mode. We just execute * the program main. However the program is part of the Redis executable * so that we can easily execute an RDB check on loading errors. */ if (strstr(argv[0],"redis-check-rdb") != NULL) redis_check_rdb_main(argc,argv); if (argc >= 2) { j = 1; /* First option to parse in argv[] */ sds options = sdsempty(); char *configfile = NULL; /* Handle special options --help and --version */ if (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0) version(); if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) usage(); if (strcmp(argv[1], "--test-memory") == 0) { if (argc == 3) { memtest(atoi(argv[2]),50); exit(0); } else { fprintf(stderr,"Please specify the amount of memory to test in megabytes.\n"); fprintf(stderr,"Example: ./redis-server --test-memory 4096\n\n"); exit(1); } } /* First argument is the config file name? */ if (argv[j][0] != '-' || argv[j][1] != '-') { configfile = argv[j]; server.configfile = getAbsolutePath(configfile); /* Replace the config file in server.exec_argv with * its absoulte path. */ zfree(server.exec_argv[j]); server.exec_argv[j] = zstrdup(server.configfile); j++; } /* All the other options are parsed and conceptually appended to the * configuration file. For instance --port 6380 will generate the * string "port 6380\n" to be parsed after the actual file name * is parsed, if any. */ while(j != argc) { if (argv[j][0] == '-' && argv[j][1] == '-') { /* Option name */ if (!strcmp(argv[j], "--check-rdb")) { /* Argument has no options, need to skip for parsing. */ j++; continue; } if (sdslen(options)) options = sdscat(options,"\n"); options = sdscat(options,argv[j]+2); options = sdscat(options," "); } else { /* Option argument */ options = sdscatrepr(options,argv[j],strlen(argv[j])); options = sdscat(options," "); } j++; } if (server.sentinel_mode && configfile && *configfile == '-') { serverLog(LL_WARNING, "Sentinel config from STDIN not allowed."); serverLog(LL_WARNING, "Sentinel needs config file on disk to save state. Exiting..."); exit(1); } resetServerSaveParams(); loadServerConfig(configfile,options); sdsfree(options); } else { serverLog(LL_WARNING, "Warning: no config file specified, using the default config. In order to specify a config file use %s /path/to/%s.conf", argv[0], server.sentinel_mode ? "sentinel" : "redis"); } server.supervised = redisIsSupervised(server.supervised_mode); int background = server.daemonize && !server.supervised; if (background) daemonize(); initServer(); if (background || server.pidfile) createPidFile(); redisSetProcTitle(argv[0]); redisAsciiArt(); checkTcpBacklogSettings(); if (!server.sentinel_mode) { /* Things not needed when running in Sentinel mode. */ serverLog(LL_WARNING,"Server started, Redis version " REDIS_VERSION); #ifdef __linux__ linuxMemoryWarnings(); #endif loadDataFromDisk(); if (server.cluster_enabled) { if (verifyClusterConfigWithData() == C_ERR) { serverLog(LL_WARNING, "You can't have keys in a DB different than DB 0 when in " "Cluster mode. Exiting."); exit(1); } } if (server.ipfd_count > 0) serverLog(LL_NOTICE,"The server is now ready to accept connections on port %d", server.port); if (server.sofd > 0) serverLog(LL_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket); } else { sentinelIsRunning(); } /* Warning the user about suspicious maxmemory setting. */ if (server.maxmemory > 0 && server.maxmemory < 1024*1024) { serverLog(LL_WARNING,"WARNING: You specified a maxmemory value that is less than 1MB (current value is %llu bytes). Are you sure this is what you really want?", server.maxmemory); } aeSetBeforeSleepProc(server.el,beforeSleep); aeMain(server.el); aeDeleteEventLoop(server.el); return 0; } /* The End */
./CrossVul/dataset_final_sorted/CWE-254/c/good_4872_1
crossvul-cpp_data_good_5205_4
/** @file bzrtpTests.c @author Johan Pascal @copyright Copyright (C) 2014 Belledonne Communications, Grenoble, France 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdio.h> #include "CUnit/Basic.h" #include "bzrtpCryptoTest.h" #include "bzrtpParserTest.h" #include "typedef.h" #include "testUtils.h" #ifdef HAVE_LIBXML2 #include <libxml/parser.h> #endif int main(int argc, char *argv[] ) { int i, fails_count=0; CU_pSuite cryptoUtilsTestSuite, parserTestSuite; CU_pSuite *suites[] = { &cryptoUtilsTestSuite, &parserTestSuite, NULL }; if (argc>1) { if (argv[1][0] == '-') { if (strcmp(argv[1], "-verbose") == 0) { verbose = 1; } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } #ifdef HAVE_LIBXML2 xmlInitParser(); #endif /* initialize the CUnit test registry */ if (CUE_SUCCESS != CU_initialize_registry()) { return CU_get_error(); } /* Add the cryptoUtils suite to the registry */ cryptoUtilsTestSuite = CU_add_suite("Bzrtp Crypto Utils", NULL, NULL); CU_add_test(cryptoUtilsTestSuite, "zrtpKDF", test_zrtpKDF); CU_add_test(cryptoUtilsTestSuite, "CRC32", test_CRC32); CU_add_test(cryptoUtilsTestSuite, "algo agreement", test_algoAgreement); CU_add_test(cryptoUtilsTestSuite, "context algo setter and getter", test_algoSetterGetter); CU_add_test(cryptoUtilsTestSuite, "adding mandatory crypto algorithms if needed", test_addMandatoryCryptoTypesIfNeeded); /* Add the parser suite to the registry */ parserTestSuite = CU_add_suite("Bzrtp ZRTP Packet Parser", NULL, NULL); CU_add_test(parserTestSuite, "Parse", test_parser); CU_add_test(parserTestSuite, "Parse hvi check fail", test_parser_hvi); CU_add_test(parserTestSuite, "Parse Exchange", test_parserComplete); CU_add_test(parserTestSuite, "State machine", test_stateMachine); /* Run all suites */ for(i=0; suites[i]; i++){ CU_basic_run_suite(*suites[i]); fails_count += CU_get_number_of_tests_failed(); } /* cleanup the CUnit registry */ CU_cleanup_registry(); #ifdef HAVE_LIBXML2 /* cleanup libxml2 */ xmlCleanupParser(); #endif return (fails_count == 0 ? 0 : 1); }
./CrossVul/dataset_final_sorted/CWE-254/c/good_5205_4
crossvul-cpp_data_bad_2305_0
/* (C) 1999-2001 Paul `Rusty' Russell * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org> * * 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. */ #include <linux/types.h> #include <linux/jiffies.h> #include <linux/timer.h> #include <linux/netfilter.h> #include <net/netfilter/nf_conntrack_l4proto.h> static unsigned int nf_ct_generic_timeout __read_mostly = 600*HZ; static inline struct nf_generic_net *generic_pernet(struct net *net) { return &net->ct.nf_ct_proto.generic; } static bool generic_pkt_to_tuple(const struct sk_buff *skb, unsigned int dataoff, struct nf_conntrack_tuple *tuple) { tuple->src.u.all = 0; tuple->dst.u.all = 0; return true; } static bool generic_invert_tuple(struct nf_conntrack_tuple *tuple, const struct nf_conntrack_tuple *orig) { tuple->src.u.all = 0; tuple->dst.u.all = 0; return true; } /* Print out the per-protocol part of the tuple. */ static int generic_print_tuple(struct seq_file *s, const struct nf_conntrack_tuple *tuple) { return 0; } static unsigned int *generic_get_timeouts(struct net *net) { return &(generic_pernet(net)->timeout); } /* Returns verdict for packet, or -1 for invalid. */ static int generic_packet(struct nf_conn *ct, const struct sk_buff *skb, unsigned int dataoff, enum ip_conntrack_info ctinfo, u_int8_t pf, unsigned int hooknum, unsigned int *timeout) { nf_ct_refresh_acct(ct, ctinfo, skb, *timeout); return NF_ACCEPT; } /* Called when a new connection for this protocol found. */ static bool generic_new(struct nf_conn *ct, const struct sk_buff *skb, unsigned int dataoff, unsigned int *timeouts) { return true; } #if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT) #include <linux/netfilter/nfnetlink.h> #include <linux/netfilter/nfnetlink_cttimeout.h> static int generic_timeout_nlattr_to_obj(struct nlattr *tb[], struct net *net, void *data) { unsigned int *timeout = data; struct nf_generic_net *gn = generic_pernet(net); if (tb[CTA_TIMEOUT_GENERIC_TIMEOUT]) *timeout = ntohl(nla_get_be32(tb[CTA_TIMEOUT_GENERIC_TIMEOUT])) * HZ; else { /* Set default generic timeout. */ *timeout = gn->timeout; } return 0; } static int generic_timeout_obj_to_nlattr(struct sk_buff *skb, const void *data) { const unsigned int *timeout = data; if (nla_put_be32(skb, CTA_TIMEOUT_GENERIC_TIMEOUT, htonl(*timeout / HZ))) goto nla_put_failure; return 0; nla_put_failure: return -ENOSPC; } static const struct nla_policy generic_timeout_nla_policy[CTA_TIMEOUT_GENERIC_MAX+1] = { [CTA_TIMEOUT_GENERIC_TIMEOUT] = { .type = NLA_U32 }, }; #endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */ #ifdef CONFIG_SYSCTL static struct ctl_table generic_sysctl_table[] = { { .procname = "nf_conntrack_generic_timeout", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { } }; #ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT static struct ctl_table generic_compat_sysctl_table[] = { { .procname = "ip_conntrack_generic_timeout", .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { } }; #endif /* CONFIG_NF_CONNTRACK_PROC_COMPAT */ #endif /* CONFIG_SYSCTL */ static int generic_kmemdup_sysctl_table(struct nf_proto_net *pn, struct nf_generic_net *gn) { #ifdef CONFIG_SYSCTL pn->ctl_table = kmemdup(generic_sysctl_table, sizeof(generic_sysctl_table), GFP_KERNEL); if (!pn->ctl_table) return -ENOMEM; pn->ctl_table[0].data = &gn->timeout; #endif return 0; } static int generic_kmemdup_compat_sysctl_table(struct nf_proto_net *pn, struct nf_generic_net *gn) { #ifdef CONFIG_SYSCTL #ifdef CONFIG_NF_CONNTRACK_PROC_COMPAT pn->ctl_compat_table = kmemdup(generic_compat_sysctl_table, sizeof(generic_compat_sysctl_table), GFP_KERNEL); if (!pn->ctl_compat_table) return -ENOMEM; pn->ctl_compat_table[0].data = &gn->timeout; #endif #endif return 0; } static int generic_init_net(struct net *net, u_int16_t proto) { int ret; struct nf_generic_net *gn = generic_pernet(net); struct nf_proto_net *pn = &gn->pn; gn->timeout = nf_ct_generic_timeout; ret = generic_kmemdup_compat_sysctl_table(pn, gn); if (ret < 0) return ret; ret = generic_kmemdup_sysctl_table(pn, gn); if (ret < 0) nf_ct_kfree_compat_sysctl_table(pn); return ret; } static struct nf_proto_net *generic_get_net_proto(struct net *net) { return &net->ct.nf_ct_proto.generic.pn; } struct nf_conntrack_l4proto nf_conntrack_l4proto_generic __read_mostly = { .l3proto = PF_UNSPEC, .l4proto = 255, .name = "unknown", .pkt_to_tuple = generic_pkt_to_tuple, .invert_tuple = generic_invert_tuple, .print_tuple = generic_print_tuple, .packet = generic_packet, .get_timeouts = generic_get_timeouts, .new = generic_new, #if IS_ENABLED(CONFIG_NF_CT_NETLINK_TIMEOUT) .ctnl_timeout = { .nlattr_to_obj = generic_timeout_nlattr_to_obj, .obj_to_nlattr = generic_timeout_obj_to_nlattr, .nlattr_max = CTA_TIMEOUT_GENERIC_MAX, .obj_size = sizeof(unsigned int), .nla_policy = generic_timeout_nla_policy, }, #endif /* CONFIG_NF_CT_NETLINK_TIMEOUT */ .init_net = generic_init_net, .get_net_proto = generic_get_net_proto, };
./CrossVul/dataset_final_sorted/CWE-254/c/bad_2305_0
crossvul-cpp_data_bad_5205_1
/** @file packetParser.c @brief functions to parse and generate a ZRTP packet @author Johan Pascal @copyright Copyright (C) 2014 Belledonne Communications, Grenoble, France 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdlib.h> #include <string.h> #include "typedef.h" #include "packetParser.h" #include <bctoolbox/crypto.h> #include "cryptoUtils.h" /* DEBUG */ #include <stdio.h> /* minimum length of a ZRTP packet: 12 bytes header + 12 bytes message(shortest are ACK messages) + 4 bytes CRC */ #define ZRTP_MIN_PACKET_LENGTH 28 /* maximum length of a ZRTP packet: 3072 bytes get it from GNU-ZRTP CPP code */ #define ZRTP_MAX_PACKET_LENGTH 3072 /* header of ZRTP message is 12 bytes : Preambule/Message Length + Message Type(2 words) */ #define ZRTP_MESSAGE_HEADER_LENGTH 12 /* length of the non optional and fixed part of all messages, in bytes */ #define ZRTP_HELLOMESSAGE_FIXED_LENGTH 88 #define ZRTP_HELLOACKMESSAGE_FIXED_LENGTH 12 #define ZRTP_COMMITMESSAGE_FIXED_LENGTH 84 #define ZRTP_DHPARTMESSAGE_FIXED_LENGTH 84 #define ZRTP_CONFIRMMESSAGE_FIXED_LENGTH 76 #define ZRTP_CONF2ACKMESSAGE_FIXED_LENGTH 12 #define ZRTP_ERRORMESSAGE_FIXED_LENGTH 16 #define ZRTP_ERRORACKMESSAGE_FIXED_LENGTH 12 #define ZRTP_GOCLEARMESSAGE_FIXED_LENGTH 20 #define ZRTP_CLEARACKMESSAGE_FIXED_LENGTH 12 #define ZRTP_SASRELAYMESSAGE_FIXED_LENGTH 76 #define ZRTP_RELAYACKMESSAGE_FIXED_LENGTH 12 #define ZRTP_PINGMESSAGE_FIXED_LENGTH 24 #define ZRTP_PINGACKMESSAGE_FIXED_LENGTH 36 /*** local functions prototypes ***/ /** * Return the variable private value length in bytes according to given key agreement algorythm * * @param[in] keyAgreementAlgo The key agreement algo mapped to an integer as defined in cryptoWrapper.h * * @return the private value length in bytes * */ uint16_t computeKeyAgreementPrivateValueLength(uint8_t keyAgreementAlgo); /** * @brief Retrieve the 8 char string value message type from the int32_t code * * @param[in] messageType The messageType code * * @return an 9 char string : 8 chars message type as specified in rfc section 5.1.1 + string terminating char */ uint8_t *messageTypeInttoString(uint32_t messageType); /** * @brief Map the 8 char string value message type to an int32_t * * @param[in] messageTypeString an 8 bytes string matching a zrtp message type * * @return a 32-bits unsigned integer mapping the message type */ int32_t messageTypeStringtoInt(uint8_t messageTypeString[8]); /** * @brief Write the message header(preambule, length, message type) into the given output buffer * * @param[out] outputBuffer Message starts at the begining of this buffer * @param[in] messageLength Message length in bytes! To be converted into 32bits words before being inserted in the message header * @param[in] messageType An 8 chars string for the message type (validity is not checked by this function) * */ void zrtpMessageSetHeader(uint8_t *outputBuffer, uint16_t messageLength, uint8_t messageType[8]); /*** Public functions implementation ***/ /* First call this function to check packet validity and create the packet structure */ bzrtpPacket_t *bzrtp_packetCheck(const uint8_t * input, uint16_t inputLength, uint16_t lastValidSequenceNumber, int *exitCode) { bzrtpPacket_t *zrtpPacket; uint16_t sequenceNumber; uint32_t packetCRC; uint16_t messageLength; uint32_t messageType; /* first check that the packet is a ZRTP one */ /* is the length compatible with a ZRTP packet */ if ((inputLength<ZRTP_MIN_PACKET_LENGTH) || (inputLength>ZRTP_MAX_PACKET_LENGTH)) { *exitCode = BZRTP_PARSER_ERROR_INVALIDPACKET; return NULL; } /* check ZRTP packet format from rfc section 5 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0 0 0 1|Not Used (set to zero) | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Magic Cookie 'ZRTP' (0x5a525450) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Identifier | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | ZRTP Message (length depends on Message Type) | | . . . | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | CRC (1 word) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+*/ if ((input[0]>>4 != 0x01) || (input[4]!= (uint8_t)((ZRTP_MAGIC_COOKIE>>24)&0xFF)) || (input[5]!= (uint8_t)((ZRTP_MAGIC_COOKIE>>16)&0xFF)) || (input[6]!= (uint8_t)((ZRTP_MAGIC_COOKIE>>8)&0xFF)) || (input[7]!= (uint8_t)(ZRTP_MAGIC_COOKIE&0xFF))) { *exitCode = BZRTP_PARSER_ERROR_INVALIDPACKET; return NULL; } /* Check the sequence number : it must be > to the last valid one (given in parameter) to discard out of order packets * TODO: what if we got a Sequence Number overflowing the 16 bits ? */ sequenceNumber = (((uint16_t)input[2])<<8) | ((uint16_t)input[3]); if (sequenceNumber <= lastValidSequenceNumber) { *exitCode = BZRTP_PARSER_ERROR_OUTOFORDER; return NULL; } /* Check the CRC : The CRC is calculated across the entire ZRTP packet, including the ZRTP header and the ZRTP message, but not including the CRC field.*/ packetCRC = ((((uint32_t)input[inputLength-4])<<24)&0xFF000000) | ((((uint32_t)input[inputLength-3])<<16)&0x00FF0000) | ((((uint32_t)input[inputLength-2])<<8)&0x0000FF00) | (((uint32_t)input[inputLength-1])&0x000000FF); if (bzrtp_CRC32((uint8_t *)input, inputLength - 4) != packetCRC) { *exitCode = BZRTP_PARSER_ERROR_INVALIDCRC; return NULL; } /* check message header : * 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0 1 0 1 0 0 0 0 0 1 0 1 1 0 1 0| length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Message Type Block (2 words) | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+*/ if ((input[ZRTP_PACKET_HEADER_LENGTH]!=0x50) || (input[ZRTP_PACKET_HEADER_LENGTH+1]!=0x5a)) { *exitCode = BZRTP_PARSER_ERROR_INVALIDMESSAGE; return NULL; } /* get the length from the message: it is expressed in 32bits words, convert it to bytes (4*) */ messageLength = 4*(((((uint16_t)input[ZRTP_PACKET_HEADER_LENGTH+2])<<8)&0xFF00) | (((uint16_t)input[ZRTP_PACKET_HEADER_LENGTH+3])&0x00FF)); /* get the message Type */ messageType = messageTypeStringtoInt((uint8_t *)(input+ZRTP_PACKET_HEADER_LENGTH+4)); if (messageType == MSGTYPE_INVALID) { *exitCode = BZRTP_PARSER_ERROR_INVALIDMESSAGE; return NULL; } /* packet and message seems to be valid, so allocate a structure and parse it */ zrtpPacket = (bzrtpPacket_t *)malloc(sizeof(bzrtpPacket_t)); memset(zrtpPacket, 0, sizeof(bzrtpPacket_t)); zrtpPacket->sequenceNumber = sequenceNumber; zrtpPacket->messageLength = messageLength; zrtpPacket->messageType = messageType; zrtpPacket->messageData = NULL; zrtpPacket->packetString = NULL; /* get the SSRC */ zrtpPacket->sourceIdentifier = ((((uint32_t)input[8])<<24)&0xFF000000) | ((((uint32_t)input[9])<<16)&0x00FF0000) | ((((uint32_t)input[10])<<8)&0x0000FF00) | (((uint32_t)input[11])&0x000000FF); *exitCode = 0; return zrtpPacket; } #define MIN(a, b) (((a) < (b)) ? (a) : (b)) /* Call this function after the packetCheck one, to actually parse the packet : create and fill the messageData structure */ int bzrtp_packetParser(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, const uint8_t * input, uint16_t inputLength, bzrtpPacket_t *zrtpPacket) { int i; /* now allocate and fill the correct message structure according to the message type */ /* messageContent points to the begining of the ZRTP message */ uint8_t *messageContent = (uint8_t *)(input+ZRTP_PACKET_HEADER_LENGTH+ZRTP_MESSAGE_HEADER_LENGTH); switch (zrtpPacket->messageType) { case MSGTYPE_HELLO : { /* allocate a Hello message structure */ bzrtpHelloMessage_t *messageData; messageData = (bzrtpHelloMessage_t *)malloc(sizeof(bzrtpHelloMessage_t)); /* fill it */ memcpy(messageData->version, messageContent, 4); messageContent +=4; memcpy(messageData->clientIdentifier, messageContent, 16); messageContent +=16; memcpy(messageData->H3, messageContent, 32); messageContent +=32; memcpy(messageData->ZID, messageContent, 12); messageContent +=12; messageData->S = ((*messageContent)>>6)&0x01; messageData->M = ((*messageContent)>>5)&0x01; messageData->P = ((*messageContent)>>4)&0x01; messageContent +=1; messageData->hc = MIN((*messageContent)&0x0F, 7); messageContent +=1; messageData->cc = MIN(((*messageContent)>>4)&0x0F, 7); messageData->ac = MIN((*messageContent)&0x0F, 7); messageContent +=1; messageData->kc = MIN(((*messageContent)>>4)&0x0F, 7); messageData->sc = MIN((*messageContent)&0x0F, 7); messageContent +=1; /* Check message length according to value in hc, cc, ac, kc and sc */ if (zrtpPacket->messageLength != ZRTP_HELLOMESSAGE_FIXED_LENGTH + 4*((uint16_t)(messageData->hc)+(uint16_t)(messageData->cc)+(uint16_t)(messageData->ac)+(uint16_t)(messageData->kc)+(uint16_t)(messageData->sc))) { free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } /* parse the variable length part: algorithms types */ for (i=0; i<messageData->hc; i++) { messageData->supportedHash[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_HASH_TYPE); messageContent +=4; } for (i=0; i<messageData->cc; i++) { messageData->supportedCipher[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_CIPHERBLOCK_TYPE); messageContent +=4; } for (i=0; i<messageData->ac; i++) { messageData->supportedAuthTag[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_AUTHTAG_TYPE); messageContent +=4; } for (i=0; i<messageData->kc; i++) { messageData->supportedKeyAgreement[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_KEYAGREEMENT_TYPE); messageContent +=4; } for (i=0; i<messageData->sc; i++) { messageData->supportedSas[i] = cryptoAlgoTypeStringToInt(messageContent, ZRTP_SAS_TYPE); messageContent +=4; } addMandatoryCryptoTypesIfNeeded(ZRTP_HASH_TYPE, messageData->supportedHash, &messageData->hc); addMandatoryCryptoTypesIfNeeded(ZRTP_CIPHERBLOCK_TYPE, messageData->supportedCipher, &messageData->cc); addMandatoryCryptoTypesIfNeeded(ZRTP_AUTHTAG_TYPE, messageData->supportedAuthTag, &messageData->ac); addMandatoryCryptoTypesIfNeeded(ZRTP_KEYAGREEMENT_TYPE, messageData->supportedKeyAgreement, &messageData->kc); addMandatoryCryptoTypesIfNeeded(ZRTP_SAS_TYPE, messageData->supportedSas, &messageData->sc); memcpy(messageData->MAC, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; /* the parsed Hello packet must be saved as it may be used to generate commit message or the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_HELLO */ case MSGTYPE_HELLOACK : { /* check message length */ if (zrtpPacket->messageLength != ZRTP_HELLOACKMESSAGE_FIXED_LENGTH) { return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } } break; /* MSGTYPE_HELLOACK */ case MSGTYPE_COMMIT: { uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; uint16_t variableLength = 0; /* allocate a commit message structure */ bzrtpCommitMessage_t *messageData; messageData = (bzrtpCommitMessage_t *)malloc(sizeof(bzrtpCommitMessage_t)); /* fill the structure */ memcpy(messageData->H2, messageContent, 32); messageContent +=32; /* We have now H2, check it matches the H3 we had in the hello message H3=SHA256(H2) and that the Hello message MAC is correct */ if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this commit shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(H2) */ bctoolbox_sha256(messageData->H2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } memcpy(messageData->ZID, messageContent, 12); messageContent +=12; messageData->hashAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_HASH_TYPE); messageContent += 4; messageData->cipherAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_CIPHERBLOCK_TYPE); messageContent += 4; messageData->authTagAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_AUTHTAG_TYPE); messageContent += 4; messageData->keyAgreementAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_KEYAGREEMENT_TYPE); messageContent += 4; /* commit message length depends on the key agreement type choosen (and set in the zrtpContext->keyAgreementAlgo) */ switch(messageData->keyAgreementAlgo) { case ZRTP_KEYAGREEMENT_DH2k : case ZRTP_KEYAGREEMENT_EC25 : case ZRTP_KEYAGREEMENT_DH3k : case ZRTP_KEYAGREEMENT_EC38 : case ZRTP_KEYAGREEMENT_EC52 : variableLength = 32; /* hvi is 32 bytes length in DH Commit message format */ break; case ZRTP_KEYAGREEMENT_Prsh : variableLength = 24; /* nonce (16 bytes) and keyID(8 bytes) are 24 bytes length in preshared Commit message format */ break; case ZRTP_KEYAGREEMENT_Mult : variableLength = 16; /* nonce is 24 bytes length in multistream Commit message format */ break; default: free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } if (zrtpPacket->messageLength != ZRTP_COMMITMESSAGE_FIXED_LENGTH + variableLength) { free(messageData); return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } messageData->sasAlgo = cryptoAlgoTypeStringToInt(messageContent, ZRTP_SAS_TYPE); messageContent += 4; /* if it is a multistream or preshared commit, get the 16 bytes nonce */ if ((messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) { memcpy(messageData->nonce, messageContent, 16); messageContent +=16; /* and the keyID for preshared commit only */ if (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) { memcpy(messageData->keyID, messageContent, 8); messageContent +=8; } } else { /* it's a DH commit message, get the hvi */ memcpy(messageData->hvi, messageContent, 32); messageContent +=32; } /* get the MAC and attach the message data to the packet structure */ memcpy(messageData->MAC, messageContent, 8); zrtpPacket->messageData = (void *)messageData; /* the parsed commit packet must be saved as it is used to generate the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_COMMIT */ case MSGTYPE_DHPART1 : case MSGTYPE_DHPART2 : { bzrtpDHPartMessage_t *messageData; /*check message length, depends on the selected key agreement algo set in zrtpContext */ uint16_t pvLength = computeKeyAgreementPrivateValueLength(zrtpChannelContext->keyAgreementAlgo); if (pvLength == 0) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } if (zrtpPacket->messageLength != ZRTP_DHPARTMESSAGE_FIXED_LENGTH+pvLength) { return BZRTP_PARSER_ERROR_INVALIDMESSAGE; } /* allocate a DHPart message structure and pv */ messageData = (bzrtpDHPartMessage_t *)malloc(sizeof(bzrtpDHPartMessage_t)); messageData->pv = (uint8_t *)malloc(pvLength*sizeof(uint8_t)); /* fill the structure */ memcpy(messageData->H1, messageContent, 32); messageContent +=32; /* We have now H1, check it matches the H2 we had in the commit message H2=SHA256(H1) and that the Commit message MAC is correct */ if ( zrtpChannelContext->role == RESPONDER) { /* do it only if we are responder (we received a commit packet) */ uint8_t checkH2[32]; uint8_t checkMAC[32]; bzrtpCommitMessage_t *peerCommitMessageData; if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Commit message in this channel, this DHPart2 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageData; /* Check H2 = SHA256(H1) */ bctoolbox_sha256(messageData->H1, 32, 32, checkH2); if (memcmp(checkH2, peerCommitMessageData->H2, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the Commit MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H1, 32, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerCommitMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } else { /* if we are initiator(we didn't received any commit message and then no H2), we must check that H3=SHA256(SHA256(H1)) and the Hello message MAC */ uint8_t checkH2[32]; uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this DHPart1 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(SHA256(H1)) */ bctoolbox_sha256(messageData->H1, 32, 32, checkH2); bctoolbox_sha256(checkH2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } memcpy(messageData->rs1ID, messageContent, 8); messageContent +=8; memcpy(messageData->rs2ID, messageContent, 8); messageContent +=8; memcpy(messageData->auxsecretID, messageContent, 8); messageContent +=8; memcpy(messageData->pbxsecretID, messageContent, 8); messageContent +=8; memcpy(messageData->pv, messageContent, pvLength); messageContent +=pvLength; memcpy(messageData->MAC, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; /* the parsed commit packet must be saved as it is used to generate the total_hash */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ } break; /* MSGTYPE_DHPART1 and MSGTYPE_DHPART2 */ case MSGTYPE_CONFIRM1: case MSGTYPE_CONFIRM2: { uint8_t *confirmMessageKey = NULL; uint8_t *confirmMessageMacKey = NULL; bzrtpConfirmMessage_t *messageData; uint16_t cipherTextLength; uint8_t computedHmac[8]; uint8_t *confirmPlainMessageBuffer; uint8_t *confirmPlainMessage; /* we shall first decrypt and validate the message, check we have the keys to do it */ if (zrtpChannelContext->role == RESPONDER) { /* responder uses initiator's keys to decrypt */ if ((zrtpChannelContext->zrtpkeyi == NULL) || (zrtpChannelContext->mackeyi == NULL)) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyi; confirmMessageMacKey = zrtpChannelContext->mackeyi; } if (zrtpChannelContext->role == INITIATOR) { /* the iniator uses responder's keys to decrypt */ if ((zrtpChannelContext->zrtpkeyr == NULL) || (zrtpChannelContext->mackeyr == NULL)) { return BZRTP_PARSER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyr; confirmMessageMacKey = zrtpChannelContext->mackeyr; } /* allocate a confirm message structure */ messageData = (bzrtpConfirmMessage_t *)malloc(sizeof(bzrtpConfirmMessage_t)); /* get the mac and the IV */ memcpy(messageData->confirm_mac, messageContent, 8); messageContent +=8; memcpy(messageData->CFBIV, messageContent, 16); messageContent +=16; /* get the cipher text length */ cipherTextLength = zrtpPacket->messageLength - ZRTP_MESSAGE_HEADER_LENGTH - 24; /* confirm message is header, confirm_mac(8 bytes), CFB IV(16 bytes), encrypted part */ /* validate the mac over the cipher text */ zrtpChannelContext->hmacFunction(confirmMessageMacKey, zrtpChannelContext->hashLength, messageContent, cipherTextLength, 8, computedHmac); if (memcmp(computedHmac, messageData->confirm_mac, 8) != 0) { /* confirm_mac doesn't match */ free(messageData); return BZRTP_PARSER_ERROR_UNMATCHINGCONFIRMMAC; } /* get plain message */ confirmPlainMessageBuffer = (uint8_t *)malloc(cipherTextLength*sizeof(uint8_t)); zrtpChannelContext->cipherDecryptionFunction(confirmMessageKey, messageData->CFBIV, messageContent, cipherTextLength, confirmPlainMessageBuffer); confirmPlainMessage = confirmPlainMessageBuffer; /* point into the allocated buffer */ /* parse it */ memcpy(messageData->H0, confirmPlainMessage, 32); confirmPlainMessage +=33; /* +33 because next 8 bits are unused */ /* Hash chain checking: if we are in multichannel or shared mode, we had not DHPart and then no H1 */ if (zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh || zrtpChannelContext->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult) { /* compute the H1=SHA256(H0) we never received */ uint8_t checkH1[32]; bctoolbox_sha256(messageData->H0, 32, 32, checkH1); /* if we are responder, we received a commit packet with H2 then check that H2=SHA256(H1) and that the commit message MAC keyed with H1 match */ if ( zrtpChannelContext->role == RESPONDER) { uint8_t checkH2[32]; uint8_t checkMAC[32]; bzrtpCommitMessage_t *peerCommitMessageData; if (zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Commit message in this channel, this Confirm2 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageData; /* Check H2 = SHA256(H1) */ bctoolbox_sha256(checkH1, 32, 32, checkH2); if (memcmp(checkH2, peerCommitMessageData->H2, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the Commit MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH1, 32, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[COMMIT_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerCommitMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } else { /* if we are initiator(we didn't received any commit message and then no H2), we must check that H3=SHA256(SHA256(H1)) and the Hello message MAC */ uint8_t checkH2[32]; uint8_t checkH3[32]; uint8_t checkMAC[32]; bzrtpHelloMessage_t *peerHelloMessageData; if (zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no Hello message in this channel, this Confirm1 shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerHelloMessageData = (bzrtpHelloMessage_t *)zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageData; /* Check H3 = SHA256(SHA256(H1)) */ bctoolbox_sha256(checkH1, 32, 32, checkH2); bctoolbox_sha256(checkH2, 32, 32, checkH3); if (memcmp(checkH3, peerHelloMessageData->H3, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the hello MAC message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(checkH2, 32, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerHelloMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } } else { /* we are in DHM mode */ /* We have now H0, check it matches the H1 we had in the DHPart message H1=SHA256(H0) and that the DHPart message MAC is correct */ uint8_t checkH1[32]; uint8_t checkMAC[32]; bzrtpDHPartMessage_t *peerDHPartMessageData; if (zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID] == NULL) { free (messageData); /* we have no DHPART message in this channel, this confirm shall never have arrived, discard it as invalid */ return BZRTP_PARSER_ERROR_UNEXPECTEDMESSAGE; } peerDHPartMessageData = (bzrtpDHPartMessage_t *)zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageData; /* Check H1 = SHA256(H0) */ bctoolbox_sha256(messageData->H0, 32, 32, checkH1); if (memcmp(checkH1, peerDHPartMessageData->H1, 32) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGHASHCHAIN; } /* Check the DHPart message. * MAC is 8 bytes long and is computed on the message(skip the ZRTP_PACKET_HEADER) and exclude the mac itself (-8 bytes from message Length) */ bctoolbox_hmacSha256(messageData->H0, 32, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpChannelContext->peerPackets[DHPART_MESSAGE_STORE_ID]->messageLength-8, 8, checkMAC); if (memcmp(checkMAC, peerDHPartMessageData->MAC, 8) != 0) { free (messageData); return BZRTP_PARSER_ERROR_UNMATCHINGMAC; } } messageData->sig_len = ((uint16_t)(confirmPlainMessage[0]&0x01))<<8 | (((uint16_t)confirmPlainMessage[1])&0x00FF); confirmPlainMessage += 2; messageData->E = ((*confirmPlainMessage)&0x08)>>3; messageData->V = ((*confirmPlainMessage)&0x04)>>2; messageData->A = ((*confirmPlainMessage)&0x02)>>1; messageData->D = (*confirmPlainMessage)&0x01; confirmPlainMessage += 1; messageData->cacheExpirationInterval = (((uint32_t)confirmPlainMessage[0])<<24) | (((uint32_t)confirmPlainMessage[1])<<16) | (((uint32_t)confirmPlainMessage[2])<<8) | ((uint32_t)confirmPlainMessage[3]); confirmPlainMessage += 4; /* if sig_len indicate a signature, parse it */ if (messageData->sig_len>0) { memcpy(messageData->signatureBlockType, confirmPlainMessage, 4); confirmPlainMessage += 4; /* allocate memory for the signature block, sig_len is in words(32 bits) and includes the signature block type word */ messageData->signatureBlock = (uint8_t *)malloc(4*(messageData->sig_len-1)*sizeof(uint8_t)); memcpy(messageData->signatureBlock, confirmPlainMessage, 4*(messageData->sig_len-1)); } else { messageData->signatureBlock = NULL; } /* free plain buffer */ free(confirmPlainMessageBuffer); /* the parsed commit packet must be saved as it is used to check correct packet repetition */ zrtpPacket->packetString = (uint8_t *)malloc(inputLength*sizeof(uint8_t)); memcpy(zrtpPacket->packetString, input, inputLength); /* store the whole packet even if we may use the message only */ /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; } break; /* MSGTYPE_CONFIRM1 and MSGTYPE_CONFIRM2 */ case MSGTYPE_CONF2ACK: /* nothing to do for this one */ break; /* MSGTYPE_CONF2ACK */ case MSGTYPE_PING: { /* allocate a ping message structure */ bzrtpPingMessage_t *messageData; messageData = (bzrtpPingMessage_t *)malloc(sizeof(bzrtpPingMessage_t)); /* fill the structure */ memcpy(messageData->version, messageContent, 4); messageContent +=4; memcpy(messageData->endpointHash, messageContent, 8); /* attach the message structure to the packet one */ zrtpPacket->messageData = (void *)messageData; } break; /* MSGTYPE_PING */ } return 0; } /* Create the packet string from the messageData contained into the zrtp Packet structure */ int bzrtp_packetBuild(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, bzrtpPacket_t *zrtpPacket, uint16_t sequenceNumber) { int i; uint8_t *messageTypeString; uint8_t *messageString = NULL; /* will point directly to the begining of the message within the packetString buffer */ uint8_t *MACbuffer = NULL; /* if needed this will point to the beginin of the MAC in the packetString buffer */ /*uint8_t *MACMessageData = NULL; */ /* if needed this will point to the MAC field in the message Data structure */ uint8_t *MACkey = NULL; /* checks */ if (zrtpPacket==NULL) { return BZRTP_BUILDER_ERROR_INVALIDPACKET; } /* get the message type (and check it is valid) */ messageTypeString = messageTypeInttoString(zrtpPacket->messageType); if (messageTypeString == NULL) { return BZRTP_BUILDER_ERROR_INVALIDMESSAGETYPE; } /* create first the message. Header and CRC will be added afterward */ switch (zrtpPacket->messageType) { case MSGTYPE_HELLO : { bzrtpHelloMessage_t *messageData; /* get the Hello message structure */ if (zrtpPacket->messageData == NULL) { return BZRTP_BUILDER_ERROR_INVALIDMESSAGE; } messageData = (bzrtpHelloMessage_t *)zrtpPacket->messageData; /* compute the message length in bytes : fixed length and optionnal algorithms parts */ zrtpPacket->messageLength = ZRTP_HELLOMESSAGE_FIXED_LENGTH + 4*((uint16_t)(messageData->hc)+(uint16_t)(messageData->cc)+(uint16_t)(messageData->ac)+(uint16_t)(messageData->kc)+(uint16_t)(messageData->sc)); /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+zrtpPacket->messageLength+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); /* have the messageString pointer to the begining of message(after the message header wich is computed for all messages after the switch) * within the packetString buffer*/ messageString = zrtpPacket->packetString + ZRTP_PACKET_HEADER_LENGTH + ZRTP_MESSAGE_HEADER_LENGTH; /* set the version (shall be 1.10), Client identifier, H3, ZID, S,M,P flags and hc,cc,ac,kc,sc */ memcpy(messageString, messageData->version, 4); messageString += 4; memcpy(messageString, messageData->clientIdentifier, 16); messageString += 16; memcpy(messageString, messageData->H3, 32); messageString += 32; memcpy(messageString, messageData->ZID, 12); messageString += 12; *messageString = ((((messageData->S)&0x01)<<6) | (((messageData->M)&0x01)<<5) | (((messageData->P)&0x01)<<4))&0x70; messageString += 1; *messageString = (messageData->hc)&0x0F; messageString += 1; *messageString = (((messageData->cc)<<4)&0xF0) | ((messageData->ac)&0x0F) ; messageString += 1; *messageString = (((messageData->kc)<<4)&0xF0) | ((messageData->sc)&0x0F) ; messageString += 1; /* now set optionnal supported algorithms */ for (i=0; i<messageData->hc; i++) { cryptoAlgoTypeIntToString(messageData->supportedHash[i], messageString); messageString +=4; } for (i=0; i<messageData->cc; i++) { cryptoAlgoTypeIntToString(messageData->supportedCipher[i], messageString); messageString +=4; } for (i=0; i<messageData->ac; i++) { cryptoAlgoTypeIntToString(messageData->supportedAuthTag[i], messageString); messageString +=4; } for (i=0; i<messageData->kc; i++) { cryptoAlgoTypeIntToString(messageData->supportedKeyAgreement[i], messageString); messageString +=4; } for (i=0; i<messageData->sc; i++) { cryptoAlgoTypeIntToString(messageData->supportedSas[i], messageString); messageString +=4; } /* there is a MAC to compute, set the pointers to the key and MAC output buffer */ MACbuffer = messageString; MACkey = zrtpChannelContext->selfH[2]; /* HMAC of Hello packet is keyed by H2 which have been set at context initialising */ } break; /* MSGTYPE_HELLO */ case MSGTYPE_HELLOACK : { /* the message length is fixed */ zrtpPacket->messageLength = ZRTP_HELLOACKMESSAGE_FIXED_LENGTH; /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+ZRTP_HELLOACKMESSAGE_FIXED_LENGTH+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); } break; /* MSGTYPE_HELLOACK */ case MSGTYPE_COMMIT : { bzrtpCommitMessage_t *messageData; uint16_t variableLength = 0; /* get the Commit message structure */ if (zrtpPacket->messageData == NULL) { return BZRTP_BUILDER_ERROR_INVALIDMESSAGE; } messageData = (bzrtpCommitMessage_t *)zrtpPacket->messageData; /* compute message length */ switch(messageData->keyAgreementAlgo) { case ZRTP_KEYAGREEMENT_DH2k : case ZRTP_KEYAGREEMENT_EC25 : case ZRTP_KEYAGREEMENT_DH3k : case ZRTP_KEYAGREEMENT_EC38 : case ZRTP_KEYAGREEMENT_EC52 : variableLength = 32; /* hvi is 32 bytes length in DH Commit message format */ break; case ZRTP_KEYAGREEMENT_Prsh : variableLength = 24; /* nonce (16 bytes) and keyID(8 bytes) are 24 bytes length in preshared Commit message format */ break; case ZRTP_KEYAGREEMENT_Mult : variableLength = 16; /* nonce is 24 bytes length in multistream Commit message format */ break; default: return BZRTP_BUILDER_ERROR_INVALIDMESSAGE; } zrtpPacket->messageLength = ZRTP_COMMITMESSAGE_FIXED_LENGTH + variableLength; /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+zrtpPacket->messageLength+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); /* have the messageString pointer to the begining of message(after the message header wich is computed for all messages after the switch) * within the packetString buffer*/ messageString = zrtpPacket->packetString + ZRTP_PACKET_HEADER_LENGTH + ZRTP_MESSAGE_HEADER_LENGTH; /* now insert the different message parts into the packetString */ memcpy(messageString, messageData->H2, 32); messageString += 32; memcpy(messageString, messageData->ZID, 12); messageString += 12; cryptoAlgoTypeIntToString(messageData->hashAlgo, messageString); messageString += 4; cryptoAlgoTypeIntToString(messageData->cipherAlgo, messageString); messageString += 4; cryptoAlgoTypeIntToString(messageData->authTagAlgo, messageString); messageString += 4; cryptoAlgoTypeIntToString(messageData->keyAgreementAlgo, messageString); messageString += 4; cryptoAlgoTypeIntToString(messageData->sasAlgo, messageString); messageString += 4; /* if it is a multistream or preshared commit insert the 16 bytes nonce */ if ((messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) { memcpy(messageString, messageData->nonce, 16); messageString += 16; /* and the keyID for preshared commit only */ if (messageData->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) { memcpy(messageString, messageData->keyID, 8); messageString +=8; } } else { /* it's a DH commit message, set the hvi */ memcpy(messageString, messageData->hvi, 32); messageString +=32; } /* there is a MAC to compute, set the pointers to the key and MAC output buffer */ MACbuffer = messageString; MACkey = zrtpChannelContext->selfH[1]; /* HMAC of Hello packet is keyed by H1 which have been set at context initialising */ } break; /*MSGTYPE_COMMIT */ case MSGTYPE_DHPART1 : case MSGTYPE_DHPART2 : { bzrtpDHPartMessage_t *messageData; uint16_t pvLength; /* get the DHPart message structure */ if (zrtpPacket->messageData == NULL) { return BZRTP_BUILDER_ERROR_INVALIDMESSAGE; } messageData = (bzrtpDHPartMessage_t *)zrtpPacket->messageData; /* compute message length */ pvLength = computeKeyAgreementPrivateValueLength(zrtpChannelContext->keyAgreementAlgo); if (pvLength==0) { return BZRTP_BUILDER_ERROR_INVALIDCONTEXT; } zrtpPacket->messageLength = ZRTP_DHPARTMESSAGE_FIXED_LENGTH + pvLength; /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+zrtpPacket->messageLength+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); /* have the messageString pointer to the begining of message(after the message header wich is computed for all messages after the switch) * within the packetString buffer*/ messageString = zrtpPacket->packetString + ZRTP_PACKET_HEADER_LENGTH + ZRTP_MESSAGE_HEADER_LENGTH; /* now insert the different message parts into the packetString */ memcpy(messageString, messageData->H1, 32); messageString += 32; memcpy(messageString, messageData->rs1ID, 8); messageString += 8; memcpy(messageString, messageData->rs2ID, 8); messageString += 8; memcpy(messageString, messageData->auxsecretID, 8); messageString += 8; memcpy(messageString, messageData->pbxsecretID, 8); messageString += 8; memcpy(messageString, messageData->pv, pvLength); messageString += pvLength; /* there is a MAC to compute, set the pointers to the key and MAC output buffer */ MACbuffer = messageString; MACkey = zrtpChannelContext->selfH[0]; /* HMAC of Hello packet is keyed by H0 which have been set at context initialising */ } break; /* MSGTYPE_DHPART1 and 2 */ case MSGTYPE_CONFIRM1: case MSGTYPE_CONFIRM2: { uint8_t *confirmMessageKey = NULL; uint8_t *confirmMessageMacKey = NULL; bzrtpConfirmMessage_t *messageData; uint16_t encryptedPartLength; uint8_t *plainMessageString; uint16_t plainMessageStringIndex = 0; /* we will have to encrypt and validate the message, check we have the keys to do it */ if (zrtpChannelContext->role == INITIATOR) { if ((zrtpChannelContext->zrtpkeyi == NULL) || (zrtpChannelContext->mackeyi == NULL)) { return BZRTP_BUILDER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyi; confirmMessageMacKey = zrtpChannelContext->mackeyi; } if (zrtpChannelContext->role == RESPONDER) { if ((zrtpChannelContext->zrtpkeyr == NULL) || (zrtpChannelContext->mackeyr == NULL)) { return BZRTP_BUILDER_ERROR_INVALIDCONTEXT; } confirmMessageKey = zrtpChannelContext->zrtpkeyr; confirmMessageMacKey = zrtpChannelContext->mackeyr; } /* get the Confirm message structure */ if (zrtpPacket->messageData == NULL) { return BZRTP_BUILDER_ERROR_INVALIDMESSAGE; } messageData = (bzrtpConfirmMessage_t *)zrtpPacket->messageData; /* compute message length */ zrtpPacket->messageLength = ZRTP_CONFIRMMESSAGE_FIXED_LENGTH + messageData->sig_len*4; /* sig_len is in word of 4 bytes */ /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+zrtpPacket->messageLength+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); /* have the messageString pointer to the begining of message(after the message header wich is computed for all messages after the switch) * within the packetString buffer*/ messageString = zrtpPacket->packetString + ZRTP_PACKET_HEADER_LENGTH + ZRTP_MESSAGE_HEADER_LENGTH; /* allocate a temporary buffer to store the plain text */ encryptedPartLength = zrtpPacket->messageLength - ZRTP_MESSAGE_HEADER_LENGTH - 24; /* message header, confirm_mac(8 bytes) and CFB IV(16 bytes) are not encrypted */ plainMessageString = (uint8_t *)malloc(encryptedPartLength*sizeof(uint8_t)); /* fill the plain message buffer with data from the message structure */ memcpy(plainMessageString, messageData->H0, 32); plainMessageStringIndex += 32; plainMessageString[plainMessageStringIndex++] = 0x00; plainMessageString[plainMessageStringIndex++] = (uint8_t)(((messageData->sig_len)>>8)&0x0001); plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->sig_len)&0x00FF); plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->E&0x01)<<3) | (uint8_t)((messageData->V&0x01)<<2) | (uint8_t)((messageData->A&0x01)<<1) | (uint8_t)(messageData->D&0x01) ; /* cache expiration in a 32 bits unsigned int */ plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->cacheExpirationInterval>>24)&0xFF); plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->cacheExpirationInterval>>16)&0xFF); plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->cacheExpirationInterval>>8)&0xFF); plainMessageString[plainMessageStringIndex++] = (uint8_t)((messageData->cacheExpirationInterval)&0xFF); if (messageData->sig_len>0) { memcpy(plainMessageString+plainMessageStringIndex, messageData->signatureBlockType, 4); plainMessageStringIndex += 4; /* sig_len is in 4 bytes words and include the 1 word of signature block type */ memcpy(plainMessageString+plainMessageStringIndex, messageData->signatureBlock, (messageData->sig_len-1)*4); } /* encrypt the buffer, set the output directly in the messageString buffer at the correct position(+24 after message header) */ zrtpChannelContext->cipherEncryptionFunction(confirmMessageKey, messageData->CFBIV, plainMessageString, encryptedPartLength, messageString+24); free(plainMessageString); /* free the plain message string temporary buffer */ /* compute the mac over the encrypted part of the message and set the result in the messageString */ zrtpChannelContext->hmacFunction(confirmMessageMacKey, zrtpChannelContext->hashLength, messageString+24, encryptedPartLength, 8, messageString); messageString += 8; /* add the CFB IV */ memcpy(messageString, messageData->CFBIV, 16); } break; /* MSGTYPE_CONFIRM1 and MSGTYPE_CONFIRM2 */ case MSGTYPE_CONF2ACK: { /* the message length is fixed */ zrtpPacket->messageLength = ZRTP_CONF2ACKMESSAGE_FIXED_LENGTH; /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+ZRTP_CONF2ACKMESSAGE_FIXED_LENGTH+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); } break; /* MSGTYPE_CONF2ACK */ case MSGTYPE_PINGACK: { bzrtpPingAckMessage_t *messageData; /* the message length is fixed */ zrtpPacket->messageLength = ZRTP_PINGACKMESSAGE_FIXED_LENGTH; /* allocate the packetString buffer : packet is header+message+crc */ zrtpPacket->packetString = (uint8_t *)malloc((ZRTP_PACKET_HEADER_LENGTH+ZRTP_PINGACKMESSAGE_FIXED_LENGTH+ZRTP_PACKET_CRC_LENGTH)*sizeof(uint8_t)); messageString = zrtpPacket->packetString + ZRTP_PACKET_HEADER_LENGTH + ZRTP_MESSAGE_HEADER_LENGTH; /* now insert the different message parts into the packetString */ messageData = (bzrtpPingAckMessage_t *)zrtpPacket->messageData; memcpy(messageString, messageData->version, 4); messageString += 4; memcpy(messageString, messageData->endpointHash, 8); messageString += 8; memcpy(messageString, messageData->endpointHashReceived, 8); messageString += 8; *messageString++ = (uint8_t)((messageData->SSRC>>24)&0xFF); *messageString++ = (uint8_t)((messageData->SSRC>>16)&0xFF); *messageString++ = (uint8_t)((messageData->SSRC>>8)&0xFF); *messageString++ = (uint8_t)(messageData->SSRC&0xFF); } break; /* MSGTYPE_PINGACK */ } /* write headers only if we have a packet string */ if (zrtpPacket->packetString != NULL) { uint32_t CRC; uint8_t *CRCbuffer; zrtpMessageSetHeader(zrtpPacket->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpPacket->messageLength, messageTypeString); /* Do we have a MAC to compute on the message ? */ if (MACbuffer != NULL) { /* compute the MAC(64 bits only) using the implicit HMAC function for ZRTP v1.10: HMAC-SHA256 */ /* HMAC is computed on the whole message except the MAC itself so a length of zrtpPacket->messageLength-8 */ bctoolbox_hmacSha256(MACkey, 32, zrtpPacket->packetString+ZRTP_PACKET_HEADER_LENGTH, zrtpPacket->messageLength-8, 8, MACbuffer); } /* set packet header and CRC */ /* preambule */ zrtpPacket->packetString[0] = 0x10; zrtpPacket->packetString[1] = 0x00; /* Sequence number */ zrtpPacket->packetString[2] = (uint8_t)((sequenceNumber>>8)&0x00FF); zrtpPacket->packetString[3] = (uint8_t)(sequenceNumber&0x00FF); /* ZRTP magic cookie */ zrtpPacket->packetString[4] = (uint8_t)((ZRTP_MAGIC_COOKIE>>24)&0xFF); zrtpPacket->packetString[5] = (uint8_t)((ZRTP_MAGIC_COOKIE>>16)&0xFF); zrtpPacket->packetString[6] = (uint8_t)((ZRTP_MAGIC_COOKIE>>8)&0xFF); zrtpPacket->packetString[7] = (uint8_t)(ZRTP_MAGIC_COOKIE&0xFF); /* Source Identifier */ zrtpPacket->packetString[8] = (uint8_t)(((zrtpPacket->sourceIdentifier)>>24)&0xFF); zrtpPacket->packetString[9] = (uint8_t)(((zrtpPacket->sourceIdentifier)>>16)&0xFF); zrtpPacket->packetString[10] = (uint8_t)(((zrtpPacket->sourceIdentifier)>>8)&0xFF); zrtpPacket->packetString[11] = (uint8_t)((zrtpPacket->sourceIdentifier)&0xFF); /* CRC */ CRC = bzrtp_CRC32(zrtpPacket->packetString, zrtpPacket->messageLength+ZRTP_PACKET_HEADER_LENGTH); CRCbuffer = (zrtpPacket->packetString)+(zrtpPacket->messageLength)+ZRTP_PACKET_HEADER_LENGTH; *CRCbuffer = (uint8_t)((CRC>>24)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>16)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>8)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)(CRC&0xFF); return 0; } else { /* no packetString allocated something wen't wrong but we shall never arrive here */ return BZRTP_BUILDER_ERROR_UNKNOWN; } } /* create a zrtpPacket and initialise it's structures */ bzrtpPacket_t *bzrtp_createZrtpPacket(bzrtpContext_t *zrtpContext, bzrtpChannelContext_t *zrtpChannelContext, uint32_t messageType, int *exitCode) { /* allocate packet */ bzrtpPacket_t *zrtpPacket = (bzrtpPacket_t *)malloc(sizeof(bzrtpPacket_t)); memset(zrtpPacket, 0, sizeof(bzrtpPacket_t)); zrtpPacket->messageData = NULL; zrtpPacket->packetString = NULL; /* initialise it */ switch(messageType) { case MSGTYPE_HELLO: { int i; bzrtpHelloMessage_t *zrtpHelloMessage = (bzrtpHelloMessage_t *)malloc(sizeof(bzrtpHelloMessage_t)); memset(zrtpHelloMessage, 0, sizeof(bzrtpHelloMessage_t)); /* initialise some fields using zrtp context data */ memcpy(zrtpHelloMessage->version, ZRTP_VERSION, 4); strncpy((char*)zrtpHelloMessage->clientIdentifier, ZRTP_CLIENT_IDENTIFIER, 16); memcpy(zrtpHelloMessage->H3, zrtpChannelContext->selfH[3], 32); memcpy(zrtpHelloMessage->ZID, zrtpContext->selfZID, 12); /* set all S,M,P flags to zero as we're not able to verify signatures, we're not a PBX(TODO: implement?), we're not passive */ zrtpHelloMessage->S = 0; zrtpHelloMessage->M = 0; zrtpHelloMessage->P = 0; /* get the algorithm availabilities from the context */ zrtpHelloMessage->hc = zrtpContext->hc; zrtpHelloMessage->cc = zrtpContext->cc; zrtpHelloMessage->ac = zrtpContext->ac; zrtpHelloMessage->kc = zrtpContext->kc; zrtpHelloMessage->sc = zrtpContext->sc; for (i=0; i<zrtpContext->hc; i++) { zrtpHelloMessage->supportedHash[i] = zrtpContext->supportedHash[i]; } for (i=0; i<zrtpContext->cc; i++) { zrtpHelloMessage->supportedCipher[i] = zrtpContext->supportedCipher[i]; } for (i=0; i<zrtpContext->ac; i++) { zrtpHelloMessage->supportedAuthTag[i] = zrtpContext->supportedAuthTag[i]; } for (i=0; i<zrtpContext->kc; i++) { zrtpHelloMessage->supportedKeyAgreement[i] = zrtpContext->supportedKeyAgreement[i]; } for (i=0; i<zrtpContext->sc; i++) { zrtpHelloMessage->supportedSas[i] = zrtpContext->supportedSas[i]; } /* attach the message data to the packet */ zrtpPacket->messageData = zrtpHelloMessage; } break; /* MSGTYPE_HELLO */ case MSGTYPE_HELLOACK : { /* nothing to do for the Hello ACK packet as it just contains it's type */ } break; /* MSGTYPE_HELLOACK */ /* In case of DH commit, this one must be called after the DHPart build and the self DH message and peer Hello message are stored in the context */ case MSGTYPE_COMMIT : { bzrtpCommitMessage_t *zrtpCommitMessage = (bzrtpCommitMessage_t *)malloc(sizeof(bzrtpCommitMessage_t)); memset(zrtpCommitMessage, 0, sizeof(bzrtpCommitMessage_t)); /* initialise some fields using zrtp context data */ memcpy(zrtpCommitMessage->H2, zrtpChannelContext->selfH[2], 32); memcpy(zrtpCommitMessage->ZID, zrtpContext->selfZID, 12); zrtpCommitMessage->hashAlgo = zrtpChannelContext->hashAlgo; zrtpCommitMessage->cipherAlgo = zrtpChannelContext->cipherAlgo; zrtpCommitMessage->authTagAlgo = zrtpChannelContext->authTagAlgo; zrtpCommitMessage->keyAgreementAlgo = zrtpChannelContext->keyAgreementAlgo; zrtpCommitMessage->sasAlgo = zrtpChannelContext->sasAlgo; /* if it is a multistream or preshared commit create a 16 random bytes nonce */ if ((zrtpCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) || (zrtpCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Mult)) { bctoolbox_rng_get(zrtpContext->RNGContext, zrtpCommitMessage->nonce, 16); /* and the keyID for preshared commit only */ if (zrtpCommitMessage->keyAgreementAlgo == ZRTP_KEYAGREEMENT_Prsh) { /* TODO at this point we must first compute the preShared key - make sure at least rs1 is present */ /* preshared_key = hash(len(rs1) || rs1 || len(auxsecret) || auxsecret || len(pbxsecret) || pbxsecret) using the agreed hash and store it into the env */ /* and then the keyID : MAC(preshared_key, "Prsh") truncated to 64 bits using the agreed MAC */ } } else { /* it's a DH commit message, set the hvi */ /* hvi = hash(initiator's DHPart2 message || responder's Hello message) using the agreed hash function truncated to 256 bits */ /* create a string with the messages concatenated */ uint16_t DHPartMessageLength = zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->messageLength; uint16_t HelloMessageLength = zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->messageLength; uint16_t DHPartHelloMessageStringLength = DHPartMessageLength + HelloMessageLength; uint8_t *DHPartHelloMessageString = (uint8_t *)malloc(DHPartHelloMessageStringLength*sizeof(uint8_t)); memcpy(DHPartHelloMessageString, zrtpChannelContext->selfPackets[DHPART_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, DHPartMessageLength); memcpy(DHPartHelloMessageString+DHPartMessageLength, zrtpChannelContext->peerPackets[HELLO_MESSAGE_STORE_ID]->packetString+ZRTP_PACKET_HEADER_LENGTH, HelloMessageLength); zrtpChannelContext->hashFunction(DHPartHelloMessageString, DHPartHelloMessageStringLength, 32, zrtpCommitMessage->hvi); free(DHPartHelloMessageString); } /* attach the message data to the packet */ zrtpPacket->messageData = zrtpCommitMessage; } break; /* MSGTYPE_COMMIT */ /* this one is called after the exchange of Hello messages when the crypto algo agreement have been performed */ case MSGTYPE_DHPART1 : case MSGTYPE_DHPART2 : { uint8_t secretLength; /* is in bytes */ uint8_t bctoolbox_keyAgreementAlgo = BCTOOLBOX_DHM_UNSET; bzrtpDHPartMessage_t *zrtpDHPartMessage = (bzrtpDHPartMessage_t *)malloc(sizeof(bzrtpDHPartMessage_t)); memset(zrtpDHPartMessage, 0, sizeof(bzrtpDHPartMessage_t)); /* initialise some fields using zrtp context data */ memcpy(zrtpDHPartMessage->H1, zrtpChannelContext->selfH[1], 32); /* get the retained secret from context, we anyway create a DHPart2 packet that we may turn into a DHPart1 packet if we end to * be the responder and not the initiator, use the initiator retained secret hashes */ memcpy(zrtpDHPartMessage->rs1ID, zrtpContext->initiatorCachedSecretHash.rs1ID, 8); memcpy(zrtpDHPartMessage->rs2ID, zrtpContext->initiatorCachedSecretHash.rs2ID, 8); memcpy(zrtpDHPartMessage->auxsecretID, zrtpChannelContext->initiatorAuxsecretID, 8); memcpy(zrtpDHPartMessage->pbxsecretID, zrtpContext->initiatorCachedSecretHash.pbxsecretID, 8); /* compute the public value and insert it in the message, will then be used whatever role - initiator or responder - we assume */ /* initialise the dhm context, secret length shall be twice the size of cipher block key length - rfc section 5.1.5 */ switch (zrtpChannelContext->cipherAlgo) { case ZRTP_CIPHER_AES3: case ZRTP_CIPHER_2FS3: secretLength = 64; break; case ZRTP_CIPHER_AES2: case ZRTP_CIPHER_2FS2: secretLength = 48; break; case ZRTP_CIPHER_AES1: case ZRTP_CIPHER_2FS1: default: secretLength = 32; break; } switch (zrtpChannelContext->keyAgreementAlgo) { case ZRTP_KEYAGREEMENT_DH2k: bctoolbox_keyAgreementAlgo = BCTOOLBOX_DHM_2048; break; case ZRTP_KEYAGREEMENT_DH3k: bctoolbox_keyAgreementAlgo = BCTOOLBOX_DHM_3072; break; default: free(zrtpPacket); free(zrtpDHPartMessage); *exitCode = BZRTP_CREATE_ERROR_UNABLETOCREATECRYPTOCONTEXT; return NULL; break; } zrtpContext->DHMContext = bctoolbox_CreateDHMContext(bctoolbox_keyAgreementAlgo, secretLength); if (zrtpContext->DHMContext == NULL) { free(zrtpPacket); free(zrtpDHPartMessage); *exitCode = BZRTP_CREATE_ERROR_UNABLETOCREATECRYPTOCONTEXT; return NULL; } /* now compute the public value */ bctoolbox_DHMCreatePublic(zrtpContext->DHMContext, (int (*)(void *, uint8_t *, size_t))bctoolbox_rng_get, zrtpContext->RNGContext); zrtpDHPartMessage->pv = (uint8_t *)malloc((zrtpChannelContext->keyAgreementLength)*sizeof(uint8_t)); memcpy(zrtpDHPartMessage->pv, zrtpContext->DHMContext->self, zrtpChannelContext->keyAgreementLength); /* attach the message data to the packet */ zrtpPacket->messageData = zrtpDHPartMessage; } break; /* MSGTYPE_DHPART1 and MSGTYPE_DHPART2 */ case MSGTYPE_CONFIRM1: case MSGTYPE_CONFIRM2: { bzrtpConfirmMessage_t *zrtpConfirmMessage = (bzrtpConfirmMessage_t *)malloc(sizeof(bzrtpConfirmMessage_t)); memset(zrtpConfirmMessage, 0, sizeof(bzrtpConfirmMessage_t)); /* initialise some fields using zrtp context data */ memcpy(zrtpConfirmMessage->H0, zrtpChannelContext->selfH[0], 32); zrtpConfirmMessage->sig_len = 0; /* signature is not supported */ zrtpConfirmMessage->cacheExpirationInterval = 0xFFFFFFFF; /* expiration interval is set to unlimited as recommended in rfc section 4.9 */ zrtpConfirmMessage->E = 0; /* we are not a PBX and then will never signal an enrollment - rfc section 7.3.1 */ zrtpConfirmMessage->V = zrtpContext->cachedSecret.previouslyVerifiedSas; zrtpConfirmMessage->A = 0; /* Go clear message is not supported - rfc section 4.7.2 */ zrtpConfirmMessage->D = 0; /* The is no backdoor in our implementation of ZRTP - rfc section 11 */ /* generate a random CFB IV */ bctoolbox_rng_get(zrtpContext->RNGContext, zrtpConfirmMessage->CFBIV, 16); /* attach the message data to the packet */ zrtpPacket->messageData = zrtpConfirmMessage; } break; /* MSGTYPE_CONFIRM1 and MSGTYPE_CONFIRM2 */ case MSGTYPE_CONF2ACK : { /* nothing to do for the conf2ACK packet as it just contains it's type */ } break; /* MSGTYPE_CONF2ACK */ case MSGTYPE_PINGACK: { bzrtpPingMessage_t *pingMessage; bzrtpPingAckMessage_t *zrtpPingAckMessage; /* to create a pingACK we must have a ping packet in the channel context, check it */ bzrtpPacket_t *pingPacket = zrtpChannelContext->pingPacket; if (pingPacket == NULL) { *exitCode = BZRTP_CREATE_ERROR_INVALIDCONTEXT; return NULL; } pingMessage = (bzrtpPingMessage_t *)pingPacket->messageData; /* create the message */ zrtpPingAckMessage = (bzrtpPingAckMessage_t *)malloc(sizeof(bzrtpPingAckMessage_t)); memset(zrtpPingAckMessage, 0, sizeof(bzrtpPingAckMessage_t)); /* initialise all fields using zrtp context data and the received ping message */ memcpy(zrtpPingAckMessage->version,ZRTP_VERSION , 4); /* we support version 1.10 only, so no need to even check what was sent in the ping */ memcpy(zrtpPingAckMessage->endpointHash, zrtpContext->selfZID, 8); /* as suggested in rfc section 5.16, use the truncated ZID as endPoint hash */ memcpy(zrtpPingAckMessage->endpointHashReceived, pingMessage->endpointHash, 8); zrtpPingAckMessage->SSRC = pingPacket->sourceIdentifier; /* attach the message data to the packet */ zrtpPacket->messageData = zrtpPingAckMessage; } /* MSGTYPE_PINGACK */ break; default: free(zrtpPacket); *exitCode = BZRTP_CREATE_ERROR_INVALIDMESSAGETYPE; return NULL; break; } zrtpPacket->sequenceNumber = 0; /* this field is not used buy the packet creator, sequence number is given as a parameter when converting the message to a packet string(packet build). Used only when parsing a string into a packet struct */ zrtpPacket->messageType = messageType; zrtpPacket->sourceIdentifier = zrtpChannelContext->selfSSRC; zrtpPacket->messageLength = 0; /* length will be computed at packet build */ zrtpPacket->packetString = NULL; *exitCode=0; return zrtpPacket; } void bzrtp_freeZrtpPacket(bzrtpPacket_t *zrtpPacket) { if (zrtpPacket != NULL) { /* some messages have fields to be freed */ if (zrtpPacket->messageData != NULL) { switch(zrtpPacket->messageType) { case MSGTYPE_DHPART1 : case MSGTYPE_DHPART2 : { bzrtpDHPartMessage_t *typedMessageData = (bzrtpDHPartMessage_t *)(zrtpPacket->messageData); if (typedMessageData != NULL) { free(typedMessageData->pv); } } break; case MSGTYPE_CONFIRM1: case MSGTYPE_CONFIRM2: { bzrtpConfirmMessage_t *typedMessageData = (bzrtpConfirmMessage_t *)(zrtpPacket->messageData); if (typedMessageData != NULL) { free(typedMessageData->signatureBlock); } } break; } } free(zrtpPacket->messageData); free(zrtpPacket->packetString); free(zrtpPacket); } } /** * @brief Modify the current sequence number of the packet in the packetString and sequenceNumber fields * The CRC at the end of packetString is also updated * * param[in/out] zrtpPacket The zrtpPacket to modify, the packetString must have been generated by * a call to bzrtp_packetBuild on this packet * param[in] sequenceNumber The new sequence number to insert in the packetString * * return 0 on succes, error code otherwise */ int bzrtp_packetUpdateSequenceNumber(bzrtpPacket_t *zrtpPacket, uint16_t sequenceNumber) { uint32_t CRC; uint8_t *CRCbuffer; if (zrtpPacket == NULL) { return BZRTP_BUILDER_ERROR_INVALIDPACKET; } if (zrtpPacket->packetString == NULL) { return BZRTP_BUILDER_ERROR_INVALIDPACKET; } /* update the sequence number field (even if it is probably useless as this function is called just before sending the DHPart2 packet only)*/ zrtpPacket->sequenceNumber = sequenceNumber; /* update hte sequence number in the packetString */ *(zrtpPacket->packetString+2)= (uint8_t)((sequenceNumber>>8)&0x00FF); *(zrtpPacket->packetString+3)= (uint8_t)(sequenceNumber&0x00FF); /* update the CRC */ CRC = bzrtp_CRC32(zrtpPacket->packetString, zrtpPacket->messageLength+ZRTP_PACKET_HEADER_LENGTH); CRCbuffer = (zrtpPacket->packetString)+(zrtpPacket->messageLength)+ZRTP_PACKET_HEADER_LENGTH; *CRCbuffer = (uint8_t)((CRC>>24)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>16)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)((CRC>>8)&0xFF); CRCbuffer++; *CRCbuffer = (uint8_t)(CRC&0xFF); return 0; } /*** Local functions implementation ***/ uint8_t *messageTypeInttoString(uint32_t messageType) { switch(messageType) { case MSGTYPE_HELLO : return (uint8_t *)"Hello "; break; case MSGTYPE_HELLOACK : return (uint8_t *)"HelloACK"; break; case MSGTYPE_COMMIT : return (uint8_t *)"Commit "; break; case MSGTYPE_DHPART1 : return (uint8_t *)"DHPart1 "; break; case MSGTYPE_DHPART2 : return (uint8_t *)"DHPart2 "; break; case MSGTYPE_CONFIRM1 : return (uint8_t *)"Confirm1"; break; case MSGTYPE_CONFIRM2 : return (uint8_t *)"Confirm2"; break; case MSGTYPE_CONF2ACK : return (uint8_t *)"Conf2ACK"; break; case MSGTYPE_ERROR : return (uint8_t *)"Error "; break; case MSGTYPE_ERRORACK : return (uint8_t *)"ErrorACK"; break; case MSGTYPE_GOCLEAR : return (uint8_t *)"GoClear "; break; case MSGTYPE_CLEARACK : return (uint8_t *)"ClearACK"; break; case MSGTYPE_SASRELAY : return (uint8_t *)"SASrelay"; break; case MSGTYPE_RELAYACK : return (uint8_t *)"RelayACK"; break; case MSGTYPE_PING : return (uint8_t *)"Ping "; break; case MSGTYPE_PINGACK : return (uint8_t *)"PingACK "; break; } return NULL; } /* * @brief Map the 8 char string value message type to an int32_t * * @param[in] messageTypeString an 8 bytes string matching a zrtp message type * * @return a 32-bits unsigned integer mapping the message type */ int32_t messageTypeStringtoInt(uint8_t messageTypeString[8]) { if (memcmp(messageTypeString, "Hello ", 8) == 0) { return MSGTYPE_HELLO; } else if (memcmp(messageTypeString, "HelloACK", 8) == 0) { return MSGTYPE_HELLOACK; } else if (memcmp(messageTypeString, "Commit ", 8) == 0) { return MSGTYPE_COMMIT; } else if (memcmp(messageTypeString, "DHPart1 ", 8) == 0) { return MSGTYPE_DHPART1; } else if (memcmp(messageTypeString, "DHPart2 ", 8) == 0) { return MSGTYPE_DHPART2; } else if (memcmp(messageTypeString, "Confirm1", 8) == 0) { return MSGTYPE_CONFIRM1; } else if (memcmp(messageTypeString, "Confirm2", 8) == 0) { return MSGTYPE_CONFIRM2; } else if (memcmp(messageTypeString, "Conf2ACK", 8) == 0) { return MSGTYPE_CONF2ACK; } else if (memcmp(messageTypeString, "Error ", 8) == 0) { return MSGTYPE_ERROR; } else if (memcmp(messageTypeString, "ErrorACK", 8) == 0) { return MSGTYPE_ERRORACK; } else if (memcmp(messageTypeString, "GoClear ", 8) == 0) { return MSGTYPE_GOCLEAR; } else if (memcmp(messageTypeString, "ClearACK", 8) == 0) { return MSGTYPE_CLEARACK; } else if (memcmp(messageTypeString, "SASrelay", 8) == 0) { return MSGTYPE_SASRELAY; } else if (memcmp(messageTypeString, "RelayACK", 8) == 0) { return MSGTYPE_RELAYACK; } else if (memcmp(messageTypeString, "Ping ", 8) == 0) { return MSGTYPE_PING; } else if (memcmp(messageTypeString, "PingACK ", 8) == 0) { return MSGTYPE_PINGACK; } else { return MSGTYPE_INVALID; } } /* * @brief Write the message header(preambule, length, message type) into the given output buffer * * @param[out] outputBuffer Message starts at the begining of this buffer * @param[in] messageLength Message length in bytes! To be converted into 32bits words before being inserted in the message header * @param[in] messageType An 8 chars string for the message type (validity is not checked by this function) * */ void zrtpMessageSetHeader(uint8_t *outputBuffer, uint16_t messageLength, uint8_t messageType[8]) { /* insert the preambule */ outputBuffer[0] = 0x50; outputBuffer[1] = 0x5a; /* then the length in 32 bits words (param is in bytes, so >> 2) */ outputBuffer[2] = (uint8_t)((messageLength>>10)&0x00FF); outputBuffer[3] = (uint8_t)((messageLength>>2)&0x00FF); /* the message type */ memcpy(outputBuffer+4, messageType, 8); } /* * Return the variable private value length in bytes according to given key agreement algorythm * * @param[in] keyAgreementAlgo The key agreement algo mapped to an integer as defined in cryptoWrapper.h * * @return the private value length in bytes * */ uint16_t computeKeyAgreementPrivateValueLength(uint8_t keyAgreementAlgo) { uint16_t pvLength = 0; switch (keyAgreementAlgo) { case ZRTP_KEYAGREEMENT_DH3k : pvLength = 384; break; case ZRTP_KEYAGREEMENT_DH2k : pvLength = 256; break; case ZRTP_KEYAGREEMENT_EC25 : pvLength = 64; break; case ZRTP_KEYAGREEMENT_EC38 : pvLength = 96; break; case ZRTP_KEYAGREEMENT_EC52 : pvLength = 132; break; default : pvLength = 0; break; } return pvLength; }
./CrossVul/dataset_final_sorted/CWE-254/c/bad_5205_1
crossvul-cpp_data_bad_4872_0
/* * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "server.h" #include <sys/uio.h> #include <math.h> static void setProtocolError(client *c, int pos); /* Return the size consumed from the allocator, for the specified SDS string, * including internal fragmentation. This function is used in order to compute * the client output buffer size. */ size_t sdsZmallocSize(sds s) { void *sh = sdsAllocPtr(s); return zmalloc_size(sh); } /* Return the amount of memory used by the sds string at object->ptr * for a string object. */ size_t getStringObjectSdsUsedMemory(robj *o) { serverAssertWithInfo(NULL,o,o->type == OBJ_STRING); switch(o->encoding) { case OBJ_ENCODING_RAW: return sdsZmallocSize(o->ptr); case OBJ_ENCODING_EMBSTR: return zmalloc_size(o)-sizeof(robj); default: return 0; /* Just integer encoding for now. */ } } void *dupClientReplyValue(void *o) { incrRefCount((robj*)o); return o; } int listMatchObjects(void *a, void *b) { return equalStringObjects(a,b); } client *createClient(int fd) { client *c = zmalloc(sizeof(client)); /* passing -1 as fd it is possible to create a non connected client. * This is useful since all the commands needs to be executed * in the context of a client. When commands are executed in other * contexts (for instance a Lua script) we need a non connected client. */ if (fd != -1) { anetNonBlock(NULL,fd); anetEnableTcpNoDelay(NULL,fd); if (server.tcpkeepalive) anetKeepAlive(NULL,fd,server.tcpkeepalive); if (aeCreateFileEvent(server.el,fd,AE_READABLE, readQueryFromClient, c) == AE_ERR) { close(fd); zfree(c); return NULL; } } selectDb(c,0); c->id = server.next_client_id++; c->fd = fd; c->name = NULL; c->bufpos = 0; c->querybuf = sdsempty(); c->querybuf_peak = 0; c->reqtype = 0; c->argc = 0; c->argv = NULL; c->cmd = c->lastcmd = NULL; c->multibulklen = 0; c->bulklen = -1; c->sentlen = 0; c->flags = 0; c->ctime = c->lastinteraction = server.unixtime; c->authenticated = 0; c->replstate = REPL_STATE_NONE; c->repl_put_online_on_ack = 0; c->reploff = 0; c->repl_ack_off = 0; c->repl_ack_time = 0; c->slave_listening_port = 0; c->slave_ip[0] = '\0'; c->slave_capa = SLAVE_CAPA_NONE; c->reply = listCreate(); c->reply_bytes = 0; c->obuf_soft_limit_reached_time = 0; listSetFreeMethod(c->reply,decrRefCountVoid); listSetDupMethod(c->reply,dupClientReplyValue); c->btype = BLOCKED_NONE; c->bpop.timeout = 0; c->bpop.keys = dictCreate(&setDictType,NULL); c->bpop.target = NULL; c->bpop.numreplicas = 0; c->bpop.reploffset = 0; c->woff = 0; c->watched_keys = listCreate(); c->pubsub_channels = dictCreate(&setDictType,NULL); c->pubsub_patterns = listCreate(); c->peerid = NULL; listSetFreeMethod(c->pubsub_patterns,decrRefCountVoid); listSetMatchMethod(c->pubsub_patterns,listMatchObjects); if (fd != -1) listAddNodeTail(server.clients,c); initClientMultiState(c); return c; } /* This function is called every time we are going to transmit new data * to the client. The behavior is the following: * * If the client should receive new data (normal clients will) the function * returns C_OK, and make sure to install the write handler in our event * loop so that when the socket is writable new data gets written. * * If the client should not receive new data, because it is a fake client * (used to load AOF in memory), a master or because the setup of the write * handler failed, the function returns C_ERR. * * The function may return C_OK without actually installing the write * event handler in the following cases: * * 1) The event handler should already be installed since the output buffer * already contained something. * 2) The client is a slave but not yet online, so we want to just accumulate * writes in the buffer but not actually sending them yet. * * Typically gets called every time a reply is built, before adding more * data to the clients output buffers. If the function returns C_ERR no * data should be appended to the output buffers. */ int prepareClientToWrite(client *c) { /* If it's the Lua client we always return ok without installing any * handler since there is no socket at all. */ if (c->flags & CLIENT_LUA) return C_OK; /* CLIENT REPLY OFF / SKIP handling: don't send replies. */ if (c->flags & (CLIENT_REPLY_OFF|CLIENT_REPLY_SKIP)) return C_ERR; /* Masters don't receive replies, unless CLIENT_MASTER_FORCE_REPLY flag * is set. */ if ((c->flags & CLIENT_MASTER) && !(c->flags & CLIENT_MASTER_FORCE_REPLY)) return C_ERR; if (c->fd <= 0) return C_ERR; /* Fake client for AOF loading. */ /* Schedule the client to write the output buffers to the socket only * if not already done (there were no pending writes already and the client * was yet not flagged), and, for slaves, if the slave can actually * receive writes at this stage. */ if (!clientHasPendingReplies(c) && !(c->flags & CLIENT_PENDING_WRITE) && (c->replstate == REPL_STATE_NONE || (c->replstate == SLAVE_STATE_ONLINE && !c->repl_put_online_on_ack))) { /* Here instead of installing the write handler, we just flag the * client and put it into a list of clients that have something * to write to the socket. This way before re-entering the event * loop, we can try to directly write to the client sockets avoiding * a system call. We'll only really install the write handler if * we'll not be able to write the whole reply at once. */ c->flags |= CLIENT_PENDING_WRITE; listAddNodeHead(server.clients_pending_write,c); } /* Authorize the caller to queue in the output buffer of this client. */ return C_OK; } /* Create a duplicate of the last object in the reply list when * it is not exclusively owned by the reply list. */ robj *dupLastObjectIfNeeded(list *reply) { robj *new, *cur; listNode *ln; serverAssert(listLength(reply) > 0); ln = listLast(reply); cur = listNodeValue(ln); if (cur->refcount > 1) { new = dupStringObject(cur); decrRefCount(cur); listNodeValue(ln) = new; } return listNodeValue(ln); } /* ----------------------------------------------------------------------------- * Low level functions to add more data to output buffers. * -------------------------------------------------------------------------- */ int _addReplyToBuffer(client *c, const char *s, size_t len) { size_t available = sizeof(c->buf)-c->bufpos; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return C_OK; /* If there already are entries in the reply list, we cannot * add anything more to the static buffer. */ if (listLength(c->reply) > 0) return C_ERR; /* Check that the buffer has enough space available for this string. */ if (len > available) return C_ERR; memcpy(c->buf+c->bufpos,s,len); c->bufpos+=len; return C_OK; } void _addReplyObjectToList(client *c, robj *o) { robj *tail; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return; if (listLength(c->reply) == 0) { incrRefCount(o); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } else { tail = listNodeValue(listLast(c->reply)); /* Append to this object when possible. */ if (tail->ptr != NULL && tail->encoding == OBJ_ENCODING_RAW && sdslen(tail->ptr)+sdslen(o->ptr) <= PROTO_REPLY_CHUNK_BYTES) { c->reply_bytes -= sdsZmallocSize(tail->ptr); tail = dupLastObjectIfNeeded(c->reply); tail->ptr = sdscatlen(tail->ptr,o->ptr,sdslen(o->ptr)); c->reply_bytes += sdsZmallocSize(tail->ptr); } else { incrRefCount(o); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } } asyncCloseClientOnOutputBufferLimitReached(c); } /* This method takes responsibility over the sds. When it is no longer * needed it will be free'd, otherwise it ends up in a robj. */ void _addReplySdsToList(client *c, sds s) { robj *tail; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) { sdsfree(s); return; } if (listLength(c->reply) == 0) { listAddNodeTail(c->reply,createObject(OBJ_STRING,s)); c->reply_bytes += sdsZmallocSize(s); } else { tail = listNodeValue(listLast(c->reply)); /* Append to this object when possible. */ if (tail->ptr != NULL && tail->encoding == OBJ_ENCODING_RAW && sdslen(tail->ptr)+sdslen(s) <= PROTO_REPLY_CHUNK_BYTES) { c->reply_bytes -= sdsZmallocSize(tail->ptr); tail = dupLastObjectIfNeeded(c->reply); tail->ptr = sdscatlen(tail->ptr,s,sdslen(s)); c->reply_bytes += sdsZmallocSize(tail->ptr); sdsfree(s); } else { listAddNodeTail(c->reply,createObject(OBJ_STRING,s)); c->reply_bytes += sdsZmallocSize(s); } } asyncCloseClientOnOutputBufferLimitReached(c); } void _addReplyStringToList(client *c, const char *s, size_t len) { robj *tail; if (c->flags & CLIENT_CLOSE_AFTER_REPLY) return; if (listLength(c->reply) == 0) { robj *o = createStringObject(s,len); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } else { tail = listNodeValue(listLast(c->reply)); /* Append to this object when possible. */ if (tail->ptr != NULL && tail->encoding == OBJ_ENCODING_RAW && sdslen(tail->ptr)+len <= PROTO_REPLY_CHUNK_BYTES) { c->reply_bytes -= sdsZmallocSize(tail->ptr); tail = dupLastObjectIfNeeded(c->reply); tail->ptr = sdscatlen(tail->ptr,s,len); c->reply_bytes += sdsZmallocSize(tail->ptr); } else { robj *o = createStringObject(s,len); listAddNodeTail(c->reply,o); c->reply_bytes += getStringObjectSdsUsedMemory(o); } } asyncCloseClientOnOutputBufferLimitReached(c); } /* ----------------------------------------------------------------------------- * Higher level functions to queue data on the client output buffer. * The following functions are the ones that commands implementations will call. * -------------------------------------------------------------------------- */ void addReply(client *c, robj *obj) { if (prepareClientToWrite(c) != C_OK) return; /* This is an important place where we can avoid copy-on-write * when there is a saving child running, avoiding touching the * refcount field of the object if it's not needed. * * If the encoding is RAW and there is room in the static buffer * we'll be able to send the object to the client without * messing with its page. */ if (sdsEncodedObject(obj)) { if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != C_OK) _addReplyObjectToList(c,obj); } else if (obj->encoding == OBJ_ENCODING_INT) { /* Optimization: if there is room in the static buffer for 32 bytes * (more than the max chars a 64 bit integer can take as string) we * avoid decoding the object and go for the lower level approach. */ if (listLength(c->reply) == 0 && (sizeof(c->buf) - c->bufpos) >= 32) { char buf[32]; int len; len = ll2string(buf,sizeof(buf),(long)obj->ptr); if (_addReplyToBuffer(c,buf,len) == C_OK) return; /* else... continue with the normal code path, but should never * happen actually since we verified there is room. */ } obj = getDecodedObject(obj); if (_addReplyToBuffer(c,obj->ptr,sdslen(obj->ptr)) != C_OK) _addReplyObjectToList(c,obj); decrRefCount(obj); } else { serverPanic("Wrong obj->encoding in addReply()"); } } void addReplySds(client *c, sds s) { if (prepareClientToWrite(c) != C_OK) { /* The caller expects the sds to be free'd. */ sdsfree(s); return; } if (_addReplyToBuffer(c,s,sdslen(s)) == C_OK) { sdsfree(s); } else { /* This method free's the sds when it is no longer needed. */ _addReplySdsToList(c,s); } } void addReplyString(client *c, const char *s, size_t len) { if (prepareClientToWrite(c) != C_OK) return; if (_addReplyToBuffer(c,s,len) != C_OK) _addReplyStringToList(c,s,len); } void addReplyErrorLength(client *c, const char *s, size_t len) { addReplyString(c,"-ERR ",5); addReplyString(c,s,len); addReplyString(c,"\r\n",2); } void addReplyError(client *c, const char *err) { addReplyErrorLength(c,err,strlen(err)); } void addReplyErrorFormat(client *c, const char *fmt, ...) { size_t l, j; va_list ap; va_start(ap,fmt); sds s = sdscatvprintf(sdsempty(),fmt,ap); va_end(ap); /* Make sure there are no newlines in the string, otherwise invalid protocol * is emitted. */ l = sdslen(s); for (j = 0; j < l; j++) { if (s[j] == '\r' || s[j] == '\n') s[j] = ' '; } addReplyErrorLength(c,s,sdslen(s)); sdsfree(s); } void addReplyStatusLength(client *c, const char *s, size_t len) { addReplyString(c,"+",1); addReplyString(c,s,len); addReplyString(c,"\r\n",2); } void addReplyStatus(client *c, const char *status) { addReplyStatusLength(c,status,strlen(status)); } void addReplyStatusFormat(client *c, const char *fmt, ...) { va_list ap; va_start(ap,fmt); sds s = sdscatvprintf(sdsempty(),fmt,ap); va_end(ap); addReplyStatusLength(c,s,sdslen(s)); sdsfree(s); } /* Adds an empty object to the reply list that will contain the multi bulk * length, which is not known when this function is called. */ void *addDeferredMultiBulkLength(client *c) { /* Note that we install the write event here even if the object is not * ready to be sent, since we are sure that before returning to the * event loop setDeferredMultiBulkLength() will be called. */ if (prepareClientToWrite(c) != C_OK) return NULL; listAddNodeTail(c->reply,createObject(OBJ_STRING,NULL)); return listLast(c->reply); } /* Populate the length object and try gluing it to the next chunk. */ void setDeferredMultiBulkLength(client *c, void *node, long length) { listNode *ln = (listNode*)node; robj *len, *next; /* Abort when *node is NULL (see addDeferredMultiBulkLength). */ if (node == NULL) return; len = listNodeValue(ln); len->ptr = sdscatprintf(sdsempty(),"*%ld\r\n",length); len->encoding = OBJ_ENCODING_RAW; /* in case it was an EMBSTR. */ c->reply_bytes += sdsZmallocSize(len->ptr); if (ln->next != NULL) { next = listNodeValue(ln->next); /* Only glue when the next node is non-NULL (an sds in this case) */ if (next->ptr != NULL) { c->reply_bytes -= sdsZmallocSize(len->ptr); c->reply_bytes -= getStringObjectSdsUsedMemory(next); len->ptr = sdscatlen(len->ptr,next->ptr,sdslen(next->ptr)); c->reply_bytes += sdsZmallocSize(len->ptr); listDelNode(c->reply,ln->next); } } asyncCloseClientOnOutputBufferLimitReached(c); } /* Add a double as a bulk reply */ void addReplyDouble(client *c, double d) { char dbuf[128], sbuf[128]; int dlen, slen; if (isinf(d)) { /* Libc in odd systems (Hi Solaris!) will format infinite in a * different way, so better to handle it in an explicit way. */ addReplyBulkCString(c, d > 0 ? "inf" : "-inf"); } else { dlen = snprintf(dbuf,sizeof(dbuf),"%.17g",d); slen = snprintf(sbuf,sizeof(sbuf),"$%d\r\n%s\r\n",dlen,dbuf); addReplyString(c,sbuf,slen); } } /* Add a long double as a bulk reply, but uses a human readable formatting * of the double instead of exposing the crude behavior of doubles to the * dear user. */ void addReplyHumanLongDouble(client *c, long double d) { robj *o = createStringObjectFromLongDouble(d,1); addReplyBulk(c,o); decrRefCount(o); } /* Add a long long as integer reply or bulk len / multi bulk count. * Basically this is used to output <prefix><long long><crlf>. */ void addReplyLongLongWithPrefix(client *c, long long ll, char prefix) { char buf[128]; int len; /* Things like $3\r\n or *2\r\n are emitted very often by the protocol * so we have a few shared objects to use if the integer is small * like it is most of the times. */ if (prefix == '*' && ll < OBJ_SHARED_BULKHDR_LEN && ll >= 0) { addReply(c,shared.mbulkhdr[ll]); return; } else if (prefix == '$' && ll < OBJ_SHARED_BULKHDR_LEN && ll >= 0) { addReply(c,shared.bulkhdr[ll]); return; } buf[0] = prefix; len = ll2string(buf+1,sizeof(buf)-1,ll); buf[len+1] = '\r'; buf[len+2] = '\n'; addReplyString(c,buf,len+3); } void addReplyLongLong(client *c, long long ll) { if (ll == 0) addReply(c,shared.czero); else if (ll == 1) addReply(c,shared.cone); else addReplyLongLongWithPrefix(c,ll,':'); } void addReplyMultiBulkLen(client *c, long length) { if (length < OBJ_SHARED_BULKHDR_LEN) addReply(c,shared.mbulkhdr[length]); else addReplyLongLongWithPrefix(c,length,'*'); } /* Create the length prefix of a bulk reply, example: $2234 */ void addReplyBulkLen(client *c, robj *obj) { size_t len; if (sdsEncodedObject(obj)) { len = sdslen(obj->ptr); } else { long n = (long)obj->ptr; /* Compute how many bytes will take this integer as a radix 10 string */ len = 1; if (n < 0) { len++; n = -n; } while((n = n/10) != 0) { len++; } } if (len < OBJ_SHARED_BULKHDR_LEN) addReply(c,shared.bulkhdr[len]); else addReplyLongLongWithPrefix(c,len,'$'); } /* Add a Redis Object as a bulk reply */ void addReplyBulk(client *c, robj *obj) { addReplyBulkLen(c,obj); addReply(c,obj); addReply(c,shared.crlf); } /* Add a C buffer as bulk reply */ void addReplyBulkCBuffer(client *c, const void *p, size_t len) { addReplyLongLongWithPrefix(c,len,'$'); addReplyString(c,p,len); addReply(c,shared.crlf); } /* Add sds to reply (takes ownership of sds and frees it) */ void addReplyBulkSds(client *c, sds s) { addReplySds(c,sdscatfmt(sdsempty(),"$%u\r\n", (unsigned long)sdslen(s))); addReplySds(c,s); addReply(c,shared.crlf); } /* Add a C nul term string as bulk reply */ void addReplyBulkCString(client *c, const char *s) { if (s == NULL) { addReply(c,shared.nullbulk); } else { addReplyBulkCBuffer(c,s,strlen(s)); } } /* Add a long long as a bulk reply */ void addReplyBulkLongLong(client *c, long long ll) { char buf[64]; int len; len = ll2string(buf,64,ll); addReplyBulkCBuffer(c,buf,len); } /* Copy 'src' client output buffers into 'dst' client output buffers. * The function takes care of freeing the old output buffers of the * destination client. */ void copyClientOutputBuffer(client *dst, client *src) { listRelease(dst->reply); dst->reply = listDup(src->reply); memcpy(dst->buf,src->buf,src->bufpos); dst->bufpos = src->bufpos; dst->reply_bytes = src->reply_bytes; } /* Return true if the specified client has pending reply buffers to write to * the socket. */ int clientHasPendingReplies(client *c) { return c->bufpos || listLength(c->reply); } #define MAX_ACCEPTS_PER_CALL 1000 static void acceptCommonHandler(int fd, int flags, char *ip) { client *c; if ((c = createClient(fd)) == NULL) { serverLog(LL_WARNING, "Error registering fd event for the new client: %s (fd=%d)", strerror(errno),fd); close(fd); /* May be already closed, just ignore errors */ return; } /* If maxclient directive is set and this is one client more... close the * connection. Note that we create the client instead to check before * for this condition, since now the socket is already set in non-blocking * mode and we can send an error for free using the Kernel I/O */ if (listLength(server.clients) > server.maxclients) { char *err = "-ERR max number of clients reached\r\n"; /* That's a best effort error message, don't check write errors */ if (write(c->fd,err,strlen(err)) == -1) { /* Nothing to do, Just to avoid the warning... */ } server.stat_rejected_conn++; freeClient(c); return; } /* If the server is running in protected mode (the default) and there * is no password set, nor a specific interface is bound, we don't accept * requests from non loopback interfaces. Instead we try to explain the * user what to do to fix it if needed. */ if (server.protected_mode && server.bindaddr_count == 0 && server.requirepass == NULL && !(flags & CLIENT_UNIX_SOCKET) && ip != NULL) { if (strcmp(ip,"127.0.0.1") && strcmp(ip,"::1")) { char *err = "-DENIED Redis is running in protected mode because protected " "mode is enabled, no bind address was specified, no " "authentication password is requested to clients. In this mode " "connections are only accepted from the loopback interface. " "If you want to connect from external computers to Redis you " "may adopt one of the following solutions: " "1) Just disable protected mode sending the command " "'CONFIG SET protected-mode no' from the loopback interface " "by connecting to Redis from the same host the server is " "running, however MAKE SURE Redis is not publicly accessible " "from internet if you do so. Use CONFIG REWRITE to make this " "change permanent. " "2) Alternatively you can just disable the protected mode by " "editing the Redis configuration file, and setting the protected " "mode option to 'no', and then restarting the server. " "3) If you started the server manually just for testing, restart " "it with the '--protected-mode no' option. " "4) Setup a bind address or an authentication password. " "NOTE: You only need to do one of the above things in order for " "the server to start accepting connections from the outside.\r\n"; if (write(c->fd,err,strlen(err)) == -1) { /* Nothing to do, Just to avoid the warning... */ } server.stat_rejected_conn++; freeClient(c); return; } } server.stat_numconnections++; c->flags |= flags; } void acceptTcpHandler(aeEventLoop *el, int fd, void *privdata, int mask) { int cport, cfd, max = MAX_ACCEPTS_PER_CALL; char cip[NET_IP_STR_LEN]; UNUSED(el); UNUSED(mask); UNUSED(privdata); while(max--) { cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); if (cfd == ANET_ERR) { if (errno != EWOULDBLOCK) serverLog(LL_WARNING, "Accepting client connection: %s", server.neterr); return; } serverLog(LL_VERBOSE,"Accepted %s:%d", cip, cport); acceptCommonHandler(cfd,0,cip); } } void acceptUnixHandler(aeEventLoop *el, int fd, void *privdata, int mask) { int cfd, max = MAX_ACCEPTS_PER_CALL; UNUSED(el); UNUSED(mask); UNUSED(privdata); while(max--) { cfd = anetUnixAccept(server.neterr, fd); if (cfd == ANET_ERR) { if (errno != EWOULDBLOCK) serverLog(LL_WARNING, "Accepting client connection: %s", server.neterr); return; } serverLog(LL_VERBOSE,"Accepted connection to %s", server.unixsocket); acceptCommonHandler(cfd,CLIENT_UNIX_SOCKET,NULL); } } static void freeClientArgv(client *c) { int j; for (j = 0; j < c->argc; j++) decrRefCount(c->argv[j]); c->argc = 0; c->cmd = NULL; } /* Close all the slaves connections. This is useful in chained replication * when we resync with our own master and want to force all our slaves to * resync with us as well. */ void disconnectSlaves(void) { while (listLength(server.slaves)) { listNode *ln = listFirst(server.slaves); freeClient((client*)ln->value); } } /* Remove the specified client from global lists where the client could * be referenced, not including the Pub/Sub channels. * This is used by freeClient() and replicationCacheMaster(). */ void unlinkClient(client *c) { listNode *ln; /* If this is marked as current client unset it. */ if (server.current_client == c) server.current_client = NULL; /* Certain operations must be done only if the client has an active socket. * If the client was already unlinked or if it's a "fake client" the * fd is already set to -1. */ if (c->fd != -1) { /* Remove from the list of active clients. */ ln = listSearchKey(server.clients,c); serverAssert(ln != NULL); listDelNode(server.clients,ln); /* Unregister async I/O handlers and close the socket. */ aeDeleteFileEvent(server.el,c->fd,AE_READABLE); aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE); close(c->fd); c->fd = -1; } /* Remove from the list of pending writes if needed. */ if (c->flags & CLIENT_PENDING_WRITE) { ln = listSearchKey(server.clients_pending_write,c); serverAssert(ln != NULL); listDelNode(server.clients_pending_write,ln); c->flags &= ~CLIENT_PENDING_WRITE; } /* When client was just unblocked because of a blocking operation, * remove it from the list of unblocked clients. */ if (c->flags & CLIENT_UNBLOCKED) { ln = listSearchKey(server.unblocked_clients,c); serverAssert(ln != NULL); listDelNode(server.unblocked_clients,ln); c->flags &= ~CLIENT_UNBLOCKED; } } void freeClient(client *c) { listNode *ln; /* If it is our master that's beging disconnected we should make sure * to cache the state to try a partial resynchronization later. * * Note that before doing this we make sure that the client is not in * some unexpected state, by checking its flags. */ if (server.master && c->flags & CLIENT_MASTER) { serverLog(LL_WARNING,"Connection with master lost."); if (!(c->flags & (CLIENT_CLOSE_AFTER_REPLY| CLIENT_CLOSE_ASAP| CLIENT_BLOCKED| CLIENT_UNBLOCKED))) { replicationCacheMaster(c); return; } } /* Log link disconnection with slave */ if ((c->flags & CLIENT_SLAVE) && !(c->flags & CLIENT_MONITOR)) { serverLog(LL_WARNING,"Connection with slave %s lost.", replicationGetSlaveName(c)); } /* Free the query buffer */ sdsfree(c->querybuf); c->querybuf = NULL; /* Deallocate structures used to block on blocking ops. */ if (c->flags & CLIENT_BLOCKED) unblockClient(c); dictRelease(c->bpop.keys); /* UNWATCH all the keys */ unwatchAllKeys(c); listRelease(c->watched_keys); /* Unsubscribe from all the pubsub channels */ pubsubUnsubscribeAllChannels(c,0); pubsubUnsubscribeAllPatterns(c,0); dictRelease(c->pubsub_channels); listRelease(c->pubsub_patterns); /* Free data structures. */ listRelease(c->reply); freeClientArgv(c); /* Unlink the client: this will close the socket, remove the I/O * handlers, and remove references of the client from different * places where active clients may be referenced. */ unlinkClient(c); /* Master/slave cleanup Case 1: * we lost the connection with a slave. */ if (c->flags & CLIENT_SLAVE) { if (c->replstate == SLAVE_STATE_SEND_BULK) { if (c->repldbfd != -1) close(c->repldbfd); if (c->replpreamble) sdsfree(c->replpreamble); } list *l = (c->flags & CLIENT_MONITOR) ? server.monitors : server.slaves; ln = listSearchKey(l,c); serverAssert(ln != NULL); listDelNode(l,ln); /* We need to remember the time when we started to have zero * attached slaves, as after some time we'll free the replication * backlog. */ if (c->flags & CLIENT_SLAVE && listLength(server.slaves) == 0) server.repl_no_slaves_since = server.unixtime; refreshGoodSlavesCount(); } /* Master/slave cleanup Case 2: * we lost the connection with the master. */ if (c->flags & CLIENT_MASTER) replicationHandleMasterDisconnection(); /* If this client was scheduled for async freeing we need to remove it * from the queue. */ if (c->flags & CLIENT_CLOSE_ASAP) { ln = listSearchKey(server.clients_to_close,c); serverAssert(ln != NULL); listDelNode(server.clients_to_close,ln); } /* Release other dynamically allocated client structure fields, * and finally release the client structure itself. */ if (c->name) decrRefCount(c->name); zfree(c->argv); freeClientMultiState(c); sdsfree(c->peerid); zfree(c); } /* Schedule a client to free it at a safe time in the serverCron() function. * This function is useful when we need to terminate a client but we are in * a context where calling freeClient() is not possible, because the client * should be valid for the continuation of the flow of the program. */ void freeClientAsync(client *c) { if (c->flags & CLIENT_CLOSE_ASAP || c->flags & CLIENT_LUA) return; c->flags |= CLIENT_CLOSE_ASAP; listAddNodeTail(server.clients_to_close,c); } void freeClientsInAsyncFreeQueue(void) { while (listLength(server.clients_to_close)) { listNode *ln = listFirst(server.clients_to_close); client *c = listNodeValue(ln); c->flags &= ~CLIENT_CLOSE_ASAP; freeClient(c); listDelNode(server.clients_to_close,ln); } } /* Write data in output buffers to client. Return C_OK if the client * is still valid after the call, C_ERR if it was freed. */ int writeToClient(int fd, client *c, int handler_installed) { ssize_t nwritten = 0, totwritten = 0; size_t objlen; size_t objmem; robj *o; while(clientHasPendingReplies(c)) { if (c->bufpos > 0) { nwritten = write(fd,c->buf+c->sentlen,c->bufpos-c->sentlen); if (nwritten <= 0) break; c->sentlen += nwritten; totwritten += nwritten; /* If the buffer was sent, set bufpos to zero to continue with * the remainder of the reply. */ if ((int)c->sentlen == c->bufpos) { c->bufpos = 0; c->sentlen = 0; } } else { o = listNodeValue(listFirst(c->reply)); objlen = sdslen(o->ptr); objmem = getStringObjectSdsUsedMemory(o); if (objlen == 0) { listDelNode(c->reply,listFirst(c->reply)); c->reply_bytes -= objmem; continue; } nwritten = write(fd, ((char*)o->ptr)+c->sentlen,objlen-c->sentlen); if (nwritten <= 0) break; c->sentlen += nwritten; totwritten += nwritten; /* If we fully sent the object on head go to the next one */ if (c->sentlen == objlen) { listDelNode(c->reply,listFirst(c->reply)); c->sentlen = 0; c->reply_bytes -= objmem; } } /* Note that we avoid to send more than NET_MAX_WRITES_PER_EVENT * bytes, in a single threaded server it's a good idea to serve * other clients as well, even if a very large request comes from * super fast link that is always able to accept data (in real world * scenario think about 'KEYS *' against the loopback interface). * * However if we are over the maxmemory limit we ignore that and * just deliver as much data as it is possible to deliver. */ server.stat_net_output_bytes += totwritten; if (totwritten > NET_MAX_WRITES_PER_EVENT && (server.maxmemory == 0 || zmalloc_used_memory() < server.maxmemory)) break; } if (nwritten == -1) { if (errno == EAGAIN) { nwritten = 0; } else { serverLog(LL_VERBOSE, "Error writing to client: %s", strerror(errno)); freeClient(c); return C_ERR; } } if (totwritten > 0) { /* For clients representing masters we don't count sending data * as an interaction, since we always send REPLCONF ACK commands * that take some time to just fill the socket output buffer. * We just rely on data / pings received for timeout detection. */ if (!(c->flags & CLIENT_MASTER)) c->lastinteraction = server.unixtime; } if (!clientHasPendingReplies(c)) { c->sentlen = 0; if (handler_installed) aeDeleteFileEvent(server.el,c->fd,AE_WRITABLE); /* Close connection after entire reply has been sent. */ if (c->flags & CLIENT_CLOSE_AFTER_REPLY) { freeClient(c); return C_ERR; } } return C_OK; } /* Write event handler. Just send data to the client. */ void sendReplyToClient(aeEventLoop *el, int fd, void *privdata, int mask) { UNUSED(el); UNUSED(mask); writeToClient(fd,privdata,1); } /* This function is called just before entering the event loop, in the hope * we can just write the replies to the client output buffer without any * need to use a syscall in order to install the writable event handler, * get it called, and so forth. */ int handleClientsWithPendingWrites(void) { listIter li; listNode *ln; int processed = listLength(server.clients_pending_write); listRewind(server.clients_pending_write,&li); while((ln = listNext(&li))) { client *c = listNodeValue(ln); c->flags &= ~CLIENT_PENDING_WRITE; listDelNode(server.clients_pending_write,ln); /* Try to write buffers to the client socket. */ if (writeToClient(c->fd,c,0) == C_ERR) continue; /* If there is nothing left, do nothing. Otherwise install * the write handler. */ if (clientHasPendingReplies(c) && aeCreateFileEvent(server.el, c->fd, AE_WRITABLE, sendReplyToClient, c) == AE_ERR) { freeClientAsync(c); } } return processed; } /* resetClient prepare the client to process the next command */ void resetClient(client *c) { redisCommandProc *prevcmd = c->cmd ? c->cmd->proc : NULL; freeClientArgv(c); c->reqtype = 0; c->multibulklen = 0; c->bulklen = -1; /* We clear the ASKING flag as well if we are not inside a MULTI, and * if what we just executed is not the ASKING command itself. */ if (!(c->flags & CLIENT_MULTI) && prevcmd != askingCommand) c->flags &= ~CLIENT_ASKING; /* Remove the CLIENT_REPLY_SKIP flag if any so that the reply * to the next command will be sent, but set the flag if the command * we just processed was "CLIENT REPLY SKIP". */ c->flags &= ~CLIENT_REPLY_SKIP; if (c->flags & CLIENT_REPLY_SKIP_NEXT) { c->flags |= CLIENT_REPLY_SKIP; c->flags &= ~CLIENT_REPLY_SKIP_NEXT; } } int processInlineBuffer(client *c) { char *newline; int argc, j; sds *argv, aux; size_t querylen; /* Search for end of line */ newline = strchr(c->querybuf,'\n'); /* Nothing to do without a \r\n */ if (newline == NULL) { if (sdslen(c->querybuf) > PROTO_INLINE_MAX_SIZE) { addReplyError(c,"Protocol error: too big inline request"); setProtocolError(c,0); } return C_ERR; } /* Handle the \r\n case. */ if (newline && newline != c->querybuf && *(newline-1) == '\r') newline--; /* Split the input buffer up to the \r\n */ querylen = newline-(c->querybuf); aux = sdsnewlen(c->querybuf,querylen); argv = sdssplitargs(aux,&argc); sdsfree(aux); if (argv == NULL) { addReplyError(c,"Protocol error: unbalanced quotes in request"); setProtocolError(c,0); return C_ERR; } /* Newline from slaves can be used to refresh the last ACK time. * This is useful for a slave to ping back while loading a big * RDB file. */ if (querylen == 0 && c->flags & CLIENT_SLAVE) c->repl_ack_time = server.unixtime; /* Leave data after the first line of the query in the buffer */ sdsrange(c->querybuf,querylen+2,-1); /* Setup argv array on client structure */ if (argc) { if (c->argv) zfree(c->argv); c->argv = zmalloc(sizeof(robj*)*argc); } /* Create redis objects for all arguments. */ for (c->argc = 0, j = 0; j < argc; j++) { if (sdslen(argv[j])) { c->argv[c->argc] = createObject(OBJ_STRING,argv[j]); c->argc++; } else { sdsfree(argv[j]); } } zfree(argv); return C_OK; } /* Helper function. Trims query buffer to make the function that processes * multi bulk requests idempotent. */ static void setProtocolError(client *c, int pos) { if (server.verbosity <= LL_VERBOSE) { sds client = catClientInfoString(sdsempty(),c); serverLog(LL_VERBOSE, "Protocol error from client: %s", client); sdsfree(client); } c->flags |= CLIENT_CLOSE_AFTER_REPLY; sdsrange(c->querybuf,pos,-1); } int processMultibulkBuffer(client *c) { char *newline = NULL; int pos = 0, ok; long long ll; if (c->multibulklen == 0) { /* The client should have been reset */ serverAssertWithInfo(c,NULL,c->argc == 0); /* Multi bulk length cannot be read without a \r\n */ newline = strchr(c->querybuf,'\r'); if (newline == NULL) { if (sdslen(c->querybuf) > PROTO_INLINE_MAX_SIZE) { addReplyError(c,"Protocol error: too big mbulk count string"); setProtocolError(c,0); } return C_ERR; } /* Buffer should also contain \n */ if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2)) return C_ERR; /* We know for sure there is a whole line since newline != NULL, * so go ahead and find out the multi bulk length. */ serverAssertWithInfo(c,NULL,c->querybuf[0] == '*'); ok = string2ll(c->querybuf+1,newline-(c->querybuf+1),&ll); if (!ok || ll > 1024*1024) { addReplyError(c,"Protocol error: invalid multibulk length"); setProtocolError(c,pos); return C_ERR; } pos = (newline-c->querybuf)+2; if (ll <= 0) { sdsrange(c->querybuf,pos,-1); return C_OK; } c->multibulklen = ll; /* Setup argv array on client structure */ if (c->argv) zfree(c->argv); c->argv = zmalloc(sizeof(robj*)*c->multibulklen); } serverAssertWithInfo(c,NULL,c->multibulklen > 0); while(c->multibulklen) { /* Read bulk length if unknown */ if (c->bulklen == -1) { newline = strchr(c->querybuf+pos,'\r'); if (newline == NULL) { if (sdslen(c->querybuf) > PROTO_INLINE_MAX_SIZE) { addReplyError(c, "Protocol error: too big bulk count string"); setProtocolError(c,0); return C_ERR; } break; } /* Buffer should also contain \n */ if (newline-(c->querybuf) > ((signed)sdslen(c->querybuf)-2)) break; if (c->querybuf[pos] != '$') { addReplyErrorFormat(c, "Protocol error: expected '$', got '%c'", c->querybuf[pos]); setProtocolError(c,pos); return C_ERR; } ok = string2ll(c->querybuf+pos+1,newline-(c->querybuf+pos+1),&ll); if (!ok || ll < 0 || ll > 512*1024*1024) { addReplyError(c,"Protocol error: invalid bulk length"); setProtocolError(c,pos); return C_ERR; } pos += newline-(c->querybuf+pos)+2; if (ll >= PROTO_MBULK_BIG_ARG) { size_t qblen; /* If we are going to read a large object from network * try to make it likely that it will start at c->querybuf * boundary so that we can optimize object creation * avoiding a large copy of data. */ sdsrange(c->querybuf,pos,-1); pos = 0; qblen = sdslen(c->querybuf); /* Hint the sds library about the amount of bytes this string is * going to contain. */ if (qblen < (size_t)ll+2) c->querybuf = sdsMakeRoomFor(c->querybuf,ll+2-qblen); } c->bulklen = ll; } /* Read bulk argument */ if (sdslen(c->querybuf)-pos < (unsigned)(c->bulklen+2)) { /* Not enough data (+2 == trailing \r\n) */ break; } else { /* Optimization: if the buffer contains JUST our bulk element * instead of creating a new object by *copying* the sds we * just use the current sds string. */ if (pos == 0 && c->bulklen >= PROTO_MBULK_BIG_ARG && (signed) sdslen(c->querybuf) == c->bulklen+2) { c->argv[c->argc++] = createObject(OBJ_STRING,c->querybuf); sdsIncrLen(c->querybuf,-2); /* remove CRLF */ /* Assume that if we saw a fat argument we'll see another one * likely... */ c->querybuf = sdsnewlen(NULL,c->bulklen+2); sdsclear(c->querybuf); pos = 0; } else { c->argv[c->argc++] = createStringObject(c->querybuf+pos,c->bulklen); pos += c->bulklen+2; } c->bulklen = -1; c->multibulklen--; } } /* Trim to pos */ if (pos) sdsrange(c->querybuf,pos,-1); /* We're done when c->multibulk == 0 */ if (c->multibulklen == 0) return C_OK; /* Still not read to process the command */ return C_ERR; } void processInputBuffer(client *c) { server.current_client = c; /* Keep processing while there is something in the input buffer */ while(sdslen(c->querybuf)) { /* Return if clients are paused. */ if (!(c->flags & CLIENT_SLAVE) && clientsArePaused()) break; /* Immediately abort if the client is in the middle of something. */ if (c->flags & CLIENT_BLOCKED) break; /* CLIENT_CLOSE_AFTER_REPLY closes the connection once the reply is * written to the client. Make sure to not let the reply grow after * this flag has been set (i.e. don't process more commands). */ if (c->flags & CLIENT_CLOSE_AFTER_REPLY) break; /* Determine request type when unknown. */ if (!c->reqtype) { if (c->querybuf[0] == '*') { c->reqtype = PROTO_REQ_MULTIBULK; } else { c->reqtype = PROTO_REQ_INLINE; } } if (c->reqtype == PROTO_REQ_INLINE) { if (processInlineBuffer(c) != C_OK) break; } else if (c->reqtype == PROTO_REQ_MULTIBULK) { if (processMultibulkBuffer(c) != C_OK) break; } else { serverPanic("Unknown request type"); } /* Multibulk processing could see a <= 0 length. */ if (c->argc == 0) { resetClient(c); } else { /* Only reset the client when the command was executed. */ if (processCommand(c) == C_OK) resetClient(c); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) break; } } server.current_client = NULL; } void readQueryFromClient(aeEventLoop *el, int fd, void *privdata, int mask) { client *c = (client*) privdata; int nread, readlen; size_t qblen; UNUSED(el); UNUSED(mask); readlen = PROTO_IOBUF_LEN; /* If this is a multi bulk request, and we are processing a bulk reply * that is large enough, try to maximize the probability that the query * buffer contains exactly the SDS string representing the object, even * at the risk of requiring more read(2) calls. This way the function * processMultiBulkBuffer() can avoid copying buffers to create the * Redis Object representing the argument. */ if (c->reqtype == PROTO_REQ_MULTIBULK && c->multibulklen && c->bulklen != -1 && c->bulklen >= PROTO_MBULK_BIG_ARG) { int remaining = (unsigned)(c->bulklen+2)-sdslen(c->querybuf); if (remaining < readlen) readlen = remaining; } qblen = sdslen(c->querybuf); if (c->querybuf_peak < qblen) c->querybuf_peak = qblen; c->querybuf = sdsMakeRoomFor(c->querybuf, readlen); nread = read(fd, c->querybuf+qblen, readlen); if (nread == -1) { if (errno == EAGAIN) { return; } else { serverLog(LL_VERBOSE, "Reading from client: %s",strerror(errno)); freeClient(c); return; } } else if (nread == 0) { serverLog(LL_VERBOSE, "Client closed connection"); freeClient(c); return; } sdsIncrLen(c->querybuf,nread); c->lastinteraction = server.unixtime; if (c->flags & CLIENT_MASTER) c->reploff += nread; server.stat_net_input_bytes += nread; if (sdslen(c->querybuf) > server.client_max_querybuf_len) { sds ci = catClientInfoString(sdsempty(),c), bytes = sdsempty(); bytes = sdscatrepr(bytes,c->querybuf,64); serverLog(LL_WARNING,"Closing client that reached max query buffer length: %s (qbuf initial bytes: %s)", ci, bytes); sdsfree(ci); sdsfree(bytes); freeClient(c); return; } processInputBuffer(c); } void getClientsMaxBuffers(unsigned long *longest_output_list, unsigned long *biggest_input_buffer) { client *c; listNode *ln; listIter li; unsigned long lol = 0, bib = 0; listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { c = listNodeValue(ln); if (listLength(c->reply) > lol) lol = listLength(c->reply); if (sdslen(c->querybuf) > bib) bib = sdslen(c->querybuf); } *longest_output_list = lol; *biggest_input_buffer = bib; } /* A Redis "Peer ID" is a colon separated ip:port pair. * For IPv4 it's in the form x.y.z.k:port, example: "127.0.0.1:1234". * For IPv6 addresses we use [] around the IP part, like in "[::1]:1234". * For Unix sockets we use path:0, like in "/tmp/redis:0". * * A Peer ID always fits inside a buffer of NET_PEER_ID_LEN bytes, including * the null term. * * On failure the function still populates 'peerid' with the "?:0" string * in case you want to relax error checking or need to display something * anyway (see anetPeerToString implementation for more info). */ void genClientPeerId(client *client, char *peerid, size_t peerid_len) { if (client->flags & CLIENT_UNIX_SOCKET) { /* Unix socket client. */ snprintf(peerid,peerid_len,"%s:0",server.unixsocket); } else { /* TCP client. */ anetFormatPeer(client->fd,peerid,peerid_len); } } /* This function returns the client peer id, by creating and caching it * if client->peerid is NULL, otherwise returning the cached value. * The Peer ID never changes during the life of the client, however it * is expensive to compute. */ char *getClientPeerId(client *c) { char peerid[NET_PEER_ID_LEN]; if (c->peerid == NULL) { genClientPeerId(c,peerid,sizeof(peerid)); c->peerid = sdsnew(peerid); } return c->peerid; } /* Concatenate a string representing the state of a client in an human * readable format, into the sds string 's'. */ sds catClientInfoString(sds s, client *client) { char flags[16], events[3], *p; int emask; p = flags; if (client->flags & CLIENT_SLAVE) { if (client->flags & CLIENT_MONITOR) *p++ = 'O'; else *p++ = 'S'; } if (client->flags & CLIENT_MASTER) *p++ = 'M'; if (client->flags & CLIENT_MULTI) *p++ = 'x'; if (client->flags & CLIENT_BLOCKED) *p++ = 'b'; if (client->flags & CLIENT_DIRTY_CAS) *p++ = 'd'; if (client->flags & CLIENT_CLOSE_AFTER_REPLY) *p++ = 'c'; if (client->flags & CLIENT_UNBLOCKED) *p++ = 'u'; if (client->flags & CLIENT_CLOSE_ASAP) *p++ = 'A'; if (client->flags & CLIENT_UNIX_SOCKET) *p++ = 'U'; if (client->flags & CLIENT_READONLY) *p++ = 'r'; if (p == flags) *p++ = 'N'; *p++ = '\0'; emask = client->fd == -1 ? 0 : aeGetFileEvents(server.el,client->fd); p = events; if (emask & AE_READABLE) *p++ = 'r'; if (emask & AE_WRITABLE) *p++ = 'w'; *p = '\0'; return sdscatfmt(s, "id=%U addr=%s fd=%i name=%s age=%I idle=%I flags=%s db=%i sub=%i psub=%i multi=%i qbuf=%U qbuf-free=%U obl=%U oll=%U omem=%U events=%s cmd=%s", (unsigned long long) client->id, getClientPeerId(client), client->fd, client->name ? (char*)client->name->ptr : "", (long long)(server.unixtime - client->ctime), (long long)(server.unixtime - client->lastinteraction), flags, client->db->id, (int) dictSize(client->pubsub_channels), (int) listLength(client->pubsub_patterns), (client->flags & CLIENT_MULTI) ? client->mstate.count : -1, (unsigned long long) sdslen(client->querybuf), (unsigned long long) sdsavail(client->querybuf), (unsigned long long) client->bufpos, (unsigned long long) listLength(client->reply), (unsigned long long) getClientOutputBufferMemoryUsage(client), events, client->lastcmd ? client->lastcmd->name : "NULL"); } sds getAllClientsInfoString(void) { listNode *ln; listIter li; client *client; sds o = sdsnewlen(NULL,200*listLength(server.clients)); sdsclear(o); listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { client = listNodeValue(ln); o = catClientInfoString(o,client); o = sdscatlen(o,"\n",1); } return o; } void clientCommand(client *c) { listNode *ln; listIter li; client *client; if (!strcasecmp(c->argv[1]->ptr,"list") && c->argc == 2) { /* CLIENT LIST */ sds o = getAllClientsInfoString(); addReplyBulkCBuffer(c,o,sdslen(o)); sdsfree(o); } else if (!strcasecmp(c->argv[1]->ptr,"reply") && c->argc == 3) { /* CLIENT REPLY ON|OFF|SKIP */ if (!strcasecmp(c->argv[2]->ptr,"on")) { c->flags &= ~(CLIENT_REPLY_SKIP|CLIENT_REPLY_OFF); addReply(c,shared.ok); } else if (!strcasecmp(c->argv[2]->ptr,"off")) { c->flags |= CLIENT_REPLY_OFF; } else if (!strcasecmp(c->argv[2]->ptr,"skip")) { if (!(c->flags & CLIENT_REPLY_OFF)) c->flags |= CLIENT_REPLY_SKIP_NEXT; } else { addReply(c,shared.syntaxerr); return; } } else if (!strcasecmp(c->argv[1]->ptr,"kill")) { /* CLIENT KILL <ip:port> * CLIENT KILL <option> [value] ... <option> [value] */ char *addr = NULL; int type = -1; uint64_t id = 0; int skipme = 1; int killed = 0, close_this_client = 0; if (c->argc == 3) { /* Old style syntax: CLIENT KILL <addr> */ addr = c->argv[2]->ptr; skipme = 0; /* With the old form, you can kill yourself. */ } else if (c->argc > 3) { int i = 2; /* Next option index. */ /* New style syntax: parse options. */ while(i < c->argc) { int moreargs = c->argc > i+1; if (!strcasecmp(c->argv[i]->ptr,"id") && moreargs) { long long tmp; if (getLongLongFromObjectOrReply(c,c->argv[i+1],&tmp,NULL) != C_OK) return; id = tmp; } else if (!strcasecmp(c->argv[i]->ptr,"type") && moreargs) { type = getClientTypeByName(c->argv[i+1]->ptr); if (type == -1) { addReplyErrorFormat(c,"Unknown client type '%s'", (char*) c->argv[i+1]->ptr); return; } } else if (!strcasecmp(c->argv[i]->ptr,"addr") && moreargs) { addr = c->argv[i+1]->ptr; } else if (!strcasecmp(c->argv[i]->ptr,"skipme") && moreargs) { if (!strcasecmp(c->argv[i+1]->ptr,"yes")) { skipme = 1; } else if (!strcasecmp(c->argv[i+1]->ptr,"no")) { skipme = 0; } else { addReply(c,shared.syntaxerr); return; } } else { addReply(c,shared.syntaxerr); return; } i += 2; } } else { addReply(c,shared.syntaxerr); return; } /* Iterate clients killing all the matching clients. */ listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { client = listNodeValue(ln); if (addr && strcmp(getClientPeerId(client),addr) != 0) continue; if (type != -1 && getClientType(client) != type) continue; if (id != 0 && client->id != id) continue; if (c == client && skipme) continue; /* Kill it. */ if (c == client) { close_this_client = 1; } else { freeClient(client); } killed++; } /* Reply according to old/new format. */ if (c->argc == 3) { if (killed == 0) addReplyError(c,"No such client"); else addReply(c,shared.ok); } else { addReplyLongLong(c,killed); } /* If this client has to be closed, flag it as CLOSE_AFTER_REPLY * only after we queued the reply to its output buffers. */ if (close_this_client) c->flags |= CLIENT_CLOSE_AFTER_REPLY; } else if (!strcasecmp(c->argv[1]->ptr,"setname") && c->argc == 3) { int j, len = sdslen(c->argv[2]->ptr); char *p = c->argv[2]->ptr; /* Setting the client name to an empty string actually removes * the current name. */ if (len == 0) { if (c->name) decrRefCount(c->name); c->name = NULL; addReply(c,shared.ok); return; } /* Otherwise check if the charset is ok. We need to do this otherwise * CLIENT LIST format will break. You should always be able to * split by space to get the different fields. */ for (j = 0; j < len; j++) { if (p[j] < '!' || p[j] > '~') { /* ASCII is assumed. */ addReplyError(c, "Client names cannot contain spaces, " "newlines or special characters."); return; } } if (c->name) decrRefCount(c->name); c->name = c->argv[2]; incrRefCount(c->name); addReply(c,shared.ok); } else if (!strcasecmp(c->argv[1]->ptr,"getname") && c->argc == 2) { if (c->name) addReplyBulk(c,c->name); else addReply(c,shared.nullbulk); } else if (!strcasecmp(c->argv[1]->ptr,"pause") && c->argc == 3) { long long duration; if (getTimeoutFromObjectOrReply(c,c->argv[2],&duration,UNIT_MILLISECONDS) != C_OK) return; pauseClients(duration); addReply(c,shared.ok); } else { addReplyError(c, "Syntax error, try CLIENT (LIST | KILL | GETNAME | SETNAME | PAUSE | REPLY)"); } } /* Rewrite the command vector of the client. All the new objects ref count * is incremented. The old command vector is freed, and the old objects * ref count is decremented. */ void rewriteClientCommandVector(client *c, int argc, ...) { va_list ap; int j; robj **argv; /* The new argument vector */ argv = zmalloc(sizeof(robj*)*argc); va_start(ap,argc); for (j = 0; j < argc; j++) { robj *a; a = va_arg(ap, robj*); argv[j] = a; incrRefCount(a); } /* We free the objects in the original vector at the end, so we are * sure that if the same objects are reused in the new vector the * refcount gets incremented before it gets decremented. */ for (j = 0; j < c->argc; j++) decrRefCount(c->argv[j]); zfree(c->argv); /* Replace argv and argc with our new versions. */ c->argv = argv; c->argc = argc; c->cmd = lookupCommandOrOriginal(c->argv[0]->ptr); serverAssertWithInfo(c,NULL,c->cmd != NULL); va_end(ap); } /* Completely replace the client command vector with the provided one. */ void replaceClientCommandVector(client *c, int argc, robj **argv) { freeClientArgv(c); zfree(c->argv); c->argv = argv; c->argc = argc; c->cmd = lookupCommandOrOriginal(c->argv[0]->ptr); serverAssertWithInfo(c,NULL,c->cmd != NULL); } /* Rewrite a single item in the command vector. * The new val ref count is incremented, and the old decremented. * * It is possible to specify an argument over the current size of the * argument vector: in this case the array of objects gets reallocated * and c->argc set to the max value. However it's up to the caller to * * 1. Make sure there are no "holes" and all the arguments are set. * 2. If the original argument vector was longer than the one we * want to end with, it's up to the caller to set c->argc and * free the no longer used objects on c->argv. */ void rewriteClientCommandArgument(client *c, int i, robj *newval) { robj *oldval; if (i >= c->argc) { c->argv = zrealloc(c->argv,sizeof(robj*)*(i+1)); c->argc = i+1; c->argv[i] = NULL; } oldval = c->argv[i]; c->argv[i] = newval; incrRefCount(newval); if (oldval) decrRefCount(oldval); /* If this is the command name make sure to fix c->cmd. */ if (i == 0) { c->cmd = lookupCommandOrOriginal(c->argv[0]->ptr); serverAssertWithInfo(c,NULL,c->cmd != NULL); } } /* This function returns the number of bytes that Redis is virtually * using to store the reply still not read by the client. * It is "virtual" since the reply output list may contain objects that * are shared and are not really using additional memory. * * The function returns the total sum of the length of all the objects * stored in the output list, plus the memory used to allocate every * list node. The static reply buffer is not taken into account since it * is allocated anyway. * * Note: this function is very fast so can be called as many time as * the caller wishes. The main usage of this function currently is * enforcing the client output length limits. */ unsigned long getClientOutputBufferMemoryUsage(client *c) { unsigned long list_item_size = sizeof(listNode)+sizeof(robj); return c->reply_bytes + (list_item_size*listLength(c->reply)); } /* Get the class of a client, used in order to enforce limits to different * classes of clients. * * The function will return one of the following: * CLIENT_TYPE_NORMAL -> Normal client * CLIENT_TYPE_SLAVE -> Slave or client executing MONITOR command * CLIENT_TYPE_PUBSUB -> Client subscribed to Pub/Sub channels * CLIENT_TYPE_MASTER -> The client representing our replication master. */ int getClientType(client *c) { if (c->flags & CLIENT_MASTER) return CLIENT_TYPE_MASTER; if ((c->flags & CLIENT_SLAVE) && !(c->flags & CLIENT_MONITOR)) return CLIENT_TYPE_SLAVE; if (c->flags & CLIENT_PUBSUB) return CLIENT_TYPE_PUBSUB; return CLIENT_TYPE_NORMAL; } int getClientTypeByName(char *name) { if (!strcasecmp(name,"normal")) return CLIENT_TYPE_NORMAL; else if (!strcasecmp(name,"slave")) return CLIENT_TYPE_SLAVE; else if (!strcasecmp(name,"pubsub")) return CLIENT_TYPE_PUBSUB; else if (!strcasecmp(name,"master")) return CLIENT_TYPE_MASTER; else return -1; } char *getClientTypeName(int class) { switch(class) { case CLIENT_TYPE_NORMAL: return "normal"; case CLIENT_TYPE_SLAVE: return "slave"; case CLIENT_TYPE_PUBSUB: return "pubsub"; case CLIENT_TYPE_MASTER: return "master"; default: return NULL; } } /* The function checks if the client reached output buffer soft or hard * limit, and also update the state needed to check the soft limit as * a side effect. * * Return value: non-zero if the client reached the soft or the hard limit. * Otherwise zero is returned. */ int checkClientOutputBufferLimits(client *c) { int soft = 0, hard = 0, class; unsigned long used_mem = getClientOutputBufferMemoryUsage(c); class = getClientType(c); /* For the purpose of output buffer limiting, masters are handled * like normal clients. */ if (class == CLIENT_TYPE_MASTER) class = CLIENT_TYPE_NORMAL; if (server.client_obuf_limits[class].hard_limit_bytes && used_mem >= server.client_obuf_limits[class].hard_limit_bytes) hard = 1; if (server.client_obuf_limits[class].soft_limit_bytes && used_mem >= server.client_obuf_limits[class].soft_limit_bytes) soft = 1; /* We need to check if the soft limit is reached continuously for the * specified amount of seconds. */ if (soft) { if (c->obuf_soft_limit_reached_time == 0) { c->obuf_soft_limit_reached_time = server.unixtime; soft = 0; /* First time we see the soft limit reached */ } else { time_t elapsed = server.unixtime - c->obuf_soft_limit_reached_time; if (elapsed <= server.client_obuf_limits[class].soft_limit_seconds) { soft = 0; /* The client still did not reached the max number of seconds for the soft limit to be considered reached. */ } } } else { c->obuf_soft_limit_reached_time = 0; } return soft || hard; } /* Asynchronously close a client if soft or hard limit is reached on the * output buffer size. The caller can check if the client will be closed * checking if the client CLIENT_CLOSE_ASAP flag is set. * * Note: we need to close the client asynchronously because this function is * called from contexts where the client can't be freed safely, i.e. from the * lower level functions pushing data inside the client output buffers. */ void asyncCloseClientOnOutputBufferLimitReached(client *c) { serverAssert(c->reply_bytes < SIZE_MAX-(1024*64)); if (c->reply_bytes == 0 || c->flags & CLIENT_CLOSE_ASAP) return; if (checkClientOutputBufferLimits(c)) { sds client = catClientInfoString(sdsempty(),c); freeClientAsync(c); serverLog(LL_WARNING,"Client %s scheduled to be closed ASAP for overcoming of output buffer limits.", client); sdsfree(client); } } /* Helper function used by freeMemoryIfNeeded() in order to flush slaves * output buffers without returning control to the event loop. * This is also called by SHUTDOWN for a best-effort attempt to send * slaves the latest writes. */ void flushSlavesOutputBuffers(void) { listIter li; listNode *ln; listRewind(server.slaves,&li); while((ln = listNext(&li))) { client *slave = listNodeValue(ln); int events; /* Note that the following will not flush output buffers of slaves * in STATE_ONLINE but having put_online_on_ack set to true: in this * case the writable event is never installed, since the purpose * of put_online_on_ack is to postpone the moment it is installed. * This is what we want since slaves in this state should not receive * writes before the first ACK. */ events = aeGetFileEvents(server.el,slave->fd); if (events & AE_WRITABLE && slave->replstate == SLAVE_STATE_ONLINE && clientHasPendingReplies(slave)) { writeToClient(slave->fd,slave,0); } } } /* Pause clients up to the specified unixtime (in ms). While clients * are paused no command is processed from clients, so the data set can't * change during that time. * * However while this function pauses normal and Pub/Sub clients, slaves are * still served, so this function can be used on server upgrades where it is * required that slaves process the latest bytes from the replication stream * before being turned to masters. * * This function is also internally used by Redis Cluster for the manual * failover procedure implemented by CLUSTER FAILOVER. * * The function always succeed, even if there is already a pause in progress. * In such a case, the pause is extended if the duration is more than the * time left for the previous duration. However if the duration is smaller * than the time left for the previous pause, no change is made to the * left duration. */ void pauseClients(mstime_t end) { if (!server.clients_paused || end > server.clients_pause_end_time) server.clients_pause_end_time = end; server.clients_paused = 1; } /* Return non-zero if clients are currently paused. As a side effect the * function checks if the pause time was reached and clear it. */ int clientsArePaused(void) { if (server.clients_paused && server.clients_pause_end_time < server.mstime) { listNode *ln; listIter li; client *c; server.clients_paused = 0; /* Put all the clients in the unblocked clients queue in order to * force the re-processing of the input buffer if any. */ listRewind(server.clients,&li); while ((ln = listNext(&li)) != NULL) { c = listNodeValue(ln); /* Don't touch slaves and blocked clients. The latter pending * requests be processed when unblocked. */ if (c->flags & (CLIENT_SLAVE|CLIENT_BLOCKED)) continue; c->flags |= CLIENT_UNBLOCKED; listAddNodeTail(server.unblocked_clients,c); } } return server.clients_paused; } /* This function is called by Redis in order to process a few events from * time to time while blocked into some not interruptible operation. * This allows to reply to clients with the -LOADING error while loading the * data set at startup or after a full resynchronization with the master * and so forth. * * It calls the event loop in order to process a few events. Specifically we * try to call the event loop 4 times as long as we receive acknowledge that * some event was processed, in order to go forward with the accept, read, * write, close sequence needed to serve a client. * * The function returns the total number of events processed. */ int processEventsWhileBlocked(void) { int iterations = 4; /* See the function top-comment. */ int count = 0; while (iterations--) { int events = 0; events += aeProcessEvents(server.el, AE_FILE_EVENTS|AE_DONT_WAIT); events += handleClientsWithPendingWrites(); if (!events) break; count += events; } return count; }
./CrossVul/dataset_final_sorted/CWE-254/c/bad_4872_0
crossvul-cpp_data_good_4886_0
/* * libvirt-domain.c: entry points for virDomainPtr APIs * * Copyright (C) 2006-2015 Red Hat, Inc. * * 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, see * <http://www.gnu.org/licenses/>. */ #include <config.h> #include <sys/stat.h> #include "intprops.h" #include "datatypes.h" #include "viralloc.h" #include "virfile.h" #include "virlog.h" #include "virtypedparam.h" VIR_LOG_INIT("libvirt.domain"); #define VIR_FROM_THIS VIR_FROM_DOMAIN /** * virConnectListDomains: * @conn: pointer to the hypervisor connection * @ids: array to collect the list of IDs of active domains * @maxids: size of @ids * * Collect the list of active domains, and store their IDs in array @ids * * For inactive domains, see virConnectListDefinedDomains(). For more * control over the results, see virConnectListAllDomains(). * * Returns the number of domains found or -1 in case of error. Note that * this command is inherently racy; a domain can be started between a * call to virConnectNumOfDomains() and this call; you are only guaranteed * that all currently active domains were listed if the return is less * than @maxids. */ int virConnectListDomains(virConnectPtr conn, int *ids, int maxids) { VIR_DEBUG("conn=%p, ids=%p, maxids=%d", conn, ids, maxids); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNullArgGoto(ids, error); virCheckNonNegativeArgGoto(maxids, error); if (conn->driver->connectListDomains) { int ret = conn->driver->connectListDomains(conn, ids, maxids); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectNumOfDomains: * @conn: pointer to the hypervisor connection * * Provides the number of active domains. * * Returns the number of domain found or -1 in case of error */ int virConnectNumOfDomains(virConnectPtr conn) { VIR_DEBUG("conn=%p", conn); virResetLastError(); virCheckConnectReturn(conn, -1); if (conn->driver->connectNumOfDomains) { int ret = conn->driver->connectNumOfDomains(conn); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainGetConnect: * @dom: pointer to a domain * * Provides the connection pointer associated with a domain. The * reference counter on the connection is not increased by this * call. * * WARNING: When writing libvirt bindings in other languages, do * not use this function. Instead, store the connection and * the domain object together. * * Returns the virConnectPtr or NULL in case of failure. */ virConnectPtr virDomainGetConnect(virDomainPtr dom) { VIR_DOMAIN_DEBUG(dom); virResetLastError(); virCheckDomainReturn(dom, NULL); return dom->conn; } /** * virDomainCreateXML: * @conn: pointer to the hypervisor connection * @xmlDesc: string containing an XML description of the domain * @flags: bitwise-OR of supported virDomainCreateFlags * * Launch a new guest domain, based on an XML description similar * to the one returned by virDomainGetXMLDesc() * This function may require privileged access to the hypervisor. * The domain is not persistent, so its definition will disappear when it * is destroyed, or if the host is restarted (see virDomainDefineXML() to * define persistent domains). * * If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain * will be started, but its CPUs will remain paused. The CPUs * can later be manually started using virDomainResume. * * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest * domain will be automatically destroyed when the virConnectPtr * object is finally released. This will also happen if the * client application crashes / loses its connection to the * libvirtd daemon. Any domains marked for auto destroy will * block attempts at migration, save-to-file, or snapshots. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure */ virDomainPtr virDomainCreateXML(virConnectPtr conn, const char *xmlDesc, unsigned int flags) { VIR_DEBUG("conn=%p, xmlDesc=%s, flags=%x", conn, NULLSTR(xmlDesc), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(xmlDesc, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainCreateXML) { virDomainPtr ret; ret = conn->driver->domainCreateXML(conn, xmlDesc, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainCreateXMLWithFiles: * @conn: pointer to the hypervisor connection * @xmlDesc: string containing an XML description of the domain * @nfiles: number of file descriptors passed * @files: list of file descriptors passed * @flags: bitwise-OR of supported virDomainCreateFlags * * Launch a new guest domain, based on an XML description similar * to the one returned by virDomainGetXMLDesc() * This function may require privileged access to the hypervisor. * The domain is not persistent, so its definition will disappear when it * is destroyed, or if the host is restarted (see virDomainDefineXML() to * define persistent domains). * * @files provides an array of file descriptors which will be * made available to the 'init' process of the guest. The file * handles exposed to the guest will be renumbered to start * from 3 (ie immediately following stderr). This is only * supported for guests which use container based virtualization * technology. * * If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain * will be started, but its CPUs will remain paused. The CPUs * can later be manually started using virDomainResume. * * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest * domain will be automatically destroyed when the virConnectPtr * object is finally released. This will also happen if the * client application crashes / loses its connection to the * libvirtd daemon. Any domains marked for auto destroy will * block attempts at migration, save-to-file, or snapshots. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure */ virDomainPtr virDomainCreateXMLWithFiles(virConnectPtr conn, const char *xmlDesc, unsigned int nfiles, int *files, unsigned int flags) { VIR_DEBUG("conn=%p, xmlDesc=%s, nfiles=%u, files=%p, flags=%x", conn, NULLSTR(xmlDesc), nfiles, files, flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(xmlDesc, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainCreateXMLWithFiles) { virDomainPtr ret; ret = conn->driver->domainCreateXMLWithFiles(conn, xmlDesc, nfiles, files, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainCreateLinux: * @conn: pointer to the hypervisor connection * @xmlDesc: string containing an XML description of the domain * @flags: extra flags; not used yet, so callers should always pass 0 * * Deprecated after 0.4.6. * Renamed to virDomainCreateXML() providing identical functionality. * This existing name will be left indefinitely for API compatibility. * * Returns a new domain object or NULL in case of failure */ virDomainPtr virDomainCreateLinux(virConnectPtr conn, const char *xmlDesc, unsigned int flags) { return virDomainCreateXML(conn, xmlDesc, flags); } /** * virDomainLookupByID: * @conn: pointer to the hypervisor connection * @id: the domain ID number * * Try to find a domain based on the hypervisor ID number * Note that this won't work for inactive domains which have an ID of -1, * in that case a lookup based on the Name or UUId need to be done instead. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure. If the * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised. */ virDomainPtr virDomainLookupByID(virConnectPtr conn, int id) { VIR_DEBUG("conn=%p, id=%d", conn, id); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNegativeArgGoto(id, error); if (conn->driver->domainLookupByID) { virDomainPtr ret; ret = conn->driver->domainLookupByID(conn, id); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainLookupByUUID: * @conn: pointer to the hypervisor connection * @uuid: the raw UUID for the domain * * Try to lookup a domain on the given hypervisor based on its UUID. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure. If the * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised. */ virDomainPtr virDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid) { VIR_UUID_DEBUG(conn, uuid); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(uuid, error); if (conn->driver->domainLookupByUUID) { virDomainPtr ret; ret = conn->driver->domainLookupByUUID(conn, uuid); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainLookupByUUIDString: * @conn: pointer to the hypervisor connection * @uuidstr: the string UUID for the domain * * Try to lookup a domain on the given hypervisor based on its UUID. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure. If the * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised. */ virDomainPtr virDomainLookupByUUIDString(virConnectPtr conn, const char *uuidstr) { unsigned char uuid[VIR_UUID_BUFLEN]; VIR_DEBUG("conn=%p, uuidstr=%s", conn, NULLSTR(uuidstr)); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(uuidstr, error); if (virUUIDParse(uuidstr, uuid) < 0) { virReportInvalidArg(uuidstr, "%s", _("Invalid UUID")); goto error; } return virDomainLookupByUUID(conn, &uuid[0]); error: virDispatchError(conn); return NULL; } /** * virDomainLookupByName: * @conn: pointer to the hypervisor connection * @name: name for the domain * * Try to lookup a domain on the given hypervisor based on its name. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns a new domain object or NULL in case of failure. If the * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised. */ virDomainPtr virDomainLookupByName(virConnectPtr conn, const char *name) { VIR_DEBUG("conn=%p, name=%s", conn, NULLSTR(name)); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(name, error); if (conn->driver->domainLookupByName) { virDomainPtr dom; dom = conn->driver->domainLookupByName(conn, name); if (!dom) goto error; return dom; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainDestroy: * @domain: a domain object * * Destroy the domain object. The running instance is shutdown if not down * already and all resources used by it are given back to the hypervisor. This * does not free the associated virDomainPtr object. * This function may require privileged access. * * virDomainDestroy first requests that a guest terminate * (e.g. SIGTERM), then waits for it to comply. After a reasonable * timeout, if the guest still exists, virDomainDestroy will * forcefully terminate the guest (e.g. SIGKILL) if necessary (which * may produce undesirable results, for example unflushed disk cache * in the guest). To avoid this possibility, it's recommended to * instead call virDomainDestroyFlags, sending the * VIR_DOMAIN_DESTROY_GRACEFUL flag. * * If the domain is transient and has any snapshot metadata (see * virDomainSnapshotNum()), then that metadata will automatically * be deleted when the domain quits. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainDestroy(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainDestroy) { int ret; ret = conn->driver->domainDestroy(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainDestroyFlags: * @domain: a domain object * @flags: bitwise-OR of virDomainDestroyFlagsValues * * Destroy the domain object. The running instance is shutdown if not down * already and all resources used by it are given back to the hypervisor. * This does not free the associated virDomainPtr object. * This function may require privileged access. * * Calling this function with no @flags set (equal to zero) is * equivalent to calling virDomainDestroy, and after a reasonable * timeout will forcefully terminate the guest (e.g. SIGKILL) if * necessary (which may produce undesirable results, for example * unflushed disk cache in the guest). Including * VIR_DOMAIN_DESTROY_GRACEFUL in the flags will prevent the forceful * termination of the guest, and virDomainDestroyFlags will instead * return an error if the guest doesn't terminate by the end of the * timeout; at that time, the management application can decide if * calling again without VIR_DOMAIN_DESTROY_GRACEFUL is appropriate. * * Another alternative which may produce cleaner results for the * guest's disks is to use virDomainShutdown() instead, but that * depends on guest support (some hypervisor/guest combinations may * ignore the shutdown request). * * * Returns 0 in case of success and -1 in case of failure. */ int virDomainDestroyFlags(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainDestroyFlags) { int ret; ret = conn->driver->domainDestroyFlags(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainFree: * @domain: a domain object * * Free the domain object. The running instance is kept alive. * The data structure is freed and should not be used thereafter. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainFree(virDomainPtr domain) { VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); virObjectUnref(domain); return 0; } /** * virDomainRef: * @domain: the domain to hold a reference on * * Increment the reference count on the domain. For each * additional call to this method, there shall be a corresponding * call to virDomainFree to release the reference count, once * the caller no longer needs the reference to this object. * * This method is typically useful for applications where multiple * threads are using a connection, and it is required that the * connection remain open until all threads have finished using * it. ie, each new thread using a domain would increment * the reference count. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainRef(virDomainPtr domain) { VIR_DOMAIN_DEBUG(domain, "refs=%d", domain ? domain->object.u.s.refs : 0); virResetLastError(); virCheckDomainReturn(domain, -1); virObjectRef(domain); return 0; } /** * virDomainSuspend: * @domain: a domain object * * Suspends an active domain, the process is frozen without further access * to CPU resources and I/O but the memory used by the domain at the * hypervisor level will stay allocated. Use virDomainResume() to reactivate * the domain. * This function may require privileged access. * Moreover, suspend may not be supported if domain is in some * special state like VIR_DOMAIN_PMSUSPENDED. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSuspend(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainSuspend) { int ret; ret = conn->driver->domainSuspend(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainResume: * @domain: a domain object * * Resume a suspended domain, the process is restarted from the state where * it was frozen by calling virDomainSuspend(). * This function may require privileged access * Moreover, resume may not be supported if domain is in some * special state like VIR_DOMAIN_PMSUSPENDED. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainResume(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainResume) { int ret; ret = conn->driver->domainResume(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainPMSuspendForDuration: * @dom: a domain object * @target: a value from virNodeSuspendTarget * @duration: duration in seconds to suspend, or 0 for indefinite * @flags: extra flags; not used yet, so callers should always pass 0 * * Attempt to have the guest enter the given @target power management * suspension level. If @duration is non-zero, also schedule the guest to * resume normal operation after that many seconds, if nothing else has * resumed it earlier. Some hypervisors require that @duration be 0, for * an indefinite suspension. * * Dependent on hypervisor used, this may require a * guest agent to be available, e.g. QEMU. * * Beware that at least for QEMU, the domain's process will be terminated * when VIR_NODE_SUSPEND_TARGET_DISK is used and a new process will be * launched when libvirt is asked to wake up the domain. As a result of * this, any runtime changes, such as device hotplug or memory settings, * are lost unless such changes were made with VIR_DOMAIN_AFFECT_CONFIG * flag. * * Returns: 0 on success, * -1 on failure. */ int virDomainPMSuspendForDuration(virDomainPtr dom, unsigned int target, unsigned long long duration, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "target=%u duration=%llu flags=%x", target, duration, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainPMSuspendForDuration) { int ret; ret = conn->driver->domainPMSuspendForDuration(dom, target, duration, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainPMWakeup: * @dom: a domain object * @flags: extra flags; not used yet, so callers should always pass 0 * * Inject a wakeup into the guest that previously used * virDomainPMSuspendForDuration, rather than waiting for the * previously requested duration (if any) to elapse. * * Returns: 0 on success, * -1 on failure. */ int virDomainPMWakeup(virDomainPtr dom, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainPMWakeup) { int ret; ret = conn->driver->domainPMWakeup(dom, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainSave: * @domain: a domain object * @to: path for the output file * * This method will suspend a domain and save its memory contents to * a file on disk. After the call, if successful, the domain is not * listed as running anymore (this ends the life of a transient domain). * Use virDomainRestore() to restore a domain after saving. * * See virDomainSaveFlags() for more control. Also, a save file can * be inspected or modified slightly with virDomainSaveImageGetXMLDesc() * and virDomainSaveImageDefineXML(). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSave(virDomainPtr domain, const char *to) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "to=%s", to); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(to, error); if (conn->driver->domainSave) { int ret; char *absolute_to; /* We must absolutize the file path as the save is done out of process */ if (virFileAbsPath(to, &absolute_to) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute output file path")); goto error; } ret = conn->driver->domainSave(domain, absolute_to); VIR_FREE(absolute_to); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSaveFlags: * @domain: a domain object * @to: path for the output file * @dxml: (optional) XML config for adjusting guest xml used on restore * @flags: bitwise-OR of virDomainSaveRestoreFlags * * This method will suspend a domain and save its memory contents to * a file on disk. After the call, if successful, the domain is not * listed as running anymore (this ends the life of a transient domain). * Use virDomainRestore() to restore a domain after saving. * * If the hypervisor supports it, @dxml can be used to alter * host-specific portions of the domain XML that will be used when * restoring an image. For example, it is possible to alter the * backing filename that is associated with a disk device, in order to * prepare for file renaming done as part of backing up the disk * device while the domain is stopped. * * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will * attempt to bypass the file system cache while creating the file, or * fail if it cannot do so for the given system; this can allow less * pressure on file system cache, but also risks slowing saves to NFS. * * Normally, the saved state file will remember whether the domain was * running or paused, and restore defaults to the same state. * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in * @flags will override what state gets saved into the file. These * two flags are mutually exclusive. * * A save file can be inspected or modified slightly with * virDomainSaveImageGetXMLDesc() and virDomainSaveImageDefineXML(). * * Some hypervisors may prevent this operation if there is a current * block copy operation; in that case, use virDomainBlockJobAbort() * to stop the block copy first. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSaveFlags(virDomainPtr domain, const char *to, const char *dxml, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "to=%s, dxml=%s, flags=%x", to, NULLSTR(dxml), flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(to, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING, VIR_DOMAIN_SAVE_PAUSED, error); if (conn->driver->domainSaveFlags) { int ret; char *absolute_to; /* We must absolutize the file path as the save is done out of process */ if (virFileAbsPath(to, &absolute_to) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute output file path")); goto error; } ret = conn->driver->domainSaveFlags(domain, absolute_to, dxml, flags); VIR_FREE(absolute_to); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainRestore: * @conn: pointer to the hypervisor connection * @from: path to the input file * * This method will restore a domain saved to disk by virDomainSave(). * * See virDomainRestoreFlags() for more control. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainRestore(virConnectPtr conn, const char *from) { VIR_DEBUG("conn=%p, from=%s", conn, NULLSTR(from)); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(from, error); if (conn->driver->domainRestore) { int ret; char *absolute_from; /* We must absolutize the file path as the restore is done out of process */ if (virFileAbsPath(from, &absolute_from) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute input file path")); goto error; } ret = conn->driver->domainRestore(conn, absolute_from); VIR_FREE(absolute_from); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainRestoreFlags: * @conn: pointer to the hypervisor connection * @from: path to the input file * @dxml: (optional) XML config for adjusting guest xml used on restore * @flags: bitwise-OR of virDomainSaveRestoreFlags * * This method will restore a domain saved to disk by virDomainSave(). * * If the hypervisor supports it, @dxml can be used to alter * host-specific portions of the domain XML that will be used when * restoring an image. For example, it is possible to alter the * backing filename that is associated with a disk device, in order to * prepare for file renaming done as part of backing up the disk * device while the domain is stopped. * * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will * attempt to bypass the file system cache while restoring the file, or * fail if it cannot do so for the given system; this can allow less * pressure on file system cache, but also risks slowing restores from NFS. * * Normally, the saved state file will remember whether the domain was * running or paused, and restore defaults to the same state. * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in * @flags will override the default read from the file. These two * flags are mutually exclusive. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainRestoreFlags(virConnectPtr conn, const char *from, const char *dxml, unsigned int flags) { VIR_DEBUG("conn=%p, from=%s, dxml=%s, flags=%x", conn, NULLSTR(from), NULLSTR(dxml), flags); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(from, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING, VIR_DOMAIN_SAVE_PAUSED, error); if (conn->driver->domainRestoreFlags) { int ret; char *absolute_from; /* We must absolutize the file path as the restore is done out of process */ if (virFileAbsPath(from, &absolute_from) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute input file path")); goto error; } ret = conn->driver->domainRestoreFlags(conn, absolute_from, dxml, flags); VIR_FREE(absolute_from); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainSaveImageGetXMLDesc: * @conn: pointer to the hypervisor connection * @file: path to saved state file * @flags: bitwise-OR of subset of virDomainXMLFlags * * This method will extract the XML describing the domain at the time * a saved state file was created. @file must be a file created * previously by virDomainSave() or virDomainSaveFlags(). * * No security-sensitive data will be included unless @flags contains * VIR_DOMAIN_XML_SECURE; this flag is rejected on read-only * connections. For this API, @flags should not contain either * VIR_DOMAIN_XML_INACTIVE or VIR_DOMAIN_XML_UPDATE_CPU. * * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of * error. The caller must free() the returned value. */ char * virDomainSaveImageGetXMLDesc(virConnectPtr conn, const char *file, unsigned int flags) { VIR_DEBUG("conn=%p, file=%s, flags=%x", conn, NULLSTR(file), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckNonNullArgGoto(file, error); if ((conn->flags & VIR_CONNECT_RO) && (flags & VIR_DOMAIN_XML_SECURE)) { virReportError(VIR_ERR_OPERATION_DENIED, "%s", _("virDomainSaveImageGetXMLDesc with secure flag")); goto error; } if (conn->driver->domainSaveImageGetXMLDesc) { char *ret; char *absolute_file; /* We must absolutize the file path as the read is done out of process */ if (virFileAbsPath(file, &absolute_file) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute input file path")); goto error; } ret = conn->driver->domainSaveImageGetXMLDesc(conn, absolute_file, flags); VIR_FREE(absolute_file); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainSaveImageDefineXML: * @conn: pointer to the hypervisor connection * @file: path to saved state file * @dxml: XML config for adjusting guest xml used on restore * @flags: bitwise-OR of virDomainSaveRestoreFlags * * This updates the definition of a domain stored in a saved state * file. @file must be a file created previously by virDomainSave() * or virDomainSaveFlags(). * * @dxml can be used to alter host-specific portions of the domain XML * that will be used when restoring an image. For example, it is * possible to alter the backing filename that is associated with a * disk device, to match renaming done as part of backing up the disk * device while the domain is stopped. * * Normally, the saved state file will remember whether the domain was * running or paused, and restore defaults to the same state. * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in * @flags will override the default saved into the file; omitting both * leaves the file's default unchanged. These two flags are mutually * exclusive. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSaveImageDefineXML(virConnectPtr conn, const char *file, const char *dxml, unsigned int flags) { VIR_DEBUG("conn=%p, file=%s, dxml=%s, flags=%x", conn, NULLSTR(file), NULLSTR(dxml), flags); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(file, error); virCheckNonNullArgGoto(dxml, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING, VIR_DOMAIN_SAVE_PAUSED, error); if (conn->driver->domainSaveImageDefineXML) { int ret; char *absolute_file; /* We must absolutize the file path as the read is done out of process */ if (virFileAbsPath(file, &absolute_file) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute input file path")); goto error; } ret = conn->driver->domainSaveImageDefineXML(conn, absolute_file, dxml, flags); VIR_FREE(absolute_file); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainCoreDump: * @domain: a domain object * @to: path for the core file * @flags: bitwise-OR of virDomainCoreDumpFlags * * This method will dump the core of a domain on a given file for analysis. * Note that for remote Xen Daemon the file path will be interpreted in * the remote host. Hypervisors may require the user to manually ensure * proper permissions on the file named by @to. * * If @flags includes VIR_DUMP_CRASH, then leave the guest shut off with * a crashed state after the dump completes. If @flags includes * VIR_DUMP_LIVE, then make the core dump while continuing to allow * the guest to run; otherwise, the guest is suspended during the dump. * VIR_DUMP_RESET flag forces reset of the guest after dump. * The above three flags are mutually exclusive. * * Additionally, if @flags includes VIR_DUMP_BYPASS_CACHE, then libvirt * will attempt to bypass the file system cache while creating the file, * or fail if it cannot do so for the given system; this can allow less * pressure on file system cache, but also risks slowing saves to NFS. * * For more control over the output format, see virDomainCoreDumpWithFormat(). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainCoreDump(virDomainPtr domain, const char *to, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "to=%s, flags=%x", to, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(to, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_LIVE, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_RESET, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_LIVE, VIR_DUMP_RESET, error); if (conn->driver->domainCoreDump) { int ret; char *absolute_to; /* We must absolutize the file path as the save is done out of process */ if (virFileAbsPath(to, &absolute_to) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute core file path")); goto error; } ret = conn->driver->domainCoreDump(domain, absolute_to, flags); VIR_FREE(absolute_to); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainCoreDumpWithFormat: * @domain: a domain object * @to: path for the core file * @dumpformat: format of domain memory's dump (one of virDomainCoreDumpFormat enum) * @flags: bitwise-OR of virDomainCoreDumpFlags * * This method will dump the core of a domain on a given file for analysis. * Note that for remote Xen Daemon the file path will be interpreted in * the remote host. Hypervisors may require the user to manually ensure * proper permissions on the file named by @to. * * @dumpformat controls which format the dump will have; use of * VIR_DOMAIN_CORE_DUMP_FORMAT_RAW mirrors what virDomainCoreDump() will * perform. Not all hypervisors are able to support all formats. * * If @flags includes VIR_DUMP_CRASH, then leave the guest shut off with * a crashed state after the dump completes. If @flags includes * VIR_DUMP_LIVE, then make the core dump while continuing to allow * the guest to run; otherwise, the guest is suspended during the dump. * VIR_DUMP_RESET flag forces reset of the guest after dump. * The above three flags are mutually exclusive. * * Additionally, if @flags includes VIR_DUMP_BYPASS_CACHE, then libvirt * will attempt to bypass the file system cache while creating the file, * or fail if it cannot do so for the given system; this can allow less * pressure on file system cache, but also risks slowing saves to NFS. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainCoreDumpWithFormat(virDomainPtr domain, const char *to, unsigned int dumpformat, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "to=%s, dumpformat=%u, flags=%x", to, dumpformat, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(to, error); if (dumpformat >= VIR_DOMAIN_CORE_DUMP_FORMAT_LAST) { virReportInvalidArg(flags, _("dumpformat '%d' is not supported"), dumpformat); goto error; } VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_LIVE, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_RESET, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_LIVE, VIR_DUMP_RESET, error); if (conn->driver->domainCoreDumpWithFormat) { int ret; char *absolute_to; /* We must absolutize the file path as the save is done out of process */ if (virFileAbsPath(to, &absolute_to) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("could not build absolute core file path")); goto error; } ret = conn->driver->domainCoreDumpWithFormat(domain, absolute_to, dumpformat, flags); VIR_FREE(absolute_to); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainScreenshot: * @domain: a domain object * @stream: stream to use as output * @screen: monitor ID to take screenshot from * @flags: extra flags; not used yet, so callers should always pass 0 * * Take a screenshot of current domain console as a stream. The image format * is hypervisor specific. Moreover, some hypervisors supports multiple * displays per domain. These can be distinguished by @screen argument. * * This call sets up a stream; subsequent use of stream API is necessary * to transfer actual data, determine how much data is successfully * transferred, and detect any errors. * * The screen ID is the sequential number of screen. In case of multiple * graphics cards, heads are enumerated before devices, e.g. having * two graphics cards, both with four heads, screen ID 5 addresses * the second head on the second card. * * Returns a string representing the mime-type of the image format, or * NULL upon error. The caller must free() the returned value. */ char * virDomainScreenshot(virDomainPtr domain, virStreamPtr stream, unsigned int screen, unsigned int flags) { VIR_DOMAIN_DEBUG(domain, "stream=%p, flags=%x", stream, flags); virResetLastError(); virCheckDomainReturn(domain, NULL); virCheckStreamGoto(stream, error); virCheckReadOnlyGoto(domain->conn->flags, error); if (domain->conn != stream->conn) { virReportInvalidArg(stream, _("stream must match connection of domain '%s'"), domain->name); goto error; } if (domain->conn->driver->domainScreenshot) { char *ret; ret = domain->conn->driver->domainScreenshot(domain, stream, screen, flags); if (ret == NULL) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virDomainShutdown: * @domain: a domain object * * Shutdown a domain, the domain object is still usable thereafter, but * the domain OS is being stopped. Note that the guest OS may ignore the * request. Additionally, the hypervisor may check and support the domain * 'on_poweroff' XML setting resulting in a domain that reboots instead of * shutting down. For guests that react to a shutdown request, the differences * from virDomainDestroy() are that the guests disk storage will be in a * stable state rather than having the (virtual) power cord pulled, and * this command returns as soon as the shutdown request is issued rather * than blocking until the guest is no longer running. * * If the domain is transient and has any snapshot metadata (see * virDomainSnapshotNum()), then that metadata will automatically * be deleted when the domain quits. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainShutdown(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainShutdown) { int ret; ret = conn->driver->domainShutdown(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainShutdownFlags: * @domain: a domain object * @flags: bitwise-OR of virDomainShutdownFlagValues * * Shutdown a domain, the domain object is still usable thereafter but * the domain OS is being stopped. Note that the guest OS may ignore the * request. Additionally, the hypervisor may check and support the domain * 'on_poweroff' XML setting resulting in a domain that reboots instead of * shutting down. For guests that react to a shutdown request, the differences * from virDomainDestroy() are that the guest's disk storage will be in a * stable state rather than having the (virtual) power cord pulled, and * this command returns as soon as the shutdown request is issued rather * than blocking until the guest is no longer running. * * If the domain is transient and has any snapshot metadata (see * virDomainSnapshotNum()), then that metadata will automatically * be deleted when the domain quits. * * If @flags is set to zero, then the hypervisor will choose the * method of shutdown it considers best. To have greater control * pass one or more of the virDomainShutdownFlagValues. The order * in which the hypervisor tries each shutdown method is undefined, * and a hypervisor is not required to support all methods. * * To use guest agent (VIR_DOMAIN_SHUTDOWN_GUEST_AGENT) the domain XML * must have <channel> configured. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainShutdownFlags(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainShutdownFlags) { int ret; ret = conn->driver->domainShutdownFlags(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainReboot: * @domain: a domain object * @flags: bitwise-OR of virDomainRebootFlagValues * * Reboot a domain, the domain object is still usable thereafter, but * the domain OS is being stopped for a restart. * Note that the guest OS may ignore the request. * Additionally, the hypervisor may check and support the domain * 'on_reboot' XML setting resulting in a domain that shuts down instead * of rebooting. * * If @flags is set to zero, then the hypervisor will choose the * method of shutdown it considers best. To have greater control * pass one or more of the virDomainRebootFlagValues. The order * in which the hypervisor tries each shutdown method is undefined, * and a hypervisor is not required to support all methods. * * To use guest agent (VIR_DOMAIN_REBOOT_GUEST_AGENT) the domain XML * must have <channel> configured. * * Due to implementation limitations in some drivers (the qemu driver, * for instance) it is not advised to migrate or save a guest that is * rebooting as a result of this API. Migrating such a guest can lead * to a plain shutdown on the destination. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainReboot(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainReboot) { int ret; ret = conn->driver->domainReboot(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainReset: * @domain: a domain object * @flags: extra flags; not used yet, so callers should always pass 0 * * Reset a domain immediately without any guest OS shutdown. * Reset emulates the power reset button on a machine, where all * hardware sees the RST line set and reinitializes internal state. * * Note that there is a risk of data loss caused by reset without any * guest OS shutdown. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainReset(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainReset) { int ret; ret = conn->driver->domainReset(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetName: * @domain: a domain object * * Get the public name for that domain * * Returns a pointer to the name or NULL, the string need not be deallocated * its lifetime will be the same as the domain object. */ const char * virDomainGetName(virDomainPtr domain) { VIR_DEBUG("domain=%p", domain); virResetLastError(); virCheckDomainReturn(domain, NULL); return domain->name; } /** * virDomainGetUUID: * @domain: a domain object * @uuid: pointer to a VIR_UUID_BUFLEN bytes array * * Get the UUID for a domain * * Returns -1 in case of error, 0 in case of success */ int virDomainGetUUID(virDomainPtr domain, unsigned char *uuid) { VIR_DOMAIN_DEBUG(domain, "uuid=%p", uuid); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(uuid, error); memcpy(uuid, &domain->uuid[0], VIR_UUID_BUFLEN); return 0; error: virDispatchError(domain->conn); return -1; } /** * virDomainGetUUIDString: * @domain: a domain object * @buf: pointer to a VIR_UUID_STRING_BUFLEN bytes array * * Get the UUID for a domain as string. For more information about * UUID see RFC4122. * * Returns -1 in case of error, 0 in case of success */ int virDomainGetUUIDString(virDomainPtr domain, char *buf) { VIR_DOMAIN_DEBUG(domain, "buf=%p", buf); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(buf, error); virUUIDFormat(domain->uuid, buf); return 0; error: virDispatchError(domain->conn); return -1; } /** * virDomainGetID: * @domain: a domain object * * Get the hypervisor ID number for the domain * * Returns the domain ID number or (unsigned int) -1 in case of error */ unsigned int virDomainGetID(virDomainPtr domain) { VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, (unsigned int)-1); return domain->id; } /** * virDomainGetOSType: * @domain: a domain object * * Get the type of domain operation system. * * Returns the new string or NULL in case of error, the string must be * freed by the caller. */ char * virDomainGetOSType(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; if (conn->driver->domainGetOSType) { char *ret; ret = conn->driver->domainGetOSType(domain); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virDomainGetMaxMemory: * @domain: a domain object or NULL * * Retrieve the maximum amount of physical memory allocated to a * domain. If domain is NULL, then this get the amount of memory reserved * to Domain0 i.e. the domain where the application runs. * * Returns the memory size in kibibytes (blocks of 1024 bytes), or 0 in * case of error. */ unsigned long virDomainGetMaxMemory(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, 0); conn = domain->conn; if (conn->driver->domainGetMaxMemory) { unsigned long long ret; ret = conn->driver->domainGetMaxMemory(domain); if (ret == 0) goto error; if ((unsigned long) ret != ret) { virReportError(VIR_ERR_OVERFLOW, _("result too large: %llu"), ret); goto error; } return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return 0; } /** * virDomainSetMaxMemory: * @domain: a domain object or NULL * @memory: the memory size in kibibytes (blocks of 1024 bytes) * * Dynamically change the maximum amount of physical memory allocated to a * domain. If domain is NULL, then this change the amount of memory reserved * to Domain0 i.e. the domain where the application runs. * This function may require privileged access to the hypervisor. * * This command is hypervisor-specific for whether active, persistent, * or both configurations are changed; for more control, use * virDomainSetMemoryFlags(). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSetMaxMemory(virDomainPtr domain, unsigned long memory) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "memory=%lu", memory); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonZeroArgGoto(memory, error); if (virMemoryMaxValue(true) / 1024 <= memory) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %lu"), memory); goto error; } if (conn->driver->domainSetMaxMemory) { int ret; ret = conn->driver->domainSetMaxMemory(domain, memory); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetMemory: * @domain: a domain object or NULL * @memory: the memory size in kibibytes (blocks of 1024 bytes) * * Dynamically change the target amount of physical memory allocated to a * domain. If domain is NULL, then this change the amount of memory reserved * to Domain0 i.e. the domain where the application runs. * This function may require privileged access to the hypervisor. * * This command is hypervisor-specific for whether active, persistent, * or both configurations are changed; for more control, use * virDomainSetMemoryFlags(). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainSetMemory(virDomainPtr domain, unsigned long memory) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "memory=%lu", memory); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonZeroArgGoto(memory, error); if (virMemoryMaxValue(true) / 1024 <= memory) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %lu"), memory); goto error; } if (conn->driver->domainSetMemory) { int ret; ret = conn->driver->domainSetMemory(domain, memory); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetMemoryFlags: * @domain: a domain object or NULL * @memory: the memory size in kibibytes (blocks of 1024 bytes) * @flags: bitwise-OR of virDomainMemoryModFlags * * Dynamically change the target amount of physical memory allocated to a * domain. If domain is NULL, then this change the amount of memory reserved * to Domain0 i.e. the domain where the application runs. * This function may require privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects * a running domain and will fail if domain is not active. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified * (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain * modifies persistent setup, while an active domain is hypervisor-dependent * on whether just live or both live and persistent state is changed. * If VIR_DOMAIN_MEM_MAXIMUM is set, the change affects domain's maximum memory * size rather than current memory size. * Not all hypervisors can support all flag combinations. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSetMemoryFlags(virDomainPtr domain, unsigned long memory, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "memory=%lu, flags=%x", memory, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonZeroArgGoto(memory, error); if (virMemoryMaxValue(true) / 1024 <= memory) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %lu"), memory); goto error; } if (conn->driver->domainSetMemoryFlags) { int ret; ret = conn->driver->domainSetMemoryFlags(domain, memory, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetMemoryStatsPeriod: * @domain: a domain object or NULL * @period: the period in seconds for stats collection * @flags: bitwise-OR of virDomainMemoryModFlags * * Dynamically change the domain memory balloon driver statistics collection * period. Use 0 to disable and a positive value to enable. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects * a running domain and will fail if domain is not active. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified * (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain * modifies persistent setup, while an active domain is hypervisor-dependent * on whether just live or both live and persistent state is changed. * * Not all hypervisors can support all flag combinations. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSetMemoryStatsPeriod(virDomainPtr domain, int period, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "period=%d, flags=%x", period, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); /* This must be positive to set the balloon collection period */ virCheckNonNegativeArgGoto(period, error); if (conn->driver->domainSetMemoryStatsPeriod) { int ret; ret = conn->driver->domainSetMemoryStatsPeriod(domain, period, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetMemoryParameters: * @domain: pointer to domain object * @params: pointer to memory parameter objects * @nparams: number of memory parameter (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainModificationImpact * * Change all or a subset of the memory tunables. * This function may require privileged access to the hypervisor. * * Possible values for all *_limit memory tunables are in range from 0 to * VIR_DOMAIN_MEMORY_PARAM_UNLIMITED. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckPositiveArgGoto(nparams, error); if (virTypedParameterValidateSet(conn, params, nparams) < 0) goto error; if (conn->driver->domainSetMemoryParameters) { int ret; ret = conn->driver->domainSetMemoryParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetMemoryParameters: * @domain: pointer to domain object * @params: pointer to memory parameter object * (return value, allocated by the caller) * @nparams: pointer to number of memory parameters; input and output * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all memory parameters. On input, @nparams gives the size of the * @params array; on output, @nparams gives how many slots were filled * with parameter information, which might be less but will not exceed * the input value. * * As a special case, calling with @params as NULL and @nparams as 0 on * input will cause @nparams on output to contain the number of parameters * supported by the hypervisor. The caller should then allocate @params * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API * again. * * Here is a sample code snippet: * * if (virDomainGetMemoryParameters(dom, NULL, &nparams, 0) == 0 && * nparams != 0) { * if ((params = malloc(sizeof(*params) * nparams)) == NULL) * goto error; * memset(params, 0, sizeof(*params) * nparams); * if (virDomainGetMemoryParameters(dom, params, &nparams, 0)) * goto error; * } * * This function may require privileged access to the hypervisor. This function * expects the caller to allocate the @params. * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetMemoryParameters(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, (nparams) ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) virCheckNonNullArgGoto(params, error); if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); conn = domain->conn; if (conn->driver->domainGetMemoryParameters) { int ret; ret = conn->driver->domainGetMemoryParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetNumaParameters: * @domain: pointer to domain object * @params: pointer to numa parameter objects * @nparams: number of numa parameters (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainModificationImpact * * Change all or a subset of the numa tunables. * This function may require privileged access to the hypervisor. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetNumaParameters(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckPositiveArgGoto(nparams, error); if (virTypedParameterValidateSet(domain->conn, params, nparams) < 0) goto error; conn = domain->conn; if (conn->driver->domainSetNumaParameters) { int ret; ret = conn->driver->domainSetNumaParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetNumaParameters: * @domain: pointer to domain object * @params: pointer to numa parameter object * (return value, allocated by the caller) * @nparams: pointer to number of numa parameters * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all numa parameters. On input, @nparams gives the size of the * @params array; on output, @nparams gives how many slots were filled * with parameter information, which might be less but will not exceed * the input value. * * As a special case, calling with @params as NULL and @nparams as 0 on * input will cause @nparams on output to contain the number of parameters * supported by the hypervisor. The caller should then allocate @params * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API * again. * * See virDomainGetMemoryParameters() for an equivalent usage example. * * This function may require privileged access to the hypervisor. This function * expects the caller to allocate the @params. * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetNumaParameters(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, (nparams) ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) virCheckNonNullArgGoto(params, error); if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; conn = domain->conn; if (conn->driver->domainGetNumaParameters) { int ret; ret = conn->driver->domainGetNumaParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetBlkioParameters: * @domain: pointer to domain object * @params: pointer to blkio parameter objects * @nparams: number of blkio parameters (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainModificationImpact * * Change all or a subset of the blkio tunables. * This function may require privileged access to the hypervisor. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetBlkioParameters(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckNonNegativeArgGoto(nparams, error); if (virTypedParameterValidateSet(conn, params, nparams) < 0) goto error; if (conn->driver->domainSetBlkioParameters) { int ret; ret = conn->driver->domainSetBlkioParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetBlkioParameters: * @domain: pointer to domain object * @params: pointer to blkio parameter object * (return value, allocated by the caller) * @nparams: pointer to number of blkio parameters; input and output * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all blkio parameters. On input, @nparams gives the size of the * @params array; on output, @nparams gives how many slots were filled * with parameter information, which might be less but will not exceed * the input value. * * As a special case, calling with @params as NULL and @nparams as 0 on * input will cause @nparams on output to contain the number of parameters * supported by the hypervisor. The caller should then allocate @params * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API * again. * * See virDomainGetMemoryParameters() for an equivalent usage example. * * This function may require privileged access to the hypervisor. This function * expects the caller to allocate the @params. * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetBlkioParameters(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, (nparams) ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) virCheckNonNullArgGoto(params, error); if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); conn = domain->conn; if (conn->driver->domainGetBlkioParameters) { int ret; ret = conn->driver->domainGetBlkioParameters(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetInfo: * @domain: a domain object * @info: pointer to a virDomainInfo structure allocated by the user * * Extract information about a domain. Note that if the connection * used to get the domain is limited only a partial set of the information * can be extracted. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "info=%p", info); virResetLastError(); if (info) memset(info, 0, sizeof(*info)); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(info, error); conn = domain->conn; if (conn->driver->domainGetInfo) { int ret; ret = conn->driver->domainGetInfo(domain, info); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetState: * @domain: a domain object * @state: returned state of the domain (one of virDomainState) * @reason: returned reason which led to @state (one of virDomain*Reason * corresponding to the current state); it is allowed to be NULL * @flags: extra flags; not used yet, so callers should always pass 0 * * Extract domain state. Each state can be accompanied with a reason (if known) * which led to the state. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetState(virDomainPtr domain, int *state, int *reason, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "state=%p, reason=%p, flags=%x", state, reason, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(state, error); conn = domain->conn; if (conn->driver->domainGetState) { int ret; ret = conn->driver->domainGetState(domain, state, reason, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetControlInfo: * @domain: a domain object * @info: pointer to a virDomainControlInfo structure allocated by the user * @flags: extra flags; not used yet, so callers should always pass 0 * * Extract details about current state of control interface to a domain. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetControlInfo(virDomainPtr domain, virDomainControlInfoPtr info, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "info=%p, flags=%x", info, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(info, error); conn = domain->conn; if (conn->driver->domainGetControlInfo) { int ret; ret = conn->driver->domainGetControlInfo(domain, info, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetXMLDesc: * @domain: a domain object * @flags: bitwise-OR of virDomainXMLFlags * * Provide an XML description of the domain. The description may be reused * later to relaunch the domain with virDomainCreateXML(). * * No security-sensitive data will be included unless @flags contains * VIR_DOMAIN_XML_SECURE; this flag is rejected on read-only * connections. If @flags includes VIR_DOMAIN_XML_INACTIVE, then the * XML represents the configuration that will be used on the next boot * of a persistent domain; otherwise, the configuration represents the * currently running domain. If @flags contains * VIR_DOMAIN_XML_UPDATE_CPU, then the portion of the domain XML * describing CPU capabilities is modified to match actual * capabilities of the host. * * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of error. * the caller must free() the returned value. */ char * virDomainGetXMLDesc(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; if ((conn->flags & VIR_CONNECT_RO) && (flags & (VIR_DOMAIN_XML_SECURE | VIR_DOMAIN_XML_MIGRATABLE))) { virReportError(VIR_ERR_OPERATION_DENIED, "%s", _("virDomainGetXMLDesc with secure flag")); goto error; } if (conn->driver->domainGetXMLDesc) { char *ret; ret = conn->driver->domainGetXMLDesc(domain, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virConnectDomainXMLFromNative: * @conn: a connection object * @nativeFormat: configuration format importing from * @nativeConfig: the configuration data to import * @flags: extra flags; not used yet, so callers should always pass 0 * * Reads native configuration data describing a domain, and * generates libvirt domain XML. The format of the native * data is hypervisor dependent. * * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of error. * the caller must free() the returned value. */ char * virConnectDomainXMLFromNative(virConnectPtr conn, const char *nativeFormat, const char *nativeConfig, unsigned int flags) { VIR_DEBUG("conn=%p, format=%s, config=%s, flags=%x", conn, NULLSTR(nativeFormat), NULLSTR(nativeConfig), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(nativeFormat, error); virCheckNonNullArgGoto(nativeConfig, error); if (conn->driver->connectDomainXMLFromNative) { char *ret; ret = conn->driver->connectDomainXMLFromNative(conn, nativeFormat, nativeConfig, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virConnectDomainXMLToNative: * @conn: a connection object * @nativeFormat: configuration format exporting to * @domainXml: the domain configuration to export * @flags: extra flags; not used yet, so callers should always pass 0 * * Reads a domain XML configuration document, and generates * a native configuration file describing the domain. * The format of the native data is hypervisor dependent. * * Returns a 0 terminated UTF-8 encoded native config datafile, or NULL in case of error. * the caller must free() the returned value. */ char * virConnectDomainXMLToNative(virConnectPtr conn, const char *nativeFormat, const char *domainXml, unsigned int flags) { VIR_DEBUG("conn=%p, format=%s, xml=%s, flags=%x", conn, NULLSTR(nativeFormat), NULLSTR(domainXml), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(nativeFormat, error); virCheckNonNullArgGoto(domainXml, error); if (conn->driver->connectDomainXMLToNative) { char *ret; ret = conn->driver->connectDomainXMLToNative(conn, nativeFormat, domainXml, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /* * Sequence v1: * * Dst: Prepare * - Get ready to accept incoming VM * - Generate optional cookie to pass to src * * Src: Perform * - Start migration and wait for send completion * - Kill off VM if successful, resume if failed * * Dst: Finish * - Wait for recv completion and check status * - Kill off VM if unsuccessful * */ static virDomainPtr virDomainMigrateVersion1(virDomainPtr domain, virConnectPtr dconn, unsigned long flags, const char *dname, const char *uri, unsigned long bandwidth) { virDomainPtr ddomain = NULL; char *uri_out = NULL; char *cookie = NULL; int cookielen = 0, ret; virDomainInfo info; unsigned int destflags; VIR_DOMAIN_DEBUG(domain, "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu", dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth); ret = virDomainGetInfo(domain, &info); if (ret == 0 && info.state == VIR_DOMAIN_PAUSED) flags |= VIR_MIGRATE_PAUSED; destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR | VIR_MIGRATE_AUTO_CONVERGE); /* Prepare the migration. * * The destination host may return a cookie, or leave cookie as * NULL. * * The destination host MUST set uri_out if uri_in is NULL. * * If uri_in is non-NULL, then the destination host may modify * the URI by setting uri_out. If it does not wish to modify * the URI, it should leave uri_out as NULL. */ if (dconn->driver->domainMigratePrepare (dconn, &cookie, &cookielen, uri, &uri_out, destflags, dname, bandwidth) == -1) goto done; if (uri == NULL && uri_out == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("domainMigratePrepare did not set uri")); goto done; } if (uri_out) uri = uri_out; /* Did domainMigratePrepare change URI? */ /* Perform the migration. The driver isn't supposed to return * until the migration is complete. */ if (domain->conn->driver->domainMigratePerform (domain, cookie, cookielen, uri, flags, dname, bandwidth) == -1) goto done; /* Get the destination domain and return it or error. * 'domain' no longer actually exists at this point * (or so we hope), but we still use the object in memory * in order to get the name. */ dname = dname ? dname : domain->name; if (dconn->driver->domainMigrateFinish) ddomain = dconn->driver->domainMigrateFinish (dconn, dname, cookie, cookielen, uri, destflags); else ddomain = virDomainLookupByName(dconn, dname); done: VIR_FREE(uri_out); VIR_FREE(cookie); return ddomain; } /* * Sequence v2: * * Src: DumpXML * - Generate XML to pass to dst * * Dst: Prepare * - Get ready to accept incoming VM * - Generate optional cookie to pass to src * * Src: Perform * - Start migration and wait for send completion * - Kill off VM if successful, resume if failed * * Dst: Finish * - Wait for recv completion and check status * - Kill off VM if unsuccessful * */ static virDomainPtr virDomainMigrateVersion2(virDomainPtr domain, virConnectPtr dconn, unsigned long flags, const char *dname, const char *uri, unsigned long bandwidth) { virDomainPtr ddomain = NULL; char *uri_out = NULL; char *cookie = NULL; char *dom_xml = NULL; int cookielen = 0, ret; virDomainInfo info; virErrorPtr orig_err = NULL; unsigned int getxml_flags = 0; int cancelled; unsigned long destflags; VIR_DOMAIN_DEBUG(domain, "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu", dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth); /* Prepare the migration. * * The destination host may return a cookie, or leave cookie as * NULL. * * The destination host MUST set uri_out if uri_in is NULL. * * If uri_in is non-NULL, then the destination host may modify * the URI by setting uri_out. If it does not wish to modify * the URI, it should leave uri_out as NULL. */ /* In version 2 of the protocol, the prepare step is slightly * different. We fetch the domain XML of the source domain * and pass it to Prepare2. */ if (!domain->conn->driver->domainGetXMLDesc) { virReportUnsupportedError(); return NULL; } if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_XML_MIGRATABLE)) { getxml_flags |= VIR_DOMAIN_XML_MIGRATABLE; } else { getxml_flags |= VIR_DOMAIN_XML_SECURE | VIR_DOMAIN_XML_UPDATE_CPU; } dom_xml = domain->conn->driver->domainGetXMLDesc(domain, getxml_flags); if (!dom_xml) return NULL; ret = virDomainGetInfo(domain, &info); if (ret == 0 && info.state == VIR_DOMAIN_PAUSED) flags |= VIR_MIGRATE_PAUSED; destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR | VIR_MIGRATE_AUTO_CONVERGE); VIR_DEBUG("Prepare2 %p flags=%lx", dconn, destflags); ret = dconn->driver->domainMigratePrepare2 (dconn, &cookie, &cookielen, uri, &uri_out, destflags, dname, bandwidth, dom_xml); VIR_FREE(dom_xml); if (ret == -1) goto done; if (uri == NULL && uri_out == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("domainMigratePrepare2 did not set uri")); cancelled = 1; /* Make sure Finish doesn't overwrite the error */ orig_err = virSaveLastError(); goto finish; } if (uri_out) uri = uri_out; /* Did domainMigratePrepare2 change URI? */ /* Perform the migration. The driver isn't supposed to return * until the migration is complete. */ VIR_DEBUG("Perform %p", domain->conn); ret = domain->conn->driver->domainMigratePerform (domain, cookie, cookielen, uri, flags, dname, bandwidth); /* Perform failed. Make sure Finish doesn't overwrite the error */ if (ret < 0) orig_err = virSaveLastError(); /* If Perform returns < 0, then we need to cancel the VM * startup on the destination */ cancelled = ret < 0 ? 1 : 0; finish: /* In version 2 of the migration protocol, we pass the * status code from the sender to the destination host, * so it can do any cleanup if the migration failed. */ dname = dname ? dname : domain->name; VIR_DEBUG("Finish2 %p ret=%d", dconn, ret); ddomain = dconn->driver->domainMigrateFinish2 (dconn, dname, cookie, cookielen, uri, destflags, cancelled); if (cancelled && ddomain) VIR_ERROR(_("finish step ignored that migration was cancelled")); done: if (orig_err) { virSetError(orig_err); virFreeError(orig_err); } VIR_FREE(uri_out); VIR_FREE(cookie); return ddomain; } /* * Sequence v3: * * Src: Begin * - Generate XML to pass to dst * - Generate optional cookie to pass to dst * * Dst: Prepare * - Get ready to accept incoming VM * - Generate optional cookie to pass to src * * Src: Perform * - Start migration and wait for send completion * - Generate optional cookie to pass to dst * * Dst: Finish * - Wait for recv completion and check status * - Kill off VM if failed, resume if success * - Generate optional cookie to pass to src * * Src: Confirm * - Kill off VM if success, resume if failed * * If useParams is true, params and nparams contain migration parameters and * we know it's safe to call the API which supports extensible parameters. * Otherwise, we have to use xmlin, dname, uri, and bandwidth and pass them * to the old-style APIs. */ static virDomainPtr virDomainMigrateVersion3Full(virDomainPtr domain, virConnectPtr dconn, const char *xmlin, const char *dname, const char *uri, unsigned long long bandwidth, virTypedParameterPtr params, int nparams, bool useParams, unsigned int flags) { virDomainPtr ddomain = NULL; char *uri_out = NULL; char *cookiein = NULL; char *cookieout = NULL; char *dom_xml = NULL; int cookieinlen = 0; int cookieoutlen = 0; int ret; virDomainInfo info; virErrorPtr orig_err = NULL; int cancelled = 1; unsigned long protection = 0; bool notify_source = true; unsigned int destflags; int state; virTypedParameterPtr tmp; VIR_DOMAIN_DEBUG(domain, "dconn=%p, xmlin=%s, dname=%s, uri=%s, bandwidth=%llu, " "params=%p, nparams=%d, useParams=%d, flags=%x", dconn, NULLSTR(xmlin), NULLSTR(dname), NULLSTR(uri), bandwidth, params, nparams, useParams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); if ((!useParams && (!domain->conn->driver->domainMigrateBegin3 || !domain->conn->driver->domainMigratePerform3 || !domain->conn->driver->domainMigrateConfirm3 || !dconn->driver->domainMigratePrepare3 || !dconn->driver->domainMigrateFinish3)) || (useParams && (!domain->conn->driver->domainMigrateBegin3Params || !domain->conn->driver->domainMigratePerform3Params || !domain->conn->driver->domainMigrateConfirm3Params || !dconn->driver->domainMigratePrepare3Params || !dconn->driver->domainMigrateFinish3Params))) { virReportUnsupportedError(); return NULL; } if (virTypedParamsCopy(&tmp, params, nparams) < 0) return NULL; params = tmp; if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION)) protection = VIR_MIGRATE_CHANGE_PROTECTION; VIR_DEBUG("Begin3 %p", domain->conn); if (useParams) { dom_xml = domain->conn->driver->domainMigrateBegin3Params (domain, params, nparams, &cookieout, &cookieoutlen, flags | protection); } else { dom_xml = domain->conn->driver->domainMigrateBegin3 (domain, xmlin, &cookieout, &cookieoutlen, flags | protection, dname, bandwidth); } if (!dom_xml) goto done; if (useParams) { /* If source is new enough to support extensible migration parameters, * it's certainly new enough to support virDomainGetState. */ ret = virDomainGetState(domain, &state, NULL, 0); } else { ret = virDomainGetInfo(domain, &info); state = info.state; } if (ret == 0 && state == VIR_DOMAIN_PAUSED) flags |= VIR_MIGRATE_PAUSED; destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR | VIR_MIGRATE_AUTO_CONVERGE); VIR_DEBUG("Prepare3 %p flags=%x", dconn, destflags); cookiein = cookieout; cookieinlen = cookieoutlen; cookieout = NULL; cookieoutlen = 0; if (useParams) { if (virTypedParamsReplaceString(&params, &nparams, VIR_MIGRATE_PARAM_DEST_XML, dom_xml) < 0) goto done; ret = dconn->driver->domainMigratePrepare3Params (dconn, params, nparams, cookiein, cookieinlen, &cookieout, &cookieoutlen, &uri_out, destflags); } else { ret = dconn->driver->domainMigratePrepare3 (dconn, cookiein, cookieinlen, &cookieout, &cookieoutlen, uri, &uri_out, destflags, dname, bandwidth, dom_xml); } if (ret == -1) { if (protection) { /* Begin already started a migration job so we need to cancel it by * calling Confirm while making sure it doesn't overwrite the error */ orig_err = virSaveLastError(); goto confirm; } else { goto done; } } /* Did domainMigratePrepare3 change URI? */ if (uri_out) { uri = uri_out; if (useParams && virTypedParamsReplaceString(&params, &nparams, VIR_MIGRATE_PARAM_URI, uri_out) < 0) { cancelled = 1; orig_err = virSaveLastError(); goto finish; } } else if (!uri && virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_URI, &uri) <= 0) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("domainMigratePrepare3 did not set uri")); cancelled = 1; orig_err = virSaveLastError(); goto finish; } if (flags & VIR_MIGRATE_OFFLINE) { VIR_DEBUG("Offline migration, skipping Perform phase"); VIR_FREE(cookieout); cookieoutlen = 0; cancelled = 0; goto finish; } /* Perform the migration. The driver isn't supposed to return * until the migration is complete. The src VM should remain * running, but in paused state until the destination can * confirm migration completion. */ VIR_DEBUG("Perform3 %p uri=%s", domain->conn, uri); VIR_FREE(cookiein); cookiein = cookieout; cookieinlen = cookieoutlen; cookieout = NULL; cookieoutlen = 0; /* dconnuri not relevant in non-P2P modes, so left NULL here */ if (useParams) { ret = domain->conn->driver->domainMigratePerform3Params (domain, NULL, params, nparams, cookiein, cookieinlen, &cookieout, &cookieoutlen, flags | protection); } else { ret = domain->conn->driver->domainMigratePerform3 (domain, NULL, cookiein, cookieinlen, &cookieout, &cookieoutlen, NULL, uri, flags | protection, dname, bandwidth); } /* Perform failed. Make sure Finish doesn't overwrite the error */ if (ret < 0) { orig_err = virSaveLastError(); /* Perform failed so we don't need to call confirm to let source know * about the failure. */ notify_source = false; } /* If Perform returns < 0, then we need to cancel the VM * startup on the destination */ cancelled = ret < 0 ? 1 : 0; finish: /* * The status code from the source is passed to the destination. * The dest can cleanup if the source indicated it failed to * send all migration data. Returns NULL for ddomain if * the dest was unable to complete migration. */ VIR_DEBUG("Finish3 %p ret=%d", dconn, ret); VIR_FREE(cookiein); cookiein = cookieout; cookieinlen = cookieoutlen; cookieout = NULL; cookieoutlen = 0; if (useParams) { if (virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_NAME, NULL) <= 0 && virTypedParamsReplaceString(&params, &nparams, VIR_MIGRATE_PARAM_DEST_NAME, domain->name) < 0) { ddomain = NULL; } else { ddomain = dconn->driver->domainMigrateFinish3Params (dconn, params, nparams, cookiein, cookieinlen, &cookieout, &cookieoutlen, destflags, cancelled); } } else { dname = dname ? dname : domain->name; ddomain = dconn->driver->domainMigrateFinish3 (dconn, dname, cookiein, cookieinlen, &cookieout, &cookieoutlen, NULL, uri, destflags, cancelled); } if (cancelled) { if (ddomain) { VIR_ERROR(_("finish step ignored that migration was cancelled")); } else { /* If Finish reported a useful error, use it instead of the * original "migration unexpectedly failed" error. * * This is ugly but we can't do better with the APIs we have. We * only replace the error if Finish was called with cancelled == 1 * and reported a real error (old libvirt would report an error * from RPC instead of MIGRATE_FINISH_OK), which only happens when * the domain died on destination. To further reduce a possibility * of false positives we also check that Perform returned * VIR_ERR_OPERATION_FAILED. */ if (orig_err && orig_err->domain == VIR_FROM_QEMU && orig_err->code == VIR_ERR_OPERATION_FAILED) { virErrorPtr err = virGetLastError(); if (err && err->domain == VIR_FROM_QEMU && err->code != VIR_ERR_MIGRATE_FINISH_OK) { virFreeError(orig_err); orig_err = NULL; } } } } /* If ddomain is NULL, then we were unable to start * the guest on the target, and must restart on the * source. There is a small chance that the ddomain * is NULL due to an RPC failure, in which case * ddomain could in fact be running on the dest. * The lock manager plugins should take care of * safety in this scenario. */ cancelled = ddomain == NULL ? 1 : 0; /* If finish3 set an error, and we don't have an earlier * one we need to preserve it in case confirm3 overwrites */ if (!orig_err) orig_err = virSaveLastError(); confirm: /* * If cancelled, then src VM will be restarted, else it will be killed. * Don't do this if migration failed on source and thus it was already * cancelled there. */ if (notify_source) { VIR_DEBUG("Confirm3 %p ret=%d domain=%p", domain->conn, ret, domain); VIR_FREE(cookiein); cookiein = cookieout; cookieinlen = cookieoutlen; cookieout = NULL; cookieoutlen = 0; if (useParams) { ret = domain->conn->driver->domainMigrateConfirm3Params (domain, params, nparams, cookiein, cookieinlen, flags | protection, cancelled); } else { ret = domain->conn->driver->domainMigrateConfirm3 (domain, cookiein, cookieinlen, flags | protection, cancelled); } /* If Confirm3 returns -1, there's nothing more we can * do, but fortunately worst case is that there is a * domain left in 'paused' state on source. */ if (ret < 0) { VIR_WARN("Guest %s probably left in 'paused' state on source", domain->name); } } done: if (orig_err) { virSetError(orig_err); virFreeError(orig_err); } VIR_FREE(dom_xml); VIR_FREE(uri_out); VIR_FREE(cookiein); VIR_FREE(cookieout); virTypedParamsFree(params, nparams); return ddomain; } static virDomainPtr virDomainMigrateVersion3(virDomainPtr domain, virConnectPtr dconn, const char *xmlin, unsigned long flags, const char *dname, const char *uri, unsigned long bandwidth) { return virDomainMigrateVersion3Full(domain, dconn, xmlin, dname, uri, bandwidth, NULL, 0, false, flags); } static virDomainPtr virDomainMigrateVersion3Params(virDomainPtr domain, virConnectPtr dconn, virTypedParameterPtr params, int nparams, unsigned int flags) { return virDomainMigrateVersion3Full(domain, dconn, NULL, NULL, NULL, 0, params, nparams, true, flags); } static int virDomainMigrateCheckNotLocal(const char *dconnuri) { virURIPtr tempuri = NULL; int ret = -1; if (!(tempuri = virURIParse(dconnuri))) goto cleanup; if (!tempuri->server || STRPREFIX(tempuri->server, "localhost")) { virReportInvalidArg(dconnuri, "%s", _("Attempt to migrate guest to the same host")); goto cleanup; } ret = 0; cleanup: virURIFree(tempuri); return ret; } static int virDomainMigrateUnmanagedProto2(virDomainPtr domain, const char *dconnuri, virTypedParameterPtr params, int nparams, unsigned int flags) { /* uri parameter is added for direct case */ const char *compatParams[] = { VIR_MIGRATE_PARAM_DEST_NAME, VIR_MIGRATE_PARAM_BANDWIDTH, VIR_MIGRATE_PARAM_URI }; const char *uri = NULL; const char *miguri = NULL; const char *dname = NULL; unsigned long long bandwidth = 0; if (!virTypedParamsCheck(params, nparams, compatParams, ARRAY_CARDINALITY(compatParams))) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Some parameters are not supported by migration " "protocol 2")); return -1; } if (virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_URI, &miguri) < 0 || virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_NAME, &dname) < 0 || virTypedParamsGetULLong(params, nparams, VIR_MIGRATE_PARAM_BANDWIDTH, &bandwidth) < 0) { return -1; } if (flags & VIR_MIGRATE_PEER2PEER) { if (miguri) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("Unable to override peer2peer migration URI")); return -1; } uri = dconnuri; } else { uri = miguri; } return domain->conn->driver->domainMigratePerform (domain, NULL, 0, uri, flags, dname, bandwidth); } static int virDomainMigrateUnmanagedProto3(virDomainPtr domain, const char *dconnuri, virTypedParameterPtr params, int nparams, unsigned int flags) { const char *compatParams[] = { VIR_MIGRATE_PARAM_URI, VIR_MIGRATE_PARAM_DEST_NAME, VIR_MIGRATE_PARAM_DEST_XML, VIR_MIGRATE_PARAM_BANDWIDTH }; const char *miguri = NULL; const char *dname = NULL; const char *xmlin = NULL; unsigned long long bandwidth = 0; if (!virTypedParamsCheck(params, nparams, compatParams, ARRAY_CARDINALITY(compatParams))) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Some parameters are not supported by migration " "protocol 3")); return -1; } if (virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_URI, &miguri) < 0 || virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_NAME, &dname) < 0 || virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_XML, &xmlin) < 0 || virTypedParamsGetULLong(params, nparams, VIR_MIGRATE_PARAM_BANDWIDTH, &bandwidth) < 0) { return -1; } return domain->conn->driver->domainMigratePerform3 (domain, xmlin, NULL, 0, NULL, NULL, dconnuri, miguri, flags, dname, bandwidth); } /* * In normal migration, the libvirt client co-ordinates communication * between the 2 libvirtd instances on source & dest hosts. * * This function encapsulates 2 alternatives to the above case. * * 1. peer-2-peer migration, the libvirt client only talks to the source * libvirtd instance. The source libvirtd then opens its own * connection to the destination and co-ordinates migration itself. * * 2. direct migration, where there is no requirement for a libvirtd instance * on the dest host. Eg, XenD can talk direct to XenD, so libvirtd on dest * does not need to be involved at all, or even running. */ static int virDomainMigrateUnmanagedParams(virDomainPtr domain, const char *dconnuri, virTypedParameterPtr params, int nparams, unsigned int flags) { VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, params=%p, nparams=%d, flags=%x", NULLSTR(dconnuri), params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); if ((flags & VIR_MIGRATE_PEER2PEER) && virDomainMigrateCheckNotLocal(dconnuri) < 0) return -1; if ((flags & VIR_MIGRATE_PEER2PEER) && VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_PARAMS)) { VIR_DEBUG("Using migration protocol 3 with extensible parameters"); if (!domain->conn->driver->domainMigratePerform3Params) { virReportUnsupportedError(); return -1; } return domain->conn->driver->domainMigratePerform3Params (domain, dconnuri, params, nparams, NULL, 0, NULL, NULL, flags); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V3)) { VIR_DEBUG("Using migration protocol 3"); if (!domain->conn->driver->domainMigratePerform3) { virReportUnsupportedError(); return -1; } return virDomainMigrateUnmanagedProto3(domain, dconnuri, params, nparams, flags); } else { VIR_DEBUG("Using migration protocol 2"); if (!domain->conn->driver->domainMigratePerform) { virReportUnsupportedError(); return -1; } return virDomainMigrateUnmanagedProto2(domain, dconnuri, params, nparams, flags); } } static int virDomainMigrateUnmanaged(virDomainPtr domain, const char *xmlin, unsigned int flags, const char *dname, const char *dconnuri, const char *miguri, unsigned long long bandwidth) { int ret = -1; virTypedParameterPtr params = NULL; int nparams = 0; int maxparams = 0; if (miguri && virTypedParamsAddString(&params, &nparams, &maxparams, VIR_MIGRATE_PARAM_URI, miguri) < 0) goto cleanup; if (dname && virTypedParamsAddString(&params, &nparams, &maxparams, VIR_MIGRATE_PARAM_DEST_NAME, dname) < 0) goto cleanup; if (xmlin && virTypedParamsAddString(&params, &nparams, &maxparams, VIR_MIGRATE_PARAM_DEST_XML, xmlin) < 0) goto cleanup; if (virTypedParamsAddULLong(&params, &nparams, &maxparams, VIR_MIGRATE_PARAM_BANDWIDTH, bandwidth) < 0) goto cleanup; ret = virDomainMigrateUnmanagedParams(domain, dconnuri, params, nparams, flags); cleanup: virTypedParamsFree(params, nparams); return ret; } /** * virDomainMigrate: * @domain: a domain object * @dconn: destination host (a connection object) * @flags: bitwise-OR of virDomainMigrateFlags * @dname: (optional) rename domain to this at destination * @uri: (optional) dest hostname/URI as seen from the source host * @bandwidth: (optional) specify migration bandwidth limit in MiB/s * * Migrate the domain object from its current host to the destination * host given by dconn (a connection to the destination host). * * Flags may be one of more of the following: * VIR_MIGRATE_LIVE Do not pause the VM during migration * VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts * VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel * VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain * on the destination host. * VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the * domain on the source host. * VIR_MIGRATE_PAUSED Leave the domain suspended on the remote side. * VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full * disk copy * VIR_MIGRATE_NON_SHARED_INC Migration with non-shared storage with * incremental disk copy * VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration * changes during the migration process (set * automatically when supported). * VIR_MIGRATE_UNSAFE Force migration even if it is considered unsafe. * VIR_MIGRATE_OFFLINE Migrate offline * * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set. * Applications using the VIR_MIGRATE_PEER2PEER flag will probably * prefer to invoke virDomainMigrateToURI, avoiding the need to * open connection to the destination host themselves. * * If a hypervisor supports renaming domains during migration, * then you may set the dname parameter to the new name (otherwise * it keeps the same name). If this is not supported by the * hypervisor, dname must be NULL or else you will get an error. * * If the VIR_MIGRATE_PEER2PEER flag is set, the uri parameter * must be a valid libvirt connection URI, by which the source * libvirt driver can connect to the destination libvirt. If * omitted, the dconn connection object will be queried for its * current URI. * * If the VIR_MIGRATE_PEER2PEER flag is NOT set, the URI parameter * takes a hypervisor specific format. The hypervisor capabilities * XML includes details of the support URI schemes. If omitted * the dconn will be asked for a default URI. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * * In either case it is typically only necessary to specify a * URI if the destination host has multiple interfaces and a * specific interface is required to transmit migration data. * * The maximum bandwidth (in MiB/s) that will be used to do migration * can be specified with the bandwidth parameter. If set to 0, * libvirt will choose a suitable default. Some hypervisors do * not support this feature and will return an error if bandwidth * is not 0. * * To see which features are supported by the current hypervisor, * see virConnectGetCapabilities, /capabilities/host/migration_features. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * virDomainFree should be used to free the resources after the * returned domain object is no longer needed. * * Returns the new domain object if the migration was successful, * or NULL in case of error. Note that the new domain object * exists in the scope of the destination connection (dconn). */ virDomainPtr virDomainMigrate(virDomainPtr domain, virConnectPtr dconn, unsigned long flags, const char *dname, const char *uri, unsigned long bandwidth) { virDomainPtr ddomain = NULL; VIR_DOMAIN_DEBUG(domain, "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu", dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, NULL); virCheckReadOnlyGoto(domain->conn->flags, error); /* Now checkout the destination */ virCheckConnectGoto(dconn, error); virCheckReadOnlyGoto(dconn->flags, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_NON_SHARED_DISK, VIR_MIGRATE_NON_SHARED_INC, error); if (flags & VIR_MIGRATE_OFFLINE) { if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the source host")); goto error; } if (!VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the destination host")); goto error; } } if (flags & VIR_MIGRATE_PEER2PEER) { if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_P2P)) { char *dstURI = NULL; if (uri == NULL) { dstURI = virConnectGetURI(dconn); if (!dstURI) return NULL; } VIR_DEBUG("Using peer2peer migration"); if (virDomainMigrateUnmanaged(domain, NULL, flags, dname, uri ? uri : dstURI, NULL, bandwidth) < 0) { VIR_FREE(dstURI); goto error; } VIR_FREE(dstURI); ddomain = virDomainLookupByName(dconn, dname ? dname : domain->name); } else { /* This driver does not support peer to peer migration */ virReportUnsupportedError(); goto error; } } else { /* Change protection requires support only on source side, and * is only needed in v3 migration, which automatically re-adds * the flag for just the source side. We mask it out for * non-peer2peer to allow migration from newer source to an * older destination that rejects the flag. */ if (flags & VIR_MIGRATE_CHANGE_PROTECTION && !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("cannot enforce change protection")); goto error; } flags &= ~VIR_MIGRATE_CHANGE_PROTECTION; if (flags & VIR_MIGRATE_TUNNELLED) { virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("cannot perform tunnelled migration without using peer2peer flag")); goto error; } /* Check that migration is supported by both drivers. */ if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V3) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V3)) { VIR_DEBUG("Using migration protocol 3"); ddomain = virDomainMigrateVersion3(domain, dconn, NULL, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V2) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V2)) { VIR_DEBUG("Using migration protocol 2"); ddomain = virDomainMigrateVersion2(domain, dconn, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V1) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V1)) { VIR_DEBUG("Using migration protocol 1"); ddomain = virDomainMigrateVersion1(domain, dconn, flags, dname, uri, bandwidth); } else { /* This driver does not support any migration method */ virReportUnsupportedError(); goto error; } } if (ddomain == NULL) goto error; return ddomain; error: virDispatchError(domain->conn); return NULL; } /** * virDomainMigrate2: * @domain: a domain object * @dconn: destination host (a connection object) * @flags: bitwise-OR of virDomainMigrateFlags * @dxml: (optional) XML config for launching guest on target * @dname: (optional) rename domain to this at destination * @uri: (optional) dest hostname/URI as seen from the source host * @bandwidth: (optional) specify migration bandwidth limit in MiB/s * * Migrate the domain object from its current host to the destination * host given by dconn (a connection to the destination host). * * Flags may be one of more of the following: * VIR_MIGRATE_LIVE Do not pause the VM during migration * VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts * VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel * VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain * on the destination host. * VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the * domain on the source host. * VIR_MIGRATE_PAUSED Leave the domain suspended on the remote side. * VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full * disk copy * VIR_MIGRATE_NON_SHARED_INC Migration with non-shared storage with * incremental disk copy * VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration * changes during the migration process (set * automatically when supported). * VIR_MIGRATE_UNSAFE Force migration even if it is considered unsafe. * VIR_MIGRATE_OFFLINE Migrate offline * * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set. * Applications using the VIR_MIGRATE_PEER2PEER flag will probably * prefer to invoke virDomainMigrateToURI, avoiding the need to * open connection to the destination host themselves. * * If a hypervisor supports renaming domains during migration, * then you may set the dname parameter to the new name (otherwise * it keeps the same name). If this is not supported by the * hypervisor, dname must be NULL or else you will get an error. * * If the VIR_MIGRATE_PEER2PEER flag is set, the uri parameter * must be a valid libvirt connection URI, by which the source * libvirt driver can connect to the destination libvirt. If * omitted, the dconn connection object will be queried for its * current URI. * * If the VIR_MIGRATE_PEER2PEER flag is NOT set, the URI parameter * takes a hypervisor specific format. The hypervisor capabilities * XML includes details of the support URI schemes. If omitted * the dconn will be asked for a default URI. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * * In either case it is typically only necessary to specify a * URI if the destination host has multiple interfaces and a * specific interface is required to transmit migration data. * * The maximum bandwidth (in MiB/s) that will be used to do migration * can be specified with the bandwidth parameter. If set to 0, * libvirt will choose a suitable default. Some hypervisors do * not support this feature and will return an error if bandwidth * is not 0. * * To see which features are supported by the current hypervisor, * see virConnectGetCapabilities, /capabilities/host/migration_features. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * If the hypervisor supports it, @dxml can be used to alter * host-specific portions of the domain XML that will be used on * the destination. For example, it is possible to alter the * backing filename that is associated with a disk device, in order * to account for naming differences between source and destination * in accessing the underlying storage. The migration will fail * if @dxml would cause any guest-visible changes. Pass NULL * if no changes are needed to the XML between source and destination. * @dxml cannot be used to rename the domain during migration (use * @dname for that purpose). Domain name in @dxml must match the * original domain name. * * virDomainFree should be used to free the resources after the * returned domain object is no longer needed. * * Returns the new domain object if the migration was successful, * or NULL in case of error. Note that the new domain object * exists in the scope of the destination connection (dconn). */ virDomainPtr virDomainMigrate2(virDomainPtr domain, virConnectPtr dconn, const char *dxml, unsigned long flags, const char *dname, const char *uri, unsigned long bandwidth) { virDomainPtr ddomain = NULL; VIR_DOMAIN_DEBUG(domain, "dconn=%p, flags=%lx, dname=%s, uri=%s, bandwidth=%lu", dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, NULL); virCheckReadOnlyGoto(domain->conn->flags, error); /* Now checkout the destination */ virCheckConnectGoto(dconn, error); virCheckReadOnlyGoto(dconn->flags, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_NON_SHARED_DISK, VIR_MIGRATE_NON_SHARED_INC, error); if (flags & VIR_MIGRATE_OFFLINE) { if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the source host")); goto error; } if (!VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the destination host")); goto error; } } if (flags & VIR_MIGRATE_PEER2PEER) { if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_P2P)) { char *dstURI = virConnectGetURI(dconn); if (!dstURI) return NULL; VIR_DEBUG("Using peer2peer migration"); if (virDomainMigrateUnmanaged(domain, dxml, flags, dname, dstURI, uri, bandwidth) < 0) { VIR_FREE(dstURI); goto error; } VIR_FREE(dstURI); ddomain = virDomainLookupByName(dconn, dname ? dname : domain->name); } else { /* This driver does not support peer to peer migration */ virReportUnsupportedError(); goto error; } } else { /* Change protection requires support only on source side, and * is only needed in v3 migration, which automatically re-adds * the flag for just the source side. We mask it out for * non-peer2peer to allow migration from newer source to an * older destination that rejects the flag. */ if (flags & VIR_MIGRATE_CHANGE_PROTECTION && !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("cannot enforce change protection")); goto error; } flags &= ~VIR_MIGRATE_CHANGE_PROTECTION; if (flags & VIR_MIGRATE_TUNNELLED) { virReportError(VIR_ERR_OPERATION_INVALID, "%s", _("cannot perform tunnelled migration without using peer2peer flag")); goto error; } /* Check that migration is supported by both drivers. */ if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V3) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V3)) { VIR_DEBUG("Using migration protocol 3"); ddomain = virDomainMigrateVersion3(domain, dconn, dxml, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V2) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V2)) { VIR_DEBUG("Using migration protocol 2"); if (dxml) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Unable to change target guest XML during migration")); goto error; } ddomain = virDomainMigrateVersion2(domain, dconn, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V1) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V1)) { VIR_DEBUG("Using migration protocol 1"); if (dxml) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Unable to change target guest XML during migration")); goto error; } ddomain = virDomainMigrateVersion1(domain, dconn, flags, dname, uri, bandwidth); } else { /* This driver does not support any migration method */ virReportUnsupportedError(); goto error; } } if (ddomain == NULL) goto error; return ddomain; error: virDispatchError(domain->conn); return NULL; } /** * virDomainMigrate3: * @domain: a domain object * @dconn: destination host (a connection object) * @params: (optional) migration parameters * @nparams: (optional) number of migration parameters in @params * @flags: bitwise-OR of virDomainMigrateFlags * * Migrate the domain object from its current host to the destination host * given by dconn (a connection to the destination host). * * See virDomainMigrateFlags documentation for description of individual flags. * * VIR_MIGRATE_TUNNELLED and VIR_MIGRATE_PEER2PEER are not supported by this * API, use virDomainMigrateToURI3 instead. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * virDomainFree should be used to free the resources after the * returned domain object is no longer needed. * * Returns the new domain object if the migration was successful, * or NULL in case of error. Note that the new domain object * exists in the scope of the destination connection (dconn). */ virDomainPtr virDomainMigrate3(virDomainPtr domain, virConnectPtr dconn, virTypedParameterPtr params, unsigned int nparams, unsigned int flags) { virDomainPtr ddomain = NULL; const char *compatParams[] = { VIR_MIGRATE_PARAM_URI, VIR_MIGRATE_PARAM_DEST_NAME, VIR_MIGRATE_PARAM_DEST_XML, VIR_MIGRATE_PARAM_BANDWIDTH }; const char *uri = NULL; const char *dname = NULL; const char *dxml = NULL; unsigned long long bandwidth = 0; VIR_DOMAIN_DEBUG(domain, "dconn=%p, params=%p, nparms=%u flags=%x", dconn, params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, NULL); virCheckReadOnlyGoto(domain->conn->flags, error); /* Now checkout the destination */ virCheckReadOnlyGoto(dconn->flags, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_NON_SHARED_DISK, VIR_MIGRATE_NON_SHARED_INC, error); if (flags & VIR_MIGRATE_PEER2PEER) { virReportInvalidArg(flags, "%s", _("use virDomainMigrateToURI3 for peer-to-peer " "migration")); goto error; } if (flags & VIR_MIGRATE_TUNNELLED) { virReportInvalidArg(flags, "%s", _("cannot perform tunnelled migration " "without using peer2peer flag")); goto error; } if (flags & VIR_MIGRATE_OFFLINE) { if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the source host")); goto error; } if (!VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the destination host")); goto error; } } /* Change protection requires support only on source side, and * is only needed in v3 migration, which automatically re-adds * the flag for just the source side. We mask it out to allow * migration from newer source to an older destination that * rejects the flag. */ if (flags & VIR_MIGRATE_CHANGE_PROTECTION && !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("cannot enforce change protection")); goto error; } flags &= ~VIR_MIGRATE_CHANGE_PROTECTION; /* Prefer extensible API but fall back to older migration APIs if params * only contains parameters which were supported by the older API. */ if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_PARAMS) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_PARAMS)) { VIR_DEBUG("Using migration protocol 3 with extensible parameters"); ddomain = virDomainMigrateVersion3Params(domain, dconn, params, nparams, flags); goto done; } if (!virTypedParamsCheck(params, nparams, compatParams, ARRAY_CARDINALITY(compatParams))) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Migration APIs with extensible parameters are not " "supported but extended parameters were passed")); goto error; } if (virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_URI, &uri) < 0 || virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_NAME, &dname) < 0 || virTypedParamsGetString(params, nparams, VIR_MIGRATE_PARAM_DEST_XML, &dxml) < 0 || virTypedParamsGetULLong(params, nparams, VIR_MIGRATE_PARAM_BANDWIDTH, &bandwidth) < 0) { goto error; } if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V3) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V3)) { VIR_DEBUG("Using migration protocol 3"); ddomain = virDomainMigrateVersion3(domain, dconn, dxml, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V2) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V2)) { VIR_DEBUG("Using migration protocol 2"); if (dxml) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Unable to change target guest XML during " "migration")); goto error; } ddomain = virDomainMigrateVersion2(domain, dconn, flags, dname, uri, bandwidth); } else if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_V1) && VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn, VIR_DRV_FEATURE_MIGRATION_V1)) { VIR_DEBUG("Using migration protocol 1"); if (dxml) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("Unable to change target guest XML during " "migration")); goto error; } ddomain = virDomainMigrateVersion1(domain, dconn, flags, dname, uri, bandwidth); } else { /* This driver does not support any migration method */ virReportUnsupportedError(); goto error; } done: if (ddomain == NULL) goto error; return ddomain; error: virDispatchError(domain->conn); return NULL; } static int virDomainMigrateUnmanagedCheckCompat(virDomainPtr domain, unsigned int flags) { VIR_EXCLUSIVE_FLAGS_RET(VIR_MIGRATE_NON_SHARED_DISK, VIR_MIGRATE_NON_SHARED_INC, -1); if (flags & VIR_MIGRATE_OFFLINE && !VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_OFFLINE)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("offline migration is not supported by " "the source host")); return -1; } if (flags & VIR_MIGRATE_PEER2PEER) { if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_P2P)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("p2p migration is not supported by " "the source host")); return -1; } } else { if (!VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_MIGRATION_DIRECT)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("direct migration is not supported by " "the source host")); return -1; } } return 0; } /** * virDomainMigrateToURI: * @domain: a domain object * @duri: mandatory URI for the destination host * @flags: bitwise-OR of virDomainMigrateFlags * @dname: (optional) rename domain to this at destination * @bandwidth: (optional) specify migration bandwidth limit in MiB/s * * Migrate the domain object from its current host to the destination * host given by duri. * * Flags may be one of more of the following: * VIR_MIGRATE_LIVE Do not pause the VM during migration * VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts * VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel * VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain * on the destination host. * VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the * domain on the source host. * VIR_MIGRATE_PAUSED Leave the domain suspended on the remote side. * VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full * disk copy * VIR_MIGRATE_NON_SHARED_INC Migration with non-shared storage with * incremental disk copy * VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration * changes during the migration process (set * automatically when supported). * VIR_MIGRATE_UNSAFE Force migration even if it is considered unsafe. * VIR_MIGRATE_OFFLINE Migrate offline * * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag. * If the VIR_MIGRATE_PEER2PEER flag is NOT set, the duri parameter * takes a hypervisor specific format. The uri_transports element of the * hypervisor capabilities XML includes details of the supported URI * schemes. Not all hypervisors will support this mode of migration, so * if the VIR_MIGRATE_PEER2PEER flag is not set, then it may be necessary * to use the alternative virDomainMigrate API providing and explicit * virConnectPtr for the destination host. * * If the VIR_MIGRATE_PEER2PEER flag IS set, the duri parameter * must be a valid libvirt connection URI, by which the source * libvirt driver can connect to the destination libvirt. * * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * * If a hypervisor supports renaming domains during migration, * the dname parameter specifies the new name for the domain. * Setting dname to NULL keeps the domain name the same. If domain * renaming is not supported by the hypervisor, dname must be NULL or * else an error will be returned. * * The maximum bandwidth (in MiB/s) that will be used to do migration * can be specified with the bandwidth parameter. If set to 0, * libvirt will choose a suitable default. Some hypervisors do * not support this feature and will return an error if bandwidth * is not 0. * * To see which features are supported by the current hypervisor, * see virConnectGetCapabilities, /capabilities/host/migration_features. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * Returns 0 if the migration succeeded, -1 upon error. */ int virDomainMigrateToURI(virDomainPtr domain, const char *duri, unsigned long flags, const char *dname, unsigned long bandwidth) { const char *dconnuri = NULL; const char *miguri = NULL; VIR_DOMAIN_DEBUG(domain, "duri=%p, flags=%lx, dname=%s, bandwidth=%lu", NULLSTR(duri), flags, NULLSTR(dname), bandwidth); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); virCheckNonNullArgGoto(duri, error); if (virDomainMigrateUnmanagedCheckCompat(domain, flags) < 0) goto error; if (flags & VIR_MIGRATE_PEER2PEER) dconnuri = duri; else miguri = duri; if (virDomainMigrateUnmanaged(domain, NULL, flags, dname, dconnuri, miguri, bandwidth) < 0) goto error; return 0; error: virDispatchError(domain->conn); return -1; } /** * virDomainMigrateToURI2: * @domain: a domain object * @dconnuri: (optional) URI for target libvirtd if @flags includes VIR_MIGRATE_PEER2PEER * @miguri: (optional) URI for invoking the migration, not if @flags includs VIR_MIGRATE_TUNNELLED * @dxml: (optional) XML config for launching guest on target * @flags: bitwise-OR of virDomainMigrateFlags * @dname: (optional) rename domain to this at destination * @bandwidth: (optional) specify migration bandwidth limit in MiB/s * * Migrate the domain object from its current host to the destination * host given by duri. * * Flags may be one of more of the following: * VIR_MIGRATE_LIVE Do not pause the VM during migration * VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts * VIR_MIGRATE_TUNNELLED Tunnel migration data over the libvirt RPC channel * VIR_MIGRATE_PERSIST_DEST If the migration is successful, persist the domain * on the destination host. * VIR_MIGRATE_UNDEFINE_SOURCE If the migration is successful, undefine the * domain on the source host. * VIR_MIGRATE_PAUSED Leave the domain suspended on the remote side. * VIR_MIGRATE_NON_SHARED_DISK Migration with non-shared storage with full * disk copy * VIR_MIGRATE_NON_SHARED_INC Migration with non-shared storage with * incremental disk copy * VIR_MIGRATE_CHANGE_PROTECTION Protect against domain configuration * changes during the migration process (set * automatically when supported). * VIR_MIGRATE_UNSAFE Force migration even if it is considered unsafe. * VIR_MIGRATE_OFFLINE Migrate offline * * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag. * * If the VIR_MIGRATE_PEER2PEER flag is set, the @dconnuri parameter * must be a valid libvirt connection URI, by which the source * libvirt driver can connect to the destination libvirt. If the * VIR_MIGRATE_PEER2PEER flag is NOT set, then @dconnuri must be * NULL. * * If the VIR_MIGRATE_TUNNELLED flag is NOT set, then the @miguri * parameter allows specification of a URI to use to initiate the * VM migration. It takes a hypervisor specific format. The uri_transports * element of the hypervisor capabilities XML includes details of the * supported URI schemes. * * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * As of 1.2.11 disks of some types ('file' and 'volume') are * precreated automatically, if there's a pool defined on the * destination for the disk path. * * If a hypervisor supports changing the configuration of the guest * during migration, the @dxml parameter specifies the new config * for the guest. The configuration must include an identical set * of virtual devices, to ensure a stable guest ABI across migration. * Only parameters related to host side configuration can be * changed in the XML. Hypervisors will validate this and refuse to * allow migration if the provided XML would cause a change in the * guest ABI, * * If a hypervisor supports renaming domains during migration, * the dname parameter specifies the new name for the domain. * Setting dname to NULL keeps the domain name the same. If domain * renaming is not supported by the hypervisor, dname must be NULL or * else an error will be returned. * * The maximum bandwidth (in MiB/s) that will be used to do migration * can be specified with the bandwidth parameter. If set to 0, * libvirt will choose a suitable default. Some hypervisors do * not support this feature and will return an error if bandwidth * is not 0. * * To see which features are supported by the current hypervisor, * see virConnectGetCapabilities, /capabilities/host/migration_features. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * Returns 0 if the migration succeeded, -1 upon error. */ int virDomainMigrateToURI2(virDomainPtr domain, const char *dconnuri, const char *miguri, const char *dxml, unsigned long flags, const char *dname, unsigned long bandwidth) { VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, miguri=%s, dxml=%s, " "flags=%lx, dname=%s, bandwidth=%lu", NULLSTR(dconnuri), NULLSTR(miguri), NULLSTR(dxml), flags, NULLSTR(dname), bandwidth); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); if (virDomainMigrateUnmanagedCheckCompat(domain, flags) < 0) goto error; if (flags & VIR_MIGRATE_PEER2PEER) virCheckNonNullArgGoto(dconnuri, error); else dconnuri = NULL; if (virDomainMigrateUnmanaged(domain, dxml, flags, dname, dconnuri, miguri, bandwidth) < 0) goto error; return 0; error: virDispatchError(domain->conn); return -1; } /** * virDomainMigrateToURI3: * @domain: a domain object * @dconnuri: (optional) URI for target libvirtd if @flags includes VIR_MIGRATE_PEER2PEER * @params: (optional) migration parameters * @nparams: (optional) number of migration parameters in @params * @flags: bitwise-OR of virDomainMigrateFlags * * Migrate the domain object from its current host to the destination host * given by URI. * * See virDomainMigrateFlags documentation for description of individual flags. * * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag. * * If the VIR_MIGRATE_PEER2PEER flag is set, the @dconnuri parameter must be a * valid libvirt connection URI, by which the source libvirt daemon can connect * to the destination libvirt. * * If the VIR_MIGRATE_PEER2PEER flag is NOT set, then @dconnuri must be NULL * and VIR_MIGRATE_PARAM_URI migration parameter must be filled in with * hypervisor specific URI used to initiate the migration. This is called * "direct" migration. * * VIR_MIGRATE_TUNNELLED requires that VIR_MIGRATE_PEER2PEER be set. * * If you want to copy non-shared storage within migration you * can use either VIR_MIGRATE_NON_SHARED_DISK or * VIR_MIGRATE_NON_SHARED_INC as they are mutually exclusive. * * There are many limitations on migration imposed by the underlying * technology - for example it may not be possible to migrate between * different processors even with the same architecture, or between * different types of hypervisor. * * Returns 0 if the migration succeeded, -1 upon error. */ int virDomainMigrateToURI3(virDomainPtr domain, const char *dconnuri, virTypedParameterPtr params, unsigned int nparams, unsigned int flags) { VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, params=%p, nparms=%u flags=%x", NULLSTR(dconnuri), params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); /* First checkout the source */ virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); if (virDomainMigrateUnmanagedCheckCompat(domain, flags) < 0) goto error; if (flags & VIR_MIGRATE_PEER2PEER) virCheckNonNullArgGoto(dconnuri, error); else dconnuri = NULL; if (virDomainMigrateUnmanagedParams(domain, dconnuri, params, nparams, flags) < 0) goto error; return 0; error: virDispatchError(domain->conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepare(virConnectPtr dconn, char **cookie, int *cookielen, const char *uri_in, char **uri_out, unsigned long flags, const char *dname, unsigned long bandwidth) { VIR_DEBUG("dconn=%p, cookie=%p, cookielen=%p, uri_in=%s, uri_out=%p, " "flags=%lx, dname=%s, bandwidth=%lu", dconn, cookie, cookielen, NULLSTR(uri_in), uri_out, flags, NULLSTR(dname), bandwidth); virResetLastError(); virCheckConnectReturn(dconn, -1); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigratePrepare) { int ret; ret = dconn->driver->domainMigratePrepare(dconn, cookie, cookielen, uri_in, uri_out, flags, dname, bandwidth); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePerform(virDomainPtr domain, const char *cookie, int cookielen, const char *uri, unsigned long flags, const char *dname, unsigned long bandwidth) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cookie=%p, cookielen=%d, uri=%s, flags=%lx, " "dname=%s, bandwidth=%lu", cookie, cookielen, uri, flags, NULLSTR(dname), bandwidth); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigratePerform) { int ret; ret = conn->driver->domainMigratePerform(domain, cookie, cookielen, uri, flags, dname, bandwidth); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ virDomainPtr virDomainMigrateFinish(virConnectPtr dconn, const char *dname, const char *cookie, int cookielen, const char *uri, unsigned long flags) { VIR_DEBUG("dconn=%p, dname=%s, cookie=%p, cookielen=%d, uri=%s, " "flags=%lx", dconn, NULLSTR(dname), cookie, cookielen, NULLSTR(uri), flags); virResetLastError(); virCheckConnectReturn(dconn, NULL); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigrateFinish) { virDomainPtr ret; ret = dconn->driver->domainMigrateFinish(dconn, dname, cookie, cookielen, uri, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepare2(virConnectPtr dconn, char **cookie, int *cookielen, const char *uri_in, char **uri_out, unsigned long flags, const char *dname, unsigned long bandwidth, const char *dom_xml) { VIR_DEBUG("dconn=%p, cookie=%p, cookielen=%p, uri_in=%s, uri_out=%p," "flags=%lx, dname=%s, bandwidth=%lu, dom_xml=%s", dconn, cookie, cookielen, NULLSTR(uri_in), uri_out, flags, NULLSTR(dname), bandwidth, NULLSTR(dom_xml)); virResetLastError(); virCheckConnectReturn(dconn, -1); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigratePrepare2) { int ret; ret = dconn->driver->domainMigratePrepare2(dconn, cookie, cookielen, uri_in, uri_out, flags, dname, bandwidth, dom_xml); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ virDomainPtr virDomainMigrateFinish2(virConnectPtr dconn, const char *dname, const char *cookie, int cookielen, const char *uri, unsigned long flags, int retcode) { VIR_DEBUG("dconn=%p, dname=%s, cookie=%p, cookielen=%d, uri=%s, " "flags=%lx, retcode=%d", dconn, NULLSTR(dname), cookie, cookielen, NULLSTR(uri), flags, retcode); virResetLastError(); virCheckConnectReturn(dconn, NULL); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigrateFinish2) { virDomainPtr ret; ret = dconn->driver->domainMigrateFinish2(dconn, dname, cookie, cookielen, uri, flags, retcode); if (!ret && !retcode) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepareTunnel(virConnectPtr conn, virStreamPtr st, unsigned long flags, const char *dname, unsigned long bandwidth, const char *dom_xml) { VIR_DEBUG("conn=%p, stream=%p, flags=%lx, dname=%s, " "bandwidth=%lu, dom_xml=%s", conn, st, flags, NULLSTR(dname), bandwidth, NULLSTR(dom_xml)); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); if (conn != st->conn) { virReportInvalidArg(conn, "%s", _("conn must match stream connection")); goto error; } if (conn->driver->domainMigratePrepareTunnel) { int rv = conn->driver->domainMigratePrepareTunnel(conn, st, flags, dname, bandwidth, dom_xml); if (rv < 0) goto error; return rv; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ char * virDomainMigrateBegin3(virDomainPtr domain, const char *xmlin, char **cookieout, int *cookieoutlen, unsigned long flags, const char *dname, unsigned long bandwidth) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xmlin=%s cookieout=%p, cookieoutlen=%p, " "flags=%lx, dname=%s, bandwidth=%lu", NULLSTR(xmlin), cookieout, cookieoutlen, flags, NULLSTR(dname), bandwidth); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateBegin3) { char *xml; xml = conn->driver->domainMigrateBegin3(domain, xmlin, cookieout, cookieoutlen, flags, dname, bandwidth); VIR_DEBUG("xml %s", NULLSTR(xml)); if (!xml) goto error; return xml; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepare3(virConnectPtr dconn, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, const char *uri_in, char **uri_out, unsigned long flags, const char *dname, unsigned long bandwidth, const char *dom_xml) { VIR_DEBUG("dconn=%p, cookiein=%p, cookieinlen=%d, cookieout=%p, " "cookieoutlen=%p, uri_in=%s, uri_out=%p, flags=%lx, dname=%s, " "bandwidth=%lu, dom_xml=%s", dconn, cookiein, cookieinlen, cookieout, cookieoutlen, NULLSTR(uri_in), uri_out, flags, NULLSTR(dname), bandwidth, NULLSTR(dom_xml)); virResetLastError(); virCheckConnectReturn(dconn, -1); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigratePrepare3) { int ret; ret = dconn->driver->domainMigratePrepare3(dconn, cookiein, cookieinlen, cookieout, cookieoutlen, uri_in, uri_out, flags, dname, bandwidth, dom_xml); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepareTunnel3(virConnectPtr conn, virStreamPtr st, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned long flags, const char *dname, unsigned long bandwidth, const char *dom_xml) { VIR_DEBUG("conn=%p, stream=%p, cookiein=%p, cookieinlen=%d, cookieout=%p, " "cookieoutlen=%p, flags=%lx, dname=%s, bandwidth=%lu, " "dom_xml=%s", conn, st, cookiein, cookieinlen, cookieout, cookieoutlen, flags, NULLSTR(dname), bandwidth, NULLSTR(dom_xml)); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); if (conn != st->conn) { virReportInvalidArg(conn, "%s", _("conn must match stream connection")); goto error; } if (conn->driver->domainMigratePrepareTunnel3) { int rv = conn->driver->domainMigratePrepareTunnel3(conn, st, cookiein, cookieinlen, cookieout, cookieoutlen, flags, dname, bandwidth, dom_xml); if (rv < 0) goto error; return rv; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePerform3(virDomainPtr domain, const char *xmlin, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, const char *dconnuri, const char *uri, unsigned long flags, const char *dname, unsigned long bandwidth) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xmlin=%s cookiein=%p, cookieinlen=%d, " "cookieout=%p, cookieoutlen=%p, dconnuri=%s, " "uri=%s, flags=%lx, dname=%s, bandwidth=%lu", NULLSTR(xmlin), cookiein, cookieinlen, cookieout, cookieoutlen, NULLSTR(dconnuri), NULLSTR(uri), flags, NULLSTR(dname), bandwidth); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigratePerform3) { int ret; ret = conn->driver->domainMigratePerform3(domain, xmlin, cookiein, cookieinlen, cookieout, cookieoutlen, dconnuri, uri, flags, dname, bandwidth); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ virDomainPtr virDomainMigrateFinish3(virConnectPtr dconn, const char *dname, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, const char *dconnuri, const char *uri, unsigned long flags, int cancelled) { VIR_DEBUG("dconn=%p, dname=%s, cookiein=%p, cookieinlen=%d, cookieout=%p," "cookieoutlen=%p, dconnuri=%s, uri=%s, flags=%lx, retcode=%d", dconn, NULLSTR(dname), cookiein, cookieinlen, cookieout, cookieoutlen, NULLSTR(dconnuri), NULLSTR(uri), flags, cancelled); virResetLastError(); virCheckConnectReturn(dconn, NULL); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigrateFinish3) { virDomainPtr ret; ret = dconn->driver->domainMigrateFinish3(dconn, dname, cookiein, cookieinlen, cookieout, cookieoutlen, dconnuri, uri, flags, cancelled); if (!ret && !cancelled) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigrateConfirm3(virDomainPtr domain, const char *cookiein, int cookieinlen, unsigned long flags, int cancelled) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cookiein=%p, cookieinlen=%d, flags=%lx, cancelled=%d", cookiein, cookieinlen, flags, cancelled); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateConfirm3) { int ret; ret = conn->driver->domainMigrateConfirm3(domain, cookiein, cookieinlen, flags, cancelled); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ char * virDomainMigrateBegin3Params(virDomainPtr domain, virTypedParameterPtr params, int nparams, char **cookieout, int *cookieoutlen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, " "cookieout=%p, cookieoutlen=%p, flags=%x", params, nparams, cookieout, cookieoutlen, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateBegin3Params) { char *xml; xml = conn->driver->domainMigrateBegin3Params(domain, params, nparams, cookieout, cookieoutlen, flags); VIR_DEBUG("xml %s", NULLSTR(xml)); if (!xml) goto error; return xml; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepare3Params(virConnectPtr dconn, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, char **uri_out, unsigned int flags) { VIR_DEBUG("dconn=%p, params=%p, nparams=%d, cookiein=%p, cookieinlen=%d, " "cookieout=%p, cookieoutlen=%p, uri_out=%p, flags=%x", dconn, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, uri_out, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckConnectReturn(dconn, -1); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigratePrepare3Params) { int ret; ret = dconn->driver->domainMigratePrepare3Params(dconn, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, uri_out, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePrepareTunnel3Params(virConnectPtr conn, virStreamPtr st, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned int flags) { VIR_DEBUG("conn=%p, stream=%p, params=%p, nparams=%d, cookiein=%p, " "cookieinlen=%d, cookieout=%p, cookieoutlen=%p, flags=%x", conn, st, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckReadOnlyGoto(conn->flags, error); if (conn != st->conn) { virReportInvalidArg(conn, "%s", _("conn must match stream connection")); goto error; } if (conn->driver->domainMigratePrepareTunnel3Params) { int rv; rv = conn->driver->domainMigratePrepareTunnel3Params( conn, st, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags); if (rv < 0) goto error; return rv; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigratePerform3Params(virDomainPtr domain, const char *dconnuri, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, params=%p, nparams=%d, cookiein=%p, " "cookieinlen=%d, cookieout=%p, cookieoutlen=%p, flags=%x", NULLSTR(dconnuri), params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigratePerform3Params) { int ret; ret = conn->driver->domainMigratePerform3Params( domain, dconnuri, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ virDomainPtr virDomainMigrateFinish3Params(virConnectPtr dconn, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned int flags, int cancelled) { VIR_DEBUG("dconn=%p, params=%p, nparams=%d, cookiein=%p, cookieinlen=%d, " "cookieout=%p, cookieoutlen=%p, flags=%x, cancelled=%d", dconn, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags, cancelled); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckConnectReturn(dconn, NULL); virCheckReadOnlyGoto(dconn->flags, error); if (dconn->driver->domainMigrateFinish3Params) { virDomainPtr ret; ret = dconn->driver->domainMigrateFinish3Params( dconn, params, nparams, cookiein, cookieinlen, cookieout, cookieoutlen, flags, cancelled); if (!ret && !cancelled) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dconn); return NULL; } /* * Not for public use. This function is part of the internal * implementation of migration in the remote case. */ int virDomainMigrateConfirm3Params(virDomainPtr domain, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, unsigned int flags, int cancelled) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, cookiein=%p, " "cookieinlen=%d, flags=%x, cancelled=%d", params, nparams, cookiein, cookieinlen, flags, cancelled); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateConfirm3Params) { int ret; ret = conn->driver->domainMigrateConfirm3Params( domain, params, nparams, cookiein, cookieinlen, flags, cancelled); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetSchedulerType: * @domain: pointer to domain object * @nparams: pointer to number of scheduler parameters, can be NULL * (return value) * * Get the scheduler type and the number of scheduler parameters. * * Returns NULL in case of error. The caller must free the returned string. */ char * virDomainGetSchedulerType(virDomainPtr domain, int *nparams) { virConnectPtr conn; char *schedtype; VIR_DOMAIN_DEBUG(domain, "nparams=%p", nparams); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; if (conn->driver->domainGetSchedulerType) { schedtype = conn->driver->domainGetSchedulerType(domain, nparams); if (!schedtype) goto error; return schedtype; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virDomainGetSchedulerParameters: * @domain: pointer to domain object * @params: pointer to scheduler parameter objects * (return value) * @nparams: pointer to number of scheduler parameter objects * (this value should generally be as large as the returned value * nparams of virDomainGetSchedulerType()); input and output * * Get all scheduler parameters. On input, @nparams gives the size of the * @params array; on output, @nparams gives how many slots were filled * with parameter information, which might be less but will not exceed * the input value. @nparams cannot be 0. * * It is hypervisor specific whether this returns the live or * persistent state; for more control, use * virDomainGetSchedulerParametersFlags(). * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetSchedulerParameters(virDomainPtr domain, virTypedParameterPtr params, int *nparams) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%p", params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(params, error); virCheckNonNullArgGoto(nparams, error); virCheckPositiveArgGoto(*nparams, error); conn = domain->conn; if (conn->driver->domainGetSchedulerParameters) { int ret; ret = conn->driver->domainGetSchedulerParameters(domain, params, nparams); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetSchedulerParametersFlags: * @domain: pointer to domain object * @params: pointer to scheduler parameter object * (return value) * @nparams: pointer to number of scheduler parameter * (this value should be same than the returned value * nparams of virDomainGetSchedulerType()); input and output * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all scheduler parameters. On input, @nparams gives the size of the * @params array; on output, @nparams gives how many slots were filled * with parameter information, which might be less but will not exceed * the input value. @nparams cannot be 0. * * The value of @flags can be exactly VIR_DOMAIN_AFFECT_CURRENT, * VIR_DOMAIN_AFFECT_LIVE, or VIR_DOMAIN_AFFECT_CONFIG. * * Here is a sample code snippet: * * char *ret = virDomainGetSchedulerType(dom, &nparams); * if (ret && nparams != 0) { * if ((params = malloc(sizeof(*params) * nparams)) == NULL) * goto error; * memset(params, 0, sizeof(*params) * nparams); * if (virDomainGetSchedulerParametersFlags(dom, params, &nparams, 0)) * goto error; * } * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetSchedulerParametersFlags(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%p, flags=%x", params, nparams, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(params, error); virCheckNonNullArgGoto(nparams, error); virCheckPositiveArgGoto(*nparams, error); if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); conn = domain->conn; if (conn->driver->domainGetSchedulerParametersFlags) { int ret; ret = conn->driver->domainGetSchedulerParametersFlags(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetSchedulerParameters: * @domain: pointer to domain object * @params: pointer to scheduler parameter objects * @nparams: number of scheduler parameter objects * (this value can be the same or less than the returned value * nparams of virDomainGetSchedulerType) * * Change all or a subset or the scheduler parameters. It is * hypervisor-specific whether this sets live, persistent, or both * settings; for more control, use * virDomainSetSchedulerParametersFlags. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetSchedulerParameters(virDomainPtr domain, virTypedParameterPtr params, int nparams) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d", params, nparams); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckNonNegativeArgGoto(nparams, error); if (virTypedParameterValidateSet(conn, params, nparams) < 0) goto error; if (conn->driver->domainSetSchedulerParameters) { int ret; ret = conn->driver->domainSetSchedulerParameters(domain, params, nparams); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetSchedulerParametersFlags: * @domain: pointer to domain object * @params: pointer to scheduler parameter objects * @nparams: number of scheduler parameter objects * (this value can be the same or less than the returned value * nparams of virDomainGetSchedulerType) * @flags: bitwise-OR of virDomainModificationImpact * * Change a subset or all scheduler parameters. The value of @flags * should be either VIR_DOMAIN_AFFECT_CURRENT, or a bitwise-or of * values from VIR_DOMAIN_AFFECT_LIVE and * VIR_DOMAIN_AFFECT_CURRENT, although hypervisors vary in which * flags are supported. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetSchedulerParametersFlags(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=%x", params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckNonNegativeArgGoto(nparams, error); if (virTypedParameterValidateSet(conn, params, nparams) < 0) goto error; if (conn->driver->domainSetSchedulerParametersFlags) { int ret; ret = conn->driver->domainSetSchedulerParametersFlags(domain, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainBlockStats: * @dom: pointer to the domain object * @disk: path to the block device, or device shorthand * @stats: block device stats (returned) * @size: size of stats structure * * This function returns block device (disk) stats for block * devices attached to the domain. * * The @disk parameter is either the device target shorthand (the * <target dev='...'/> sub-element, such as "vda"), or (since 0.9.8) * an unambiguous source name of the block device (the <source * file='...'/> sub-element, such as "/path/to/image"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. Some drivers might also * accept the empty string for the @disk parameter, and then yield * summary stats for the entire domain. * * Domains may have more than one block device. To get stats for * each you should make multiple calls to this function. * * Individual fields within the stats structure may be returned * as -1, which indicates that the hypervisor does not support * that particular statistic. * * Returns: 0 in case of success or -1 in case of failure. */ int virDomainBlockStats(virDomainPtr dom, const char *disk, virDomainBlockStatsPtr stats, size_t size) { virConnectPtr conn; virDomainBlockStatsStruct stats2 = { -1, -1, -1, -1, -1 }; VIR_DOMAIN_DEBUG(dom, "disk=%s, stats=%p, size=%zi", disk, stats, size); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(disk, error); virCheckNonNullArgGoto(stats, error); if (size > sizeof(stats2)) { virReportInvalidArg(size, _("size must not exceed %zu"), sizeof(stats2)); goto error; } conn = dom->conn; if (conn->driver->domainBlockStats) { if (conn->driver->domainBlockStats(dom, disk, &stats2) == -1) goto error; memcpy(stats, &stats2, size); return 0; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockStatsFlags: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @params: pointer to block stats parameter object * (return value, allocated by the caller) * @nparams: pointer to number of block stats; input and output * @flags: bitwise-OR of virTypedParameterFlags * * This function is to get block stats parameters for block * devices attached to the domain. * * The @disk parameter is either the device target shorthand (the * <target dev='...'/> sub-element, such as "vda"), or (since 0.9.8) * an unambiguous source name of the block device (the <source * file='...'/> sub-element, such as "/path/to/image"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. Some drivers might also * accept the empty string for the @disk parameter, and then yield * summary stats for the entire domain. * * Domains may have more than one block device. To get stats for * each you should make multiple calls to this function. * * On input, @nparams gives the size of the @params array; on output, * @nparams gives how many slots were filled with parameter * information, which might be less but will not exceed the input * value. * * As a special case, calling with @params as NULL and @nparams as 0 on * input will cause @nparams on output to contain the number of parameters * supported by the hypervisor. (Note that block devices of different types * might support different parameters, so it might be necessary to compute * @nparams for each block device). The caller should then allocate @params * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API * again. See virDomainGetMemoryParameters() for more details. * * Returns -1 in case of error, 0 in case of success. */ int virDomainBlockStatsFlags(virDomainPtr dom, const char *disk, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=%x", disk, params, nparams ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(disk, error); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) virCheckNonNullArgGoto(params, error); if (VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; conn = dom->conn; if (conn->driver->domainBlockStatsFlags) { int ret; ret = conn->driver->domainBlockStatsFlags(dom, disk, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainInterfaceStats: * @dom: pointer to the domain object * @path: path to the interface * @stats: network interface stats (returned) * @size: size of stats structure * * This function returns network interface stats for interfaces * attached to the domain. * * The path parameter is the name of the network interface. * * Domains may have more than one network interface. To get stats for * each you should make multiple calls to this function. * * Individual fields within the stats structure may be returned * as -1, which indicates that the hypervisor does not support * that particular statistic. * * Returns: 0 in case of success or -1 in case of failure. */ int virDomainInterfaceStats(virDomainPtr dom, const char *path, virDomainInterfaceStatsPtr stats, size_t size) { virConnectPtr conn; virDomainInterfaceStatsStruct stats2 = { -1, -1, -1, -1, -1, -1, -1, -1 }; VIR_DOMAIN_DEBUG(dom, "path=%s, stats=%p, size=%zi", path, stats, size); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(path, error); virCheckNonNullArgGoto(stats, error); if (size > sizeof(stats2)) { virReportInvalidArg(size, _("size must not exceed %zu"), sizeof(stats2)); goto error; } conn = dom->conn; if (conn->driver->domainInterfaceStats) { if (conn->driver->domainInterfaceStats(dom, path, &stats2) == -1) goto error; memcpy(stats, &stats2, size); return 0; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainSetInterfaceParameters: * @domain: pointer to domain object * @device: the interface name or mac address * @params: pointer to interface parameter objects * @nparams: number of interface parameter (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainModificationImpact * * Change a subset or all parameters of interface; currently this * includes bandwidth parameters. The value of @flags should be * either VIR_DOMAIN_AFFECT_CURRENT, or a bitwise-or of values * VIR_DOMAIN_AFFECT_LIVE and VIR_DOMAIN_AFFECT_CONFIG, although * hypervisors vary in which flags are supported. * * This function may require privileged access to the hypervisor. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetInterfaceParameters(virDomainPtr domain, const char *device, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "device=%s, params=%p, nparams=%d, flags=%x", device, params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(params, error); virCheckPositiveArgGoto(nparams, error); if (virTypedParameterValidateSet(conn, params, nparams) < 0) goto error; if (conn->driver->domainSetInterfaceParameters) { int ret; ret = conn->driver->domainSetInterfaceParameters(domain, device, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetInterfaceParameters: * @domain: pointer to domain object * @device: the interface name or mac address * @params: pointer to interface parameter objects * (return value, allocated by the caller) * @nparams: pointer to number of interface parameter; input and output * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all interface parameters. On input, @nparams gives the size of * the @params array; on output, @nparams gives how many slots were * filled with parameter information, which might be less but will not * exceed the input value. * * As a special case, calling with @params as NULL and @nparams as 0 on * input will cause @nparams on output to contain the number of parameters * supported by the hypervisor. The caller should then allocate @params * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the * API again. See virDomainGetMemoryParameters() for an equivalent usage * example. * * This function may require privileged access to the hypervisor. This function * expects the caller to allocate the @params. * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetInterfaceParameters(virDomainPtr domain, const char *device, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "device=%s, params=%p, nparams=%d, flags=%x", device, params, (nparams) ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) virCheckNonNullArgGoto(params, error); if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; conn = domain->conn; if (conn->driver->domainGetInterfaceParameters) { int ret; ret = conn->driver->domainGetInterfaceParameters(domain, device, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainMemoryStats: * @dom: pointer to the domain object * @stats: nr_stats-sized array of stat structures (returned) * @nr_stats: number of memory statistics requested * @flags: extra flags; not used yet, so callers should always pass 0 * * This function provides memory statistics for the domain. * * Up to 'nr_stats' elements of 'stats' will be populated with memory statistics * from the domain. Only statistics supported by the domain, the driver, and * this version of libvirt will be returned. * * Memory Statistics: * * VIR_DOMAIN_MEMORY_STAT_SWAP_IN: * The total amount of data read from swap space (in kb). * VIR_DOMAIN_MEMORY_STAT_SWAP_OUT: * The total amount of memory written out to swap space (in kb). * VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT: * The number of page faults that required disk IO to service. * VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT: * The number of page faults serviced without disk IO. * VIR_DOMAIN_MEMORY_STAT_UNUSED: * The amount of memory which is not being used for any purpose (in kb). * VIR_DOMAIN_MEMORY_STAT_AVAILABLE: * The total amount of memory available to the domain's OS (in kb). * VIR_DOMAIN_MEMORY_STAT_ACTUAL_BALLOON: * Current balloon value (in kb). * * Returns: The number of stats provided or -1 in case of failure. */ int virDomainMemoryStats(virDomainPtr dom, virDomainMemoryStatPtr stats, unsigned int nr_stats, unsigned int flags) { virConnectPtr conn; unsigned long nr_stats_ret = 0; VIR_DOMAIN_DEBUG(dom, "stats=%p, nr_stats=%u, flags=%x", stats, nr_stats, flags); virResetLastError(); virCheckDomainReturn(dom, -1); if (!stats || nr_stats == 0) return 0; if (nr_stats > VIR_DOMAIN_MEMORY_STAT_NR) nr_stats = VIR_DOMAIN_MEMORY_STAT_NR; conn = dom->conn; if (conn->driver->domainMemoryStats) { nr_stats_ret = conn->driver->domainMemoryStats(dom, stats, nr_stats, flags); if (nr_stats_ret == -1) goto error; return nr_stats_ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockPeek: * @dom: pointer to the domain object * @disk: path to the block device, or device shorthand * @offset: offset within block device * @size: size to read * @buffer: return buffer (must be at least size bytes) * @flags: extra flags; not used yet, so callers should always pass 0 * * This function allows you to read the contents of a domain's * disk device. * * Typical uses for this are to determine if the domain has * written a Master Boot Record (indicating that the domain * has completed installation), or to try to work out the state * of the domain's filesystems. * * (Note that in the local case you might try to open the * block device or file directly, but that won't work in the * remote case, nor if you don't have sufficient permission. * Hence the need for this call). * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * 'offset' and 'size' represent an area which must lie entirely * within the device or file. 'size' may be 0 to test if the * call would succeed. * * 'buffer' is the return buffer and must be at least 'size' bytes. * * NB. The remote driver imposes a 64K byte limit on 'size'. * For your program to be able to work reliably over a remote * connection you should split large requests to <= 65536 bytes. * However, with 0.9.13 this RPC limit has been raised to 1M byte. * Starting with version 1.0.6 the RPC limit has been raised again. * Now large requests up to 16M byte are supported. * * Returns: 0 in case of success or -1 in case of failure. */ int virDomainBlockPeek(virDomainPtr dom, const char *disk, unsigned long long offset /* really 64 bits */, size_t size, void *buffer, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, offset=%lld, size=%zi, buffer=%p, flags=%x", disk, offset, size, buffer, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonEmptyStringArgGoto(disk, error); /* Allow size == 0 as an access test. */ if (size > 0) virCheckNonNullArgGoto(buffer, error); if (conn->driver->domainBlockPeek) { int ret; ret = conn->driver->domainBlockPeek(dom, disk, offset, size, buffer, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockResize: * @dom: pointer to the domain object * @disk: path to the block image, or shorthand * @size: new size of the block image, see below for unit * @flags: bitwise-OR of virDomainBlockResizeFlags * * Resize a block device of domain while the domain is running. If * @flags is 0, then @size is in kibibytes (blocks of 1024 bytes); * since 0.9.11, if @flags includes VIR_DOMAIN_BLOCK_RESIZE_BYTES, * @size is in bytes instead. @size is taken directly as the new * size. Depending on the file format, the hypervisor may round up * to the next alignment boundary. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * Note that this call may fail if the underlying virtualization hypervisor * does not support it; this call requires privileged access to the * hypervisor. * * Returns: 0 in case of success or -1 in case of failure. */ int virDomainBlockResize(virDomainPtr dom, const char *disk, unsigned long long size, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, size=%llu, flags=%x", disk, size, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (conn->driver->domainBlockResize) { int ret; ret = conn->driver->domainBlockResize(dom, disk, size, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainMemoryPeek: * @dom: pointer to the domain object * @start: start of memory to peek * @size: size of memory to peek * @buffer: return buffer (must be at least size bytes) * @flags: bitwise-OR of virDomainMemoryFlags * * This function allows you to read the contents of a domain's * memory. * * The memory which is read is controlled by the 'start', 'size' * and 'flags' parameters. * * If 'flags' is VIR_MEMORY_VIRTUAL then the 'start' and 'size' * parameters are interpreted as virtual memory addresses for * whichever task happens to be running on the domain at the * moment. Although this sounds haphazard it is in fact what * you want in order to read Linux kernel state, because it * ensures that pointers in the kernel image can be interpreted * coherently. * * 'buffer' is the return buffer and must be at least 'size' bytes. * 'size' may be 0 to test if the call would succeed. * * NB. The remote driver imposes a 64K byte limit on 'size'. * For your program to be able to work reliably over a remote * connection you should split large requests to <= 65536 bytes. * However, with 0.9.13 this RPC limit has been raised to 1M byte. * Starting with version 1.0.6 the RPC limit has been raised again. * Now large requests up to 16M byte are supported. * * Returns: 0 in case of success or -1 in case of failure. */ int virDomainMemoryPeek(virDomainPtr dom, unsigned long long start /* really 64 bits */, size_t size, void *buffer, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "start=%lld, size=%zi, buffer=%p, flags=%x", start, size, buffer, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); /* Note on access to physical memory: A VIR_MEMORY_PHYSICAL flag is * a possibility. However it isn't really useful unless the caller * can also access registers, particularly CR3 on x86 in order to * get the Page Table Directory. Since registers are different on * every architecture, that would imply another call to get the * machine registers. * * The QEMU driver handles VIR_MEMORY_VIRTUAL, mapping it * to the qemu 'memsave' command which does the virtual to physical * mapping inside qemu. * * The QEMU driver also handles VIR_MEMORY_PHYSICAL, mapping it * to the qemu 'pmemsave' command. * * At time of writing there is no Xen driver. However the Xen * hypervisor only lets you map physical pages from other domains, * and so the Xen driver would have to do the virtual to physical * mapping by chasing 2, 3 or 4-level page tables from the PTD. * There is example code in libxc (xc_translate_foreign_address) * which does this, although we cannot copy this code directly * because of incompatible licensing. */ VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MEMORY_VIRTUAL, VIR_MEMORY_PHYSICAL, error); /* Allow size == 0 as an access test. */ if (size > 0) virCheckNonNullArgGoto(buffer, error); if (conn->driver->domainMemoryPeek) { int ret; ret = conn->driver->domainMemoryPeek(dom, start, size, buffer, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetBlockInfo: * @domain: a domain object * @disk: path to the block device, or device shorthand * @info: pointer to a virDomainBlockInfo structure allocated by the user * @flags: extra flags; not used yet, so callers should always pass 0 * * Extract information about a domain's block device. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * For QEMU domains, the allocation and physical virDomainBlockInfo * values returned will generally be the same, except when using a * non raw, block backing device, such as qcow2 for an active domain. * When the persistent domain is not active, QEMU will return the * default which is the same value for allocation and physical. * * Active QEMU domains can return an allocation value which is more * representative of the currently used blocks by the device compared * to the physical size of the device. Applications can use/monitor * the allocation value with the understanding that if the domain * becomes inactive during an attempt to get the value, the default * values will be returned. Thus, the application should check * after the call for the domain being inactive if the values are * the same. Optionally, the application could be watching for a * shutdown event and then ignore any values received afterwards. * This can be an issue when a domain is being migrated and the * exact timing of the domain being made inactive and check of * the allocation value results the default being returned. For * a transient domain in the similar situation, this call will return * -1 and an error message indicating the "domain is not running". * * The following is some pseudo code illustrating the call sequence: * * ... * virDomainPtr dom; * virDomainBlockInfo info; * char *device; * ... * // Either get a list of all domains or a specific domain * // via a virDomainLookupBy*() call. * // * // It's also required to fill in the device pointer, but that's * // specific to the implementation. For the purposes of this example * // a qcow2 backed device name string would need to be provided. * ... * // If the following call is made on a persistent domain with a * // qcow2 block backed block device, then it's possible the returned * // allocation equals the physical value. In that case, the domain * // that may have been active prior to calling has become inactive, * // such as is the case during a domain migration. Thus once we * // get data returned, check for active domain when the values are * // the same. * if (virDomainGetBlockInfo(dom, device, &info, 0) < 0) * goto failure; * if (info.allocation == info.physical) { * // If the domain is no longer active, * // then the defaults are being returned. * if (!virDomainIsActive()) * goto ignore_return; * } * // Do something with the allocation and physical values * ... * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetBlockInfo(virDomainPtr domain, const char *disk, virDomainBlockInfoPtr info, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "info=%p, flags=%x", info, flags); virResetLastError(); if (info) memset(info, 0, sizeof(*info)); virCheckDomainReturn(domain, -1); virCheckNonEmptyStringArgGoto(disk, error); virCheckNonNullArgGoto(info, error); conn = domain->conn; if (conn->driver->domainGetBlockInfo) { int ret; ret = conn->driver->domainGetBlockInfo(domain, disk, info, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainDefineXML: * @conn: pointer to the hypervisor connection * @xml: the XML description for the domain, preferably in UTF-8 * * Define a domain, but does not start it. * This definition is persistent, until explicitly undefined with * virDomainUndefine(). A previous definition for this domain would be * overridden if it already exists. * * Some hypervisors may prevent this operation if there is a current * block copy operation on a transient domain with the same id as the * domain being defined; in that case, use virDomainBlockJobAbort() to * stop the block copy first. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns NULL in case of error, a pointer to the domain otherwise */ virDomainPtr virDomainDefineXML(virConnectPtr conn, const char *xml) { VIR_DEBUG("conn=%p, xml=%s", conn, NULLSTR(xml)); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(xml, error); if (conn->driver->domainDefineXML) { virDomainPtr ret; ret = conn->driver->domainDefineXML(conn, xml); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainDefineXMLFlags: * @conn: pointer to the hypervisor connection * @xml: the XML description for the domain, preferably in UTF-8 * @flags: bitwise OR of the virDomainDefineFlags constants * * Defines a domain, but does not start it. * This definition is persistent, until explicitly undefined with * virDomainUndefine(). A previous definition for this domain would be * overridden if it already exists. * * Some hypervisors may prevent this operation if there is a current * block copy operation on a transient domain with the same id as the * domain being defined; in that case, use virDomainBlockJobAbort() to * stop the block copy first. * * virDomainFree should be used to free the resources after the * domain object is no longer needed. * * Returns NULL in case of error, a pointer to the domain otherwise */ virDomainPtr virDomainDefineXMLFlags(virConnectPtr conn, const char *xml, unsigned int flags) { VIR_DEBUG("conn=%p, xml=%s flags=%x", conn, NULLSTR(xml), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(xml, error); if (conn->driver->domainDefineXMLFlags) { virDomainPtr ret; ret = conn->driver->domainDefineXMLFlags(conn, xml, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virDomainUndefine: * @domain: pointer to a defined domain * * Undefine a domain. If the domain is running, it's converted to * transient domain, without stopping it. If the domain is inactive, * the domain configuration is removed. * * If the domain has a managed save image (see * virDomainHasManagedSaveImage()), or if it is inactive and has any * snapshot metadata (see virDomainSnapshotNum()), then the undefine will * fail. See virDomainUndefineFlags() for more control. * * Returns 0 in case of success, -1 in case of error */ int virDomainUndefine(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainUndefine) { int ret; ret = conn->driver->domainUndefine(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainUndefineFlags: * @domain: pointer to a defined domain * @flags: bitwise-OR of supported virDomainUndefineFlagsValues * * Undefine a domain. If the domain is running, it's converted to * transient domain, without stopping it. If the domain is inactive, * the domain configuration is removed. * * If the domain has a managed save image (see virDomainHasManagedSaveImage()), * then including VIR_DOMAIN_UNDEFINE_MANAGED_SAVE in @flags will also remove * that file, and omitting the flag will cause the undefine process to fail. * * If the domain is inactive and has any snapshot metadata (see * virDomainSnapshotNum()), then including * VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA in @flags will also remove * that metadata. Omitting the flag will cause the undefine of an * inactive domain to fail. Active snapshots will retain snapshot * metadata until the (now-transient) domain halts, regardless of * whether this flag is present. On hypervisors where snapshots do * not use libvirt metadata, this flag has no effect. * * If the domain has any nvram specified, then including * VIR_DOMAIN_UNDEFINE_NVRAM will also remove that file, and omitting the flag * will cause the undefine process to fail. * * Returns 0 in case of success, -1 in case of error */ int virDomainUndefineFlags(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainUndefineFlags) { int ret; ret = conn->driver->domainUndefineFlags(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virConnectNumOfDefinedDomains: * @conn: pointer to the hypervisor connection * * Provides the number of defined but inactive domains. * * Returns the number of domain found or -1 in case of error */ int virConnectNumOfDefinedDomains(virConnectPtr conn) { VIR_DEBUG("conn=%p", conn); virResetLastError(); virCheckConnectReturn(conn, -1); if (conn->driver->connectNumOfDefinedDomains) { int ret; ret = conn->driver->connectNumOfDefinedDomains(conn); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectListDefinedDomains: * @conn: pointer to the hypervisor connection * @names: pointer to an array to store the names * @maxnames: size of the array * * list the defined but inactive domains, stores the pointers to the names * in @names * * For active domains, see virConnectListDomains(). For more control over * the results, see virConnectListAllDomains(). * * Returns the number of names provided in the array or -1 in case of error. * Note that this command is inherently racy; a domain can be defined between * a call to virConnectNumOfDefinedDomains() and this call; you are only * guaranteed that all currently defined domains were listed if the return * is less than @maxids. The client must call free() on each returned name. */ int virConnectListDefinedDomains(virConnectPtr conn, char **const names, int maxnames) { VIR_DEBUG("conn=%p, names=%p, maxnames=%d", conn, names, maxnames); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNullArgGoto(names, error); virCheckNonNegativeArgGoto(maxnames, error); if (conn->driver->connectListDefinedDomains) { int ret; ret = conn->driver->connectListDefinedDomains(conn, names, maxnames); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectListAllDomains: * @conn: Pointer to the hypervisor connection. * @domains: Pointer to a variable to store the array containing domain objects * or NULL if the list is not required (just returns number of guests). * @flags: bitwise-OR of virConnectListAllDomainsFlags * * Collect a possibly-filtered list of all domains, and return an allocated * array of information for each. This API solves the race inherent in * virConnectListDomains() and virConnectListDefinedDomains(). * * Normally, all domains are returned; however, @flags can be used to * filter the results for a smaller list of targeted domains. The valid * flags are divided into groups, where each group contains bits that * describe mutually exclusive attributes of a domain, and where all bits * within a group describe all possible domains. Some hypervisors might * reject explicit bits from a group where the hypervisor cannot make a * distinction (for example, not all hypervisors can tell whether domains * have snapshots). For a group supported by a given hypervisor, the * behavior when no bits of a group are set is identical to the behavior * when all bits in that group are set. When setting bits from more than * one group, it is possible to select an impossible combination (such * as an inactive transient domain), in that case a hypervisor may return * either 0 or an error. * * The first group of @flags is VIR_CONNECT_LIST_DOMAINS_ACTIVE (online * domains) and VIR_CONNECT_LIST_DOMAINS_INACTIVE (offline domains). * * The next group of @flags is VIR_CONNECT_LIST_DOMAINS_PERSISTENT (defined * domains) and VIR_CONNECT_LIST_DOMAINS_TRANSIENT (running but not defined). * * The next group of @flags covers various domain states: * VIR_CONNECT_LIST_DOMAINS_RUNNING, VIR_CONNECT_LIST_DOMAINS_PAUSED, * VIR_CONNECT_LIST_DOMAINS_SHUTOFF, and a catch-all for all other states * (such as crashed, this catch-all covers the possibility of adding new * states). * * The remaining groups cover boolean attributes commonly asked about * domains; they include VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE and * VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE, for filtering based on whether * a managed save image exists; VIR_CONNECT_LIST_DOMAINS_AUTOSTART and * VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART, for filtering based on autostart; * VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT and * VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT, for filtering based on whether * a domain has snapshots. * * Example of usage: * * virDomainPtr *domains; * size_t i; * int ret; * unsigned int flags = VIR_CONNECT_LIST_DOMAINS_RUNNING | * VIR_CONNECT_LIST_DOMAINS_PERSISTENT; * ret = virConnectListAllDomains(conn, &domains, flags); * if (ret < 0) * error(); * for (i = 0; i < ret; i++) { * do_something_with_domain(domains[i]); * //here or in a separate loop if needed * virDomainFree(domains[i]); * } * free(domains); * * Returns the number of domains found or -1 and sets domains to NULL in case of * error. On success, the array stored into @domains is guaranteed to have an * extra allocated element set to NULL but not included in the return count, to * make iteration easier. The caller is responsible for calling virDomainFree() * on each array element, then calling free() on @domains. */ int virConnectListAllDomains(virConnectPtr conn, virDomainPtr **domains, unsigned int flags) { VIR_DEBUG("conn=%p, domains=%p, flags=%x", conn, domains, flags); virResetLastError(); if (domains) *domains = NULL; virCheckConnectReturn(conn, -1); if (conn->driver->connectListAllDomains) { int ret; ret = conn->driver->connectListAllDomains(conn, domains, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainCreate: * @domain: pointer to a defined domain * * Launch a defined domain. If the call succeeds the domain moves from the * defined to the running domains pools. The domain will be paused only * if restoring from managed state created from a paused domain. For more * control, see virDomainCreateWithFlags(). * * Returns 0 in case of success, -1 in case of error */ int virDomainCreate(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainCreate) { int ret; ret = conn->driver->domainCreate(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainCreateWithFlags: * @domain: pointer to a defined domain * @flags: bitwise-OR of supported virDomainCreateFlags * * Launch a defined domain. If the call succeeds the domain moves from the * defined to the running domains pools. * * If the VIR_DOMAIN_START_PAUSED flag is set, or if the guest domain * has a managed save image that requested paused state (see * virDomainManagedSave()) the guest domain will be started, but its * CPUs will remain paused. The CPUs can later be manually started * using virDomainResume(). In all other cases, the guest domain will * be running. * * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest * domain will be automatically destroyed when the virConnectPtr * object is finally released. This will also happen if the * client application crashes / loses its connection to the * libvirtd daemon. Any domains marked for auto destroy will * block attempts at migration, save-to-file, or snapshots. * * If the VIR_DOMAIN_START_BYPASS_CACHE flag is set, and there is a * managed save file for this domain (created by virDomainManagedSave()), * then libvirt will attempt to bypass the file system cache while restoring * the file, or fail if it cannot do so for the given system; this can allow * less pressure on file system cache, but also risks slowing loads from NFS. * * If the VIR_DOMAIN_START_FORCE_BOOT flag is set, then any managed save * file for this domain is discarded, and the domain boots from scratch. * * Returns 0 in case of success, -1 in case of error */ int virDomainCreateWithFlags(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainCreateWithFlags) { int ret; ret = conn->driver->domainCreateWithFlags(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainCreateWithFiles: * @domain: pointer to a defined domain * @nfiles: number of file descriptors passed * @files: list of file descriptors passed * @flags: bitwise-OR of supported virDomainCreateFlags * * Launch a defined domain. If the call succeeds the domain moves from the * defined to the running domains pools. * * @files provides an array of file descriptors which will be * made available to the 'init' process of the guest. The file * handles exposed to the guest will be renumbered to start * from 3 (ie immediately following stderr). This is only * supported for guests which use container based virtualization * technology. * * If the VIR_DOMAIN_START_PAUSED flag is set, or if the guest domain * has a managed save image that requested paused state (see * virDomainManagedSave()) the guest domain will be started, but its * CPUs will remain paused. The CPUs can later be manually started * using virDomainResume(). In all other cases, the guest domain will * be running. * * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest * domain will be automatically destroyed when the virConnectPtr * object is finally released. This will also happen if the * client application crashes / loses its connection to the * libvirtd daemon. Any domains marked for auto destroy will * block attempts at migration, save-to-file, or snapshots. * * If the VIR_DOMAIN_START_BYPASS_CACHE flag is set, and there is a * managed save file for this domain (created by virDomainManagedSave()), * then libvirt will attempt to bypass the file system cache while restoring * the file, or fail if it cannot do so for the given system; this can allow * less pressure on file system cache, but also risks slowing loads from NFS. * * If the VIR_DOMAIN_START_FORCE_BOOT flag is set, then any managed save * file for this domain is discarded, and the domain boots from scratch. * * Returns 0 in case of success, -1 in case of error */ int virDomainCreateWithFiles(virDomainPtr domain, unsigned int nfiles, int *files, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "nfiles=%u, files=%p, flags=%x", nfiles, files, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainCreateWithFiles) { int ret; ret = conn->driver->domainCreateWithFiles(domain, nfiles, files, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetAutostart: * @domain: a domain object * @autostart: the value returned * * Provides a boolean value indicating whether the domain * configured to be automatically started when the host * machine boots. * * Returns -1 in case of error, 0 in case of success */ int virDomainGetAutostart(virDomainPtr domain, int *autostart) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "autostart=%p", autostart); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(autostart, error); conn = domain->conn; if (conn->driver->domainGetAutostart) { int ret; ret = conn->driver->domainGetAutostart(domain, autostart); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetAutostart: * @domain: a domain object * @autostart: whether the domain should be automatically started 0 or 1 * * Configure the domain to be automatically started * when the host machine boots. * * Returns -1 in case of error, 0 in case of success */ int virDomainSetAutostart(virDomainPtr domain, int autostart) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "autostart=%d", autostart); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainSetAutostart) { int ret; ret = conn->driver->domainSetAutostart(domain, autostart); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainInjectNMI: * @domain: pointer to domain object, or NULL for Domain0 * @flags: extra flags; not used yet, so callers should always pass 0 * * Send NMI to the guest * * Returns 0 in case of success, -1 in case of failure. */ int virDomainInjectNMI(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainInjectNMI) { int ret; ret = conn->driver->domainInjectNMI(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSendKey: * @domain: pointer to domain object, or NULL for Domain0 * @codeset: the code set of keycodes, from virKeycodeSet * @holdtime: the duration (in milliseconds) that the keys will be held * @keycodes: array of keycodes * @nkeycodes: number of keycodes, up to VIR_DOMAIN_SEND_KEY_MAX_KEYS * @flags: extra flags; not used yet, so callers should always pass 0 * * Send key(s) to the guest. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSendKey(virDomainPtr domain, unsigned int codeset, unsigned int holdtime, unsigned int *keycodes, int nkeycodes, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "codeset=%u, holdtime=%u, nkeycodes=%u, flags=%x", codeset, holdtime, nkeycodes, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(keycodes, error); virCheckPositiveArgGoto(nkeycodes, error); if (nkeycodes > VIR_DOMAIN_SEND_KEY_MAX_KEYS) { virReportInvalidArg(nkeycodes, _("nkeycodes must be <= %d"), VIR_DOMAIN_SEND_KEY_MAX_KEYS); goto error; } if (conn->driver->domainSendKey) { int ret; ret = conn->driver->domainSendKey(domain, codeset, holdtime, keycodes, nkeycodes, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSendProcessSignal: * @domain: pointer to domain object * @pid_value: a positive integer process ID, or negative integer process group ID * @signum: a signal from the virDomainProcessSignal enum * @flags: one of the virDomainProcessSignalFlag values * * Send a signal to the designated process in the guest * * The signal numbers must be taken from the virDomainProcessSignal * enum. These will be translated to the corresponding signal * number for the guest OS, by the guest agent delivering the * signal. If there is no mapping from virDomainProcessSignal to * the native OS signals, this API will report an error. * * If @pid_value is an integer greater than zero, it is * treated as a process ID. If @pid_value is an integer * less than zero, it is treated as a process group ID. * All the @pid_value numbers are from the container/guest * namespace. The value zero is not valid. * * Not all hypervisors will support sending signals to * arbitrary processes or process groups. If this API is * implemented the minimum requirement is to be able to * use @pid_value == 1 (i.e. kill init). No other value is * required to be supported. * * If the @signum is VIR_DOMAIN_PROCESS_SIGNAL_NOP then this * API will simply report whether the process is running in * the container/guest. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSendProcessSignal(virDomainPtr domain, long long pid_value, unsigned int signum, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "pid=%lld, signum=%u flags=%x", pid_value, signum, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonZeroArgGoto(pid_value, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainSendProcessSignal) { int ret; ret = conn->driver->domainSendProcessSignal(domain, pid_value, signum, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetVcpus: * @domain: pointer to domain object, or NULL for Domain0 * @nvcpus: the new number of virtual CPUs for this domain * * Dynamically change the number of virtual CPUs used by the domain. * Note that this call may fail if the underlying virtualization hypervisor * does not support it or if growing the number is arbitrarily limited. * This function may require privileged access to the hypervisor. * * Note that if this call is executed before the guest has finished booting, * the guest may fail to process the change. * * This command only changes the runtime configuration of the domain, * so can only be called on an active domain. It is hypervisor-dependent * whether it also affects persistent configuration; for more control, * use virDomainSetVcpusFlags(). * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "nvcpus=%u", nvcpus); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonZeroArgGoto(nvcpus, error); if (conn->driver->domainSetVcpus) { int ret; ret = conn->driver->domainSetVcpus(domain, nvcpus); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetVcpusFlags: * @domain: pointer to domain object, or NULL for Domain0 * @nvcpus: the new number of virtual CPUs for this domain, must be at least 1 * @flags: bitwise-OR of virDomainVcpuFlags * * Dynamically change the number of virtual CPUs used by the domain. * Note that this call may fail if the underlying virtualization hypervisor * does not support it or if growing the number is arbitrarily limited. * This function may require privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE to affect a running * domain (which may fail if domain is not active), or * VIR_DOMAIN_AFFECT_CONFIG to affect the next boot via the XML * description of the domain. Both flags may be set. * If neither flag is specified (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), * then an inactive domain modifies persistent setup, while an active domain * is hypervisor-dependent on whether just live or both live and persistent * state is changed. * * Note that if this call is executed before the guest has finished booting, * the guest may fail to process the change. * * If @flags includes VIR_DOMAIN_VCPU_MAXIMUM, then * VIR_DOMAIN_AFFECT_LIVE must be clear, and only the maximum virtual * CPU limit is altered; generally, this value must be less than or * equal to virConnectGetMaxVcpus(). Otherwise, this call affects the * current virtual CPU limit, which must be less than or equal to the * maximum limit. * * If @flags includes VIR_DOMAIN_VCPU_GUEST, then the state of processors is * modified inside the guest instead of the hypervisor. This flag can only * be used with live guests and is incompatible with VIR_DOMAIN_VCPU_MAXIMUM. * The usage of this flag may require a guest agent configured. * * Not all hypervisors can support all flag combinations. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "nvcpus=%u, flags=%x", nvcpus, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); VIR_REQUIRE_FLAG_GOTO(VIR_DOMAIN_VCPU_MAXIMUM, VIR_DOMAIN_AFFECT_CONFIG, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_VCPU_GUEST, VIR_DOMAIN_AFFECT_CONFIG, error); virCheckNonZeroArgGoto(nvcpus, error); conn = domain->conn; if (conn->driver->domainSetVcpusFlags) { int ret; ret = conn->driver->domainSetVcpusFlags(domain, nvcpus, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetVcpusFlags: * @domain: pointer to domain object, or NULL for Domain0 * @flags: bitwise-OR of virDomainVcpuFlags * * Query the number of virtual CPUs used by the domain. Note that * this call may fail if the underlying virtualization hypervisor does * not support it. This function may require privileged access to the * hypervisor. * * If @flags includes VIR_DOMAIN_AFFECT_LIVE, this will query a * running domain (which will fail if domain is not active); if * it includes VIR_DOMAIN_AFFECT_CONFIG, this will query the XML * description of the domain. It is an error to set both flags. * If neither flag is set (that is, VIR_DOMAIN_AFFECT_CURRENT), * then the configuration queried depends on whether the domain * is currently running. * * If @flags includes VIR_DOMAIN_VCPU_MAXIMUM, then the maximum * virtual CPU limit is queried. Otherwise, this call queries the * current virtual CPU count. * * If @flags includes VIR_DOMAIN_VCPU_GUEST, then the state of the processors * is queried in the guest instead of the hypervisor. This flag is only usable * on live domains. Guest agent may be needed for this flag to be available. * * Returns the number of vCPUs in case of success, -1 in case of failure. */ int virDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; if (flags & VIR_DOMAIN_VCPU_GUEST) virCheckReadOnlyGoto(conn->flags, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); if (conn->driver->domainGetVcpusFlags) { int ret; ret = conn->driver->domainGetVcpusFlags(domain, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainPinVcpu: * @domain: pointer to domain object, or NULL for Domain0 * @vcpu: virtual CPU number * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN) * Each bit set to 1 means that corresponding CPU is usable. * Bytes are stored in little-endian order: CPU0-7, 8-15... * In each byte, lowest CPU number is least significant bit. * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in * underlying virtualization system (Xen...). * If maplen < size, missing bytes are set to zero. * If maplen > size, failure code is returned. * * Dynamically change the real CPUs which can be allocated to a virtual CPU. * This function may require privileged access to the hypervisor. * * This command only changes the runtime configuration of the domain, * so can only be called on an active domain. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainPinVcpu(virDomainPtr domain, unsigned int vcpu, unsigned char *cpumap, int maplen) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "vcpu=%u, cpumap=%p, maplen=%d", vcpu, cpumap, maplen); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(cpumap, error); virCheckPositiveArgGoto(maplen, error); if (conn->driver->domainPinVcpu) { int ret; ret = conn->driver->domainPinVcpu(domain, vcpu, cpumap, maplen); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainPinVcpuFlags: * @domain: pointer to domain object, or NULL for Domain0 * @vcpu: virtual CPU number * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN) * Each bit set to 1 means that corresponding CPU is usable. * Bytes are stored in little-endian order: CPU0-7, 8-15... * In each byte, lowest CPU number is least significant bit. * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in * underlying virtualization system (Xen...). * If maplen < size, missing bytes are set to zero. * If maplen > size, failure code is returned. * @flags: bitwise-OR of virDomainModificationImpact * * Dynamically change the real CPUs which can be allocated to a virtual CPU. * This function may require privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain * and may fail if domain is not alive. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified (that is, * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies * persistent setup, while an active domain is hypervisor-dependent on whether * just live or both live and persistent state is changed. * Not all hypervisors can support all flag combinations. * * See also virDomainGetVcpuPinInfo for querying this information. * * Returns 0 in case of success, -1 in case of failure. * */ int virDomainPinVcpuFlags(virDomainPtr domain, unsigned int vcpu, unsigned char *cpumap, int maplen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "vcpu=%u, cpumap=%p, maplen=%d, flags=%x", vcpu, cpumap, maplen, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(cpumap, error); virCheckPositiveArgGoto(maplen, error); if (conn->driver->domainPinVcpuFlags) { int ret; ret = conn->driver->domainPinVcpuFlags(domain, vcpu, cpumap, maplen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetVcpuPinInfo: * @domain: pointer to domain object, or NULL for Domain0 * @ncpumaps: the number of cpumap (listed first to match virDomainGetVcpus) * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this * domain (in 8-bit bytes) (OUT) * It's assumed there is <ncpumaps> cpumap in cpumaps array. * The memory allocated to cpumaps must be (ncpumaps * maplen) bytes * (ie: calloc(ncpumaps, maplen)). * One cpumap inside cpumaps has the format described in * virDomainPinVcpu() API. * Must not be NULL. * @maplen: the number of bytes in one cpumap, from 1 up to size of CPU map. * Must be positive. * @flags: bitwise-OR of virDomainModificationImpact * Must not be VIR_DOMAIN_AFFECT_LIVE and * VIR_DOMAIN_AFFECT_CONFIG concurrently. * * Query the CPU affinity setting of all virtual CPUs of domain, store it * in cpumaps. * * Returns the number of virtual CPUs in case of success, * -1 in case of failure. */ int virDomainGetVcpuPinInfo(virDomainPtr domain, int ncpumaps, unsigned char *cpumaps, int maplen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "ncpumaps=%d, cpumaps=%p, maplen=%d, flags=%x", ncpumaps, cpumaps, maplen, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(cpumaps, error); virCheckPositiveArgGoto(ncpumaps, error); virCheckPositiveArgGoto(maplen, error); if (INT_MULTIPLY_OVERFLOW(ncpumaps, maplen)) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %d * %d"), ncpumaps, maplen); goto error; } VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); if (conn->driver->domainGetVcpuPinInfo) { int ret; ret = conn->driver->domainGetVcpuPinInfo(domain, ncpumaps, cpumaps, maplen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainPinEmulator: * @domain: pointer to domain object, or NULL for Domain0 * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN) * Each bit set to 1 means that corresponding CPU is usable. * Bytes are stored in little-endian order: CPU0-7, 8-15... * In each byte, lowest CPU number is least significant bit. * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in * underlying virtualization system (Xen...). * If maplen < size, missing bytes are set to zero. * If maplen > size, failure code is returned. * @flags: bitwise-OR of virDomainModificationImpact * * Dynamically change the real CPUs which can be allocated to all emulator * threads. This function may require privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain * and may fail if domain is not alive. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified (that is, * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies * persistent setup, while an active domain is hypervisor-dependent on whether * just live or both live and persistent state is changed. * Not all hypervisors can support all flag combinations. * * See also virDomainGetEmulatorPinInfo for querying this information. * * Returns 0 in case of success, -1 in case of failure. * */ int virDomainPinEmulator(virDomainPtr domain, unsigned char *cpumap, int maplen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cpumap=%p, maplen=%d, flags=%x", cpumap, maplen, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(cpumap, error); virCheckPositiveArgGoto(maplen, error); if (conn->driver->domainPinEmulator) { int ret; ret = conn->driver->domainPinEmulator(domain, cpumap, maplen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetEmulatorPinInfo: * @domain: pointer to domain object, or NULL for Domain0 * @cpumap: pointer to a bit map of real CPUs for all emulator threads of * this domain (in 8-bit bytes) (OUT) * There is only one cpumap for all emulator threads. * Must not be NULL. * @maplen: the number of bytes in one cpumap, from 1 up to size of CPU map. * Must be positive. * @flags: bitwise-OR of virDomainModificationImpact * Must not be VIR_DOMAIN_AFFECT_LIVE and * VIR_DOMAIN_AFFECT_CONFIG concurrently. * * Query the CPU affinity setting of all emulator threads of domain, store * it in cpumap. * * Returns 1 in case of success, * 0 in case of no emulator threads are pined to pcpus, * -1 in case of failure. */ int virDomainGetEmulatorPinInfo(virDomainPtr domain, unsigned char *cpumap, int maplen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cpumap=%p, maplen=%d, flags=%x", cpumap, maplen, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(cpumap, error); virCheckPositiveArgGoto(maplen, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); conn = domain->conn; if (conn->driver->domainGetEmulatorPinInfo) { int ret; ret = conn->driver->domainGetEmulatorPinInfo(domain, cpumap, maplen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetVcpus: * @domain: pointer to domain object, or NULL for Domain0 * @info: pointer to an array of virVcpuInfo structures (OUT) * @maxinfo: number of structures in info array * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this * domain (in 8-bit bytes) (OUT) * If cpumaps is NULL, then no cpumap information is returned by the API. * It's assumed there is <maxinfo> cpumap in cpumaps array. * The memory allocated to cpumaps must be (maxinfo * maplen) bytes * (ie: calloc(maxinfo, maplen)). * One cpumap inside cpumaps has the format described in * virDomainPinVcpu() API. * @maplen: number of bytes in one cpumap, from 1 up to size of CPU map in * underlying virtualization system (Xen...). * Must be zero when cpumaps is NULL and positive when it is non-NULL. * * Extract information about virtual CPUs of domain, store it in info array * and also in cpumaps if this pointer isn't NULL. This call may fail * on an inactive domain. * * See also virDomainGetVcpuPinInfo for querying just cpumaps, including on * an inactive domain. * * Returns the number of info filled in case of success, -1 in case of failure. */ int virDomainGetVcpus(virDomainPtr domain, virVcpuInfoPtr info, int maxinfo, unsigned char *cpumaps, int maplen) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "info=%p, maxinfo=%d, cpumaps=%p, maplen=%d", info, maxinfo, cpumaps, maplen); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(info, error); virCheckPositiveArgGoto(maxinfo, error); /* Ensure that domainGetVcpus (aka remoteDomainGetVcpus) does not try to memcpy anything into a NULL pointer. */ if (cpumaps) virCheckPositiveArgGoto(maplen, error); else virCheckZeroArgGoto(maplen, error); if (cpumaps && INT_MULTIPLY_OVERFLOW(maxinfo, maplen)) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %d * %d"), maxinfo, maplen); goto error; } conn = domain->conn; if (conn->driver->domainGetVcpus) { int ret; ret = conn->driver->domainGetVcpus(domain, info, maxinfo, cpumaps, maplen); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetMaxVcpus: * @domain: pointer to domain object * * Provides the maximum number of virtual CPUs supported for * the guest VM. If the guest is inactive, this is basically * the same as virConnectGetMaxVcpus(). If the guest is running * this will reflect the maximum number of virtual CPUs the * guest was booted with. For more details, see virDomainGetVcpusFlags(). * * Returns the maximum of virtual CPU or -1 in case of error. */ int virDomainGetMaxVcpus(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; if (conn->driver->domainGetMaxVcpus) { int ret; ret = conn->driver->domainGetMaxVcpus(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetIOThreadInfo: * @dom: a domain object * @info: pointer to an array of virDomainIOThreadInfo structures (OUT) * @flags: bitwise-OR of virDomainModificationImpact * Must not be VIR_DOMAIN_AFFECT_LIVE and * VIR_DOMAIN_AFFECT_CONFIG concurrently. * * Fetch IOThreads of an active domain including the cpumap information to * determine on which CPU the IOThread has affinity to run. * * Returns the number of IOThreads or -1 in case of error. * On success, the array of information is stored into @info. The caller is * responsible for calling virDomainIOThreadInfoFree() on each array element, * then calling free() on @info. On error, @info is set to NULL. */ int virDomainGetIOThreadInfo(virDomainPtr dom, virDomainIOThreadInfoPtr **info, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "info=%p flags=%x", info, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(info, error); *info = NULL; VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); if (dom->conn->driver->domainGetIOThreadInfo) { int ret; ret = dom->conn->driver->domainGetIOThreadInfo(dom, info, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainIOThreadInfoFree: * @info: pointer to a virDomainIOThreadInfo object * * Frees the memory used by @info. */ void virDomainIOThreadInfoFree(virDomainIOThreadInfoPtr info) { if (!info) return; VIR_FREE(info->cpumap); VIR_FREE(info); } /** * virDomainPinIOThread: * @domain: a domain object * @iothread_id: the IOThread ID to set the CPU affinity * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN) * Each bit set to 1 means that corresponding CPU is usable. * Bytes are stored in little-endian order: CPU0-7, 8-15... * In each byte, lowest CPU number is least significant bit. * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in * underlying virtualization system (Xen...). * If maplen < size, missing bytes are set to zero. * If maplen > size, failure code is returned. * @flags: bitwise-OR of virDomainModificationImpact * * Dynamically change the real CPUs which can be allocated to an IOThread. * This function may require privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain * and may fail if domain is not alive. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified (that is, * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies * persistent setup, while an active domain is hypervisor-dependent on whether * just live or both live and persistent state is changed. * Not all hypervisors can support all flag combinations. * * See also virDomainGetIOThreadInfo for querying this information. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainPinIOThread(virDomainPtr domain, unsigned int iothread_id, unsigned char *cpumap, int maplen, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "iothread_id=%u, cpumap=%p, maplen=%d", iothread_id, cpumap, maplen); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(cpumap, error); virCheckPositiveArgGoto(maplen, error); if (conn->driver->domainPinIOThread) { int ret; ret = conn->driver->domainPinIOThread(domain, iothread_id, cpumap, maplen, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainAddIOThread: * @domain: a domain object * @iothread_id: the specific IOThread ID value to add * @flags: bitwise-OR of virDomainModificationImpact * * Dynamically add an IOThread to the domain. It is left up to the * underlying virtual hypervisor to determine the valid range for an * @iothread_id and determining whether the @iothread_id already exists. * * Note that this call can fail if the underlying virtualization hypervisor * does not support it or if growing the number is arbitrarily limited. * This function requires privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain * and may fail if domain is not alive. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified (that is, * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies * persistent setup, while an active domain is hypervisor-dependent on whether * just live or both live and persistent state is changed. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainAddIOThread(virDomainPtr domain, unsigned int iothread_id, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "iothread_id=%u, flags=%x", iothread_id, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); conn = domain->conn; if (conn->driver->domainAddIOThread) { int ret; ret = conn->driver->domainAddIOThread(domain, iothread_id, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainDelIOThread: * @domain: a domain object * @iothread_id: the specific IOThread ID value to delete * @flags: bitwise-OR of virDomainModificationImpact * * Dynamically delete an IOThread from the domain. The @iothread_id to be * deleted must not have a resource associated with it and can be any of * the currently valid IOThread ID's. * * Note that this call can fail if the underlying virtualization hypervisor * does not support it or if reducing the number is arbitrarily limited. * This function requires privileged access to the hypervisor. * * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG. * Both flags may be set. * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain * and may fail if domain is not alive. * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state, * and will fail for transient domains. If neither flag is specified (that is, * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies * persistent setup, while an active domain is hypervisor-dependent on whether * just live or both live and persistent state is changed. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainDelIOThread(virDomainPtr domain, unsigned int iothread_id, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "iothread_id=%u, flags=%x", iothread_id, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckReadOnlyGoto(domain->conn->flags, error); virCheckNonZeroArgGoto(iothread_id, error); conn = domain->conn; if (conn->driver->domainDelIOThread) { int ret; ret = conn->driver->domainDelIOThread(domain, iothread_id, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetSecurityLabel: * @domain: a domain object * @seclabel: pointer to a virSecurityLabel structure * * Extract security label of an active domain. The 'label' field * in the @seclabel argument will be initialized to the empty * string if the domain is not running under a security model. * * Returns 0 in case of success, -1 in case of failure */ int virDomainGetSecurityLabel(virDomainPtr domain, virSecurityLabelPtr seclabel) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "seclabel=%p", seclabel); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(seclabel, error); if (conn->driver->domainGetSecurityLabel) { int ret; ret = conn->driver->domainGetSecurityLabel(domain, seclabel); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetSecurityLabelList: * @domain: a domain object * @seclabels: will be auto-allocated and filled with domains' security labels. * Caller must free memory on return. * * Extract the security labels of an active domain. The 'label' field * in the @seclabels argument will be initialized to the empty * string if the domain is not running under a security model. * * Returns number of elemnets in @seclabels on success, -1 in case of failure. */ int virDomainGetSecurityLabelList(virDomainPtr domain, virSecurityLabelPtr* seclabels) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "seclabels=%p", seclabels); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(seclabels, error); conn = domain->conn; if (conn->driver->domainGetSecurityLabelList) { int ret; ret = conn->driver->domainGetSecurityLabelList(domain, seclabels); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainSetMetadata: * @domain: a domain object * @type: type of metadata, from virDomainMetadataType * @metadata: new metadata text * @key: XML namespace key, or NULL * @uri: XML namespace URI, or NULL * @flags: bitwise-OR of virDomainModificationImpact * * Sets the appropriate domain element given by @type to the * value of @metadata. A @type of VIR_DOMAIN_METADATA_DESCRIPTION * is free-form text; VIR_DOMAIN_METADATA_TITLE is free-form, but no * newlines are permitted, and should be short (although the length is * not enforced). For these two options @key and @uri are irrelevant and * must be set to NULL. * * For type VIR_DOMAIN_METADATA_ELEMENT @metadata must be well-formed * XML belonging to namespace defined by @uri with local name @key. * * Passing NULL for @metadata says to remove that element from the * domain XML (passing the empty string leaves the element present). * * The resulting metadata will be present in virDomainGetXMLDesc(), * as well as quick access through virDomainGetMetadata(). * * @flags controls whether the live domain, persistent configuration, * or both will be modified. * * Returns 0 on success, -1 in case of failure. */ int virDomainSetMetadata(virDomainPtr domain, int type, const char *metadata, const char *key, const char *uri, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "type=%d, metadata='%s', key='%s', uri='%s', flags=%x", type, NULLSTR(metadata), NULLSTR(key), NULLSTR(uri), flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); switch (type) { case VIR_DOMAIN_METADATA_TITLE: if (metadata && strchr(metadata, '\n')) { virReportInvalidArg(metadata, "%s", _("metadata title can't contain " "newlines")); goto error; } /* fallthrough */ case VIR_DOMAIN_METADATA_DESCRIPTION: virCheckNullArgGoto(uri, error); virCheckNullArgGoto(key, error); break; case VIR_DOMAIN_METADATA_ELEMENT: virCheckNonNullArgGoto(uri, error); if (metadata) virCheckNonNullArgGoto(key, error); break; default: /* For future expansion */ break; } if (conn->driver->domainSetMetadata) { int ret; ret = conn->driver->domainSetMetadata(domain, type, metadata, key, uri, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetMetadata: * @domain: a domain object * @type: type of metadata, from virDomainMetadataType * @uri: XML namespace identifier * @flags: bitwise-OR of virDomainModificationImpact * * Retrieves the appropriate domain element given by @type. * If VIR_DOMAIN_METADATA_ELEMENT is requested parameter @uri * must be set to the name of the namespace the requested elements * belong to, otherwise must be NULL. * * If an element of the domain XML is not present, the resulting * error will be VIR_ERR_NO_DOMAIN_METADATA. This method forms * a shortcut for seeing information from virDomainSetMetadata() * without having to go through virDomainGetXMLDesc(). * * @flags controls whether the live domain or persistent * configuration will be queried. * * Returns the metadata string on success (caller must free), * or NULL in case of failure. */ char * virDomainGetMetadata(virDomainPtr domain, int type, const char *uri, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "type=%d, uri='%s', flags=%x", type, NULLSTR(uri), flags); virResetLastError(); virCheckDomainReturn(domain, NULL); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); switch (type) { case VIR_DOMAIN_METADATA_TITLE: case VIR_DOMAIN_METADATA_DESCRIPTION: virCheckNullArgGoto(uri, error); break; case VIR_DOMAIN_METADATA_ELEMENT: virCheckNonNullArgGoto(uri, error); break; default: /* For future expansion */ break; } conn = domain->conn; if (conn->driver->domainGetMetadata) { char *ret; if (!(ret = conn->driver->domainGetMetadata(domain, type, uri, flags))) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virDomainAttachDevice: * @domain: pointer to domain object * @xml: pointer to XML description of one device * * Create a virtual device attachment to backend. This function, * having hotplug semantics, is only allowed on an active domain. * * For compatibility, this method can also be used to change the media * in an existing CDROM/Floppy device, however, applications are * recommended to use the virDomainUpdateDeviceFlag method instead. * * Be aware that hotplug changes might not persist across a domain going * into S4 state (also known as hibernation) unless you also modify the * persistent domain definition. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainAttachDevice(virDomainPtr domain, const char *xml) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xml=%s", xml); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(xml, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainAttachDevice) { int ret; ret = conn->driver->domainAttachDevice(domain, xml); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainAttachDeviceFlags: * @domain: pointer to domain object * @xml: pointer to XML description of one device * @flags: bitwise-OR of virDomainDeviceModifyFlags * * Attach a virtual device to a domain, using the flags parameter * to control how the device is attached. VIR_DOMAIN_AFFECT_CURRENT * specifies that the device allocation is made based on current domain * state. VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be * allocated to the active domain instance only and is not added to the * persisted domain configuration. VIR_DOMAIN_AFFECT_CONFIG * specifies that the device shall be allocated to the persisted domain * configuration only. Note that the target hypervisor must return an * error if unable to satisfy flags. E.g. the hypervisor driver will * return failure if LIVE is specified but it only supports modifying the * persisted device allocation. * * For compatibility, this method can also be used to change the media * in an existing CDROM/Floppy device, however, applications are * recommended to use the virDomainUpdateDeviceFlag method instead. * * Be aware that hotplug changes might not persist across a domain going * into S4 state (also known as hibernation) unless you also modify the * persistent domain definition. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainAttachDeviceFlags(virDomainPtr domain, const char *xml, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=%x", xml, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(xml, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainAttachDeviceFlags) { int ret; ret = conn->driver->domainAttachDeviceFlags(domain, xml, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainDetachDevice: * @domain: pointer to domain object * @xml: pointer to XML description of one device * * This is an equivalent of virDomainDetachDeviceFlags() when called with * @flags parameter set to VIR_DOMAIN_AFFECT_LIVE. * * See virDomainDetachDeviceFlags() for more details. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainDetachDevice(virDomainPtr domain, const char *xml) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xml=%s", xml); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(xml, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainDetachDevice) { int ret; ret = conn->driver->domainDetachDevice(domain, xml); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainDetachDeviceFlags: * @domain: pointer to domain object * @xml: pointer to XML description of one device * @flags: bitwise-OR of virDomainDeviceModifyFlags * * Detach a virtual device from a domain, using the flags parameter * to control how the device is detached. VIR_DOMAIN_AFFECT_CURRENT * specifies that the device allocation is removed based on current domain * state. VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be * deallocated from the active domain instance only and is not from the * persisted domain configuration. VIR_DOMAIN_AFFECT_CONFIG * specifies that the device shall be deallocated from the persisted domain * configuration only. Note that the target hypervisor must return an * error if unable to satisfy flags. E.g. the hypervisor driver will * return failure if LIVE is specified but it only supports removing the * persisted device allocation. * * Some hypervisors may prevent this operation if there is a current * block copy operation on the device being detached; in that case, * use virDomainBlockJobAbort() to stop the block copy first. * * Beware that depending on the hypervisor and device type, detaching a device * from a running domain may be asynchronous. That is, calling * virDomainDetachDeviceFlags may just request device removal while the device * is actually removed later (in cooperation with a guest OS). Previously, * this fact was ignored and the device could have been removed from domain * configuration before it was actually removed by the hypervisor causing * various failures on subsequent operations. To check whether the device was * successfully removed, either recheck domain configuration using * virDomainGetXMLDesc() or add a handler for the VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED * event. In case the device is already gone when virDomainDetachDeviceFlags * returns, the event is delivered before this API call ends. To help existing * clients work better in most cases, this API will try to transform an * asynchronous device removal that finishes shortly after the request into * a synchronous removal. In other words, this API may wait a bit for the * removal to complete in case it was not synchronous. * * Be aware that hotplug changes might not persist across a domain going * into S4 state (also known as hibernation) unless you also modify the * persistent domain definition. * * The supplied XML description of the device should be as specific * as its definition in the domain XML. The set of attributes used * to match the device are internal to the drivers. Using a partial definition, * or attempting to detach a device that is not present in the domain XML, * but shares some specific attributes with one that is present, * may lead to unexpected results. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainDetachDeviceFlags(virDomainPtr domain, const char *xml, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=%x", xml, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(xml, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainDetachDeviceFlags) { int ret; ret = conn->driver->domainDetachDeviceFlags(domain, xml, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainUpdateDeviceFlags: * @domain: pointer to domain object * @xml: pointer to XML description of one device * @flags: bitwise-OR of virDomainDeviceModifyFlags * * Change a virtual device on a domain, using the flags parameter * to control how the device is changed. VIR_DOMAIN_AFFECT_CURRENT * specifies that the device change is made based on current domain * state. VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be * changed on the active domain instance only and is not added to the * persisted domain configuration. VIR_DOMAIN_AFFECT_CONFIG * specifies that the device shall be changed on the persisted domain * configuration only. Note that the target hypervisor must return an * error if unable to satisfy flags. E.g. the hypervisor driver will * return failure if LIVE is specified but it only supports modifying the * persisted device allocation. * * This method is used for actions such changing CDROM/Floppy device * media, altering the graphics configuration such as password, * reconfiguring the NIC device backend connectivity, etc. * * Returns 0 in case of success, -1 in case of failure. */ int virDomainUpdateDeviceFlags(virDomainPtr domain, const char *xml, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=%x", xml, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(xml, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainUpdateDeviceFlags) { int ret; ret = conn->driver->domainUpdateDeviceFlags(domain, xml, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virConnectDomainEventRegister: * @conn: pointer to the connection * @cb: callback to the function handling domain events * @opaque: opaque data to pass on to the callback * @freecb: optional function to deallocate opaque when not used anymore * * Adds a callback to receive notifications of domain lifecycle events * occurring on a connection. This function requires that an event loop * has been previously registered with virEventRegisterImpl() or * virEventRegisterDefaultImpl(). * * Use of this method is no longer recommended. Instead applications * should try virConnectDomainEventRegisterAny() which has a more flexible * API contract. * * The virDomainPtr object handle passed into the callback upon delivery * of an event is only valid for the duration of execution of the callback. * If the callback wishes to keep the domain object after the callback returns, * it shall take a reference to it, by calling virDomainRef. * The reference can be released once the object is no longer required * by calling virDomainFree. * * Returns 0 on success, -1 on failure. Older versions of some hypervisors * sometimes returned a positive number on success, but without any reliable * semantics on what that number represents. */ int virConnectDomainEventRegister(virConnectPtr conn, virConnectDomainEventCallback cb, void *opaque, virFreeCallback freecb) { VIR_DEBUG("conn=%p, cb=%p, opaque=%p, freecb=%p", conn, cb, opaque, freecb); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNullArgGoto(cb, error); if (conn->driver && conn->driver->connectDomainEventRegister) { int ret; ret = conn->driver->connectDomainEventRegister(conn, cb, opaque, freecb); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectDomainEventDeregister: * @conn: pointer to the connection * @cb: callback to the function handling domain events * * Removes a callback previously registered with the * virConnectDomainEventRegister() function. * * Use of this method is no longer recommended. Instead applications * should try virConnectDomainEventDeregisterAny() which has a more flexible * API contract * * Returns 0 on success, -1 on failure. Older versions of some hypervisors * sometimes returned a positive number on success, but without any reliable * semantics on what that number represents. */ int virConnectDomainEventDeregister(virConnectPtr conn, virConnectDomainEventCallback cb) { VIR_DEBUG("conn=%p, cb=%p", conn, cb); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNullArgGoto(cb, error); if (conn->driver && conn->driver->connectDomainEventDeregister) { int ret; ret = conn->driver->connectDomainEventDeregister(conn, cb); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainIsActive: * @dom: pointer to the domain object * * Determine if the domain is currently running * * Returns 1 if running, 0 if inactive, -1 on error */ int virDomainIsActive(virDomainPtr dom) { VIR_DEBUG("dom=%p", dom); virResetLastError(); virCheckDomainReturn(dom, -1); if (dom->conn->driver->domainIsActive) { int ret; ret = dom->conn->driver->domainIsActive(dom); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainIsPersistent: * @dom: pointer to the domain object * * Determine if the domain has a persistent configuration * which means it will still exist after shutting down * * Returns 1 if persistent, 0 if transient, -1 on error */ int virDomainIsPersistent(virDomainPtr dom) { VIR_DOMAIN_DEBUG(dom); virResetLastError(); virCheckDomainReturn(dom, -1); if (dom->conn->driver->domainIsPersistent) { int ret; ret = dom->conn->driver->domainIsPersistent(dom); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainRename: * @dom: pointer to the domain object * @new_name: new domain name * @flags: extra flags; not used yet, so callers should always pass 0 * * Rename a domain. New domain name is specified in the second * argument. Depending on each driver implementation it may be * required that domain is in a specific state. * * There might be some attributes and/or elements in domain XML that if no * value provided at XML defining time, libvirt will derive their value from * the domain name. These are not updated by this API. Users are strongly * advised to change these after the rename was successful. * * Returns 0 if successfully renamed, -1 on error */ int virDomainRename(virDomainPtr dom, const char *new_name, unsigned int flags) { VIR_DEBUG("dom=%p, new_name=%s", dom, NULLSTR(new_name)); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(new_name, error); virCheckReadOnlyGoto(dom->conn->flags, error); if (dom->conn->driver->domainRename) { int ret = dom->conn->driver->domainRename(dom, new_name, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainIsUpdated: * @dom: pointer to the domain object * * Determine if the domain has been updated. * * Returns 1 if updated, 0 if not, -1 on error */ int virDomainIsUpdated(virDomainPtr dom) { VIR_DOMAIN_DEBUG(dom); virResetLastError(); virCheckDomainReturn(dom, -1); if (dom->conn->driver->domainIsUpdated) { int ret; ret = dom->conn->driver->domainIsUpdated(dom); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetJobInfo: * @domain: a domain object * @info: pointer to a virDomainJobInfo structure allocated by the user * * Extract information about progress of a background job on a domain. * Will return an error if the domain is not active. * * This function returns a limited amount of information in comparison * to virDomainGetJobStats(). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetJobInfo(virDomainPtr domain, virDomainJobInfoPtr info) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "info=%p", info); virResetLastError(); if (info) memset(info, 0, sizeof(*info)); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(info, error); conn = domain->conn; if (conn->driver->domainGetJobInfo) { int ret; ret = conn->driver->domainGetJobInfo(domain, info); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetJobStats: * @domain: a domain object * @type: where to store the job type (one of virDomainJobType) * @params: where to store job statistics * @nparams: number of items in @params * @flags: bitwise-OR of virDomainGetJobStatsFlags * * Extract information about progress of a background job on a domain. * Will return an error if the domain is not active. The function returns * a superset of progress information provided by virDomainGetJobInfo. * Possible fields returned in @params are defined by VIR_DOMAIN_JOB_* * macros and new fields will likely be introduced in the future so callers * may receive fields that they do not understand in case they talk to a * newer server. * * When @flags contains VIR_DOMAIN_JOB_STATS_COMPLETED, the function will * return statistics about a recently completed job. Specifically, this * flag may be used to query statistics of a completed incoming migration. * Statistics of a completed job are automatically destroyed once read or * when libvirtd is restarted. Note that time information returned for * completed migrations may be completely irrelevant unless both source and * destination hosts have synchronized time (i.e., NTP daemon is running on * both of them). * * Returns 0 in case of success and -1 in case of failure. */ int virDomainGetJobStats(virDomainPtr domain, int *type, virTypedParameterPtr *params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "type=%p, params=%p, nparams=%p, flags=%x", type, params, nparams, flags); virResetLastError(); virCheckDomainReturn(domain, -1); virCheckNonNullArgGoto(type, error); virCheckNonNullArgGoto(params, error); virCheckNonNullArgGoto(nparams, error); conn = domain->conn; if (conn->driver->domainGetJobStats) { int ret; ret = conn->driver->domainGetJobStats(domain, type, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainAbortJob: * @domain: a domain object * * Requests that the current background job be aborted at the * soonest opportunity. * * Returns 0 in case of success and -1 in case of failure. */ int virDomainAbortJob(virDomainPtr domain) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainAbortJob) { int ret; ret = conn->driver->domainAbortJob(domain); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainMigrateSetMaxDowntime: * @domain: a domain object * @downtime: maximum tolerable downtime for live migration, in milliseconds * @flags: extra flags; not used yet, so callers should always pass 0 * * Sets maximum tolerable time for which the domain is allowed to be paused * at the end of live migration. It's supposed to be called while the domain is * being live-migrated as a reaction to migration progress. * * Returns 0 in case of success, -1 otherwise. */ int virDomainMigrateSetMaxDowntime(virDomainPtr domain, unsigned long long downtime, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "downtime=%llu, flags=%x", downtime, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateSetMaxDowntime) { if (conn->driver->domainMigrateSetMaxDowntime(domain, downtime, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainMigrateGetCompressionCache: * @domain: a domain object * @cacheSize: return value of current size of the cache (in bytes) * @flags: extra flags; not used yet, so callers should always pass 0 * * Gets current size of the cache (in bytes) used for compressing repeatedly * transferred memory pages during live migration. * * Returns 0 in case of success, -1 otherwise. */ int virDomainMigrateGetCompressionCache(virDomainPtr domain, unsigned long long *cacheSize, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cacheSize=%p, flags=%x", cacheSize, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(cacheSize, error); if (conn->driver->domainMigrateGetCompressionCache) { if (conn->driver->domainMigrateGetCompressionCache(domain, cacheSize, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainMigrateSetCompressionCache: * @domain: a domain object * @cacheSize: size of the cache (in bytes) used for compression * @flags: extra flags; not used yet, so callers should always pass 0 * * Sets size of the cache (in bytes) used for compressing repeatedly * transferred memory pages during live migration. It's supposed to be called * while the domain is being live-migrated as a reaction to migration progress * and increasing number of compression cache misses obtained from * virDomainGetJobStats. * * Returns 0 in case of success, -1 otherwise. */ int virDomainMigrateSetCompressionCache(virDomainPtr domain, unsigned long long cacheSize, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "cacheSize=%llu, flags=%x", cacheSize, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateSetCompressionCache) { if (conn->driver->domainMigrateSetCompressionCache(domain, cacheSize, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainMigrateSetMaxSpeed: * @domain: a domain object * @bandwidth: migration bandwidth limit in MiB/s * @flags: extra flags; not used yet, so callers should always pass 0 * * The maximum bandwidth (in MiB/s) that will be used to do migration * can be specified with the bandwidth parameter. Not all hypervisors * will support a bandwidth cap * * Returns 0 in case of success, -1 otherwise. */ int virDomainMigrateSetMaxSpeed(virDomainPtr domain, unsigned long bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "bandwidth=%lu, flags=%x", bandwidth, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateSetMaxSpeed) { if (conn->driver->domainMigrateSetMaxSpeed(domain, bandwidth, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainMigrateGetMaxSpeed: * @domain: a domain object * @bandwidth: return value of current migration bandwidth limit in MiB/s * @flags: extra flags; not used yet, so callers should always pass 0 * * Get the current maximum bandwidth (in MiB/s) that will be used if the * domain is migrated. Not all hypervisors will support a bandwidth limit. * * Returns 0 in case of success, -1 otherwise. */ int virDomainMigrateGetMaxSpeed(virDomainPtr domain, unsigned long *bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "bandwidth = %p, flags=%x", bandwidth, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; virCheckNonNullArgGoto(bandwidth, error); virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainMigrateGetMaxSpeed) { if (conn->driver->domainMigrateGetMaxSpeed(domain, bandwidth, flags) < 0) goto error; return 0; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectDomainEventRegisterAny: * @conn: pointer to the connection * @dom: pointer to the domain * @eventID: the event type to receive * @cb: callback to the function handling domain events * @opaque: opaque data to pass on to the callback * @freecb: optional function to deallocate opaque when not used anymore * * Adds a callback to receive notifications of arbitrary domain events * occurring on a domain. This function requires that an event loop * has been previously registered with virEventRegisterImpl() or * virEventRegisterDefaultImpl(). * * If @dom is NULL, then events will be monitored for any domain. If @dom * is non-NULL, then only the specific domain will be monitored. * * Most types of event have a callback providing a custom set of parameters * for the event. When registering an event, it is thus necessary to use * the VIR_DOMAIN_EVENT_CALLBACK() macro to cast the supplied function pointer * to match the signature of this method. * * The virDomainPtr object handle passed into the callback upon delivery * of an event is only valid for the duration of execution of the callback. * If the callback wishes to keep the domain object after the callback returns, * it shall take a reference to it, by calling virDomainRef(). * The reference can be released once the object is no longer required * by calling virDomainFree(). * * The return value from this method is a positive integer identifier * for the callback. To unregister a callback, this callback ID should * be passed to the virConnectDomainEventDeregisterAny() method. * * Returns a callback identifier on success, -1 on failure. */ int virConnectDomainEventRegisterAny(virConnectPtr conn, virDomainPtr dom, int eventID, virConnectDomainEventGenericCallback cb, void *opaque, virFreeCallback freecb) { VIR_DOMAIN_DEBUG(dom, "conn=%p, eventID=%d, cb=%p, opaque=%p, freecb=%p", conn, eventID, cb, opaque, freecb); virResetLastError(); virCheckConnectReturn(conn, -1); if (dom) { virCheckDomainGoto(dom, error); if (dom->conn != conn) { virReportInvalidArg(dom, _("domain '%s' must match connection"), dom->name); goto error; } } virCheckNonNullArgGoto(cb, error); virCheckNonNegativeArgGoto(eventID, error); if (eventID >= VIR_DOMAIN_EVENT_ID_LAST) { virReportInvalidArg(eventID, _("eventID must be less than %d"), VIR_DOMAIN_EVENT_ID_LAST); goto error; } if (conn->driver && conn->driver->connectDomainEventRegisterAny) { int ret; ret = conn->driver->connectDomainEventRegisterAny(conn, dom, eventID, cb, opaque, freecb); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virConnectDomainEventDeregisterAny: * @conn: pointer to the connection * @callbackID: the callback identifier * * Removes an event callback. The callbackID parameter should be the * value obtained from a previous virConnectDomainEventRegisterAny() method. * * Returns 0 on success, -1 on failure. Older versions of some hypervisors * sometimes returned a positive number on success, but without any reliable * semantics on what that number represents. */ int virConnectDomainEventDeregisterAny(virConnectPtr conn, int callbackID) { VIR_DEBUG("conn=%p, callbackID=%d", conn, callbackID); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNegativeArgGoto(callbackID, error); if (conn->driver && conn->driver->connectDomainEventDeregisterAny) { int ret; ret = conn->driver->connectDomainEventDeregisterAny(conn, callbackID); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainManagedSave: * @dom: pointer to the domain * @flags: bitwise-OR of virDomainSaveRestoreFlags * * This method will suspend a domain and save its memory contents to * a file on disk. After the call, if successful, the domain is not * listed as running anymore. * The difference from virDomainSave() is that libvirt is keeping track of * the saved state itself, and will reuse it once the domain is being * restarted (automatically or via an explicit libvirt call). * As a result any running domain is sure to not have a managed saved image. * This also implies that managed save only works on persistent domains, * since the domain must still exist in order to use virDomainCreate() to * restart it. * * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will * attempt to bypass the file system cache while creating the file, or * fail if it cannot do so for the given system; this can allow less * pressure on file system cache, but also risks slowing saves to NFS. * * Normally, the managed saved state will remember whether the domain * was running or paused, and start will resume to the same state. * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in * @flags will override the default saved into the file. These two * flags are mutually exclusive. * * Returns 0 in case of success or -1 in case of failure */ int virDomainManagedSave(virDomainPtr dom, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING, VIR_DOMAIN_SAVE_PAUSED, error); if (conn->driver->domainManagedSave) { int ret; ret = conn->driver->domainManagedSave(dom, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainHasManagedSaveImage: * @dom: pointer to the domain * @flags: extra flags; not used yet, so callers should always pass 0 * * Check if a domain has a managed save image as created by * virDomainManagedSave(). Note that any running domain should not have * such an image, as it should have been removed on restart. * * Returns 0 if no image is present, 1 if an image is present, and * -1 in case of error */ int virDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; if (conn->driver->domainHasManagedSaveImage) { int ret; ret = conn->driver->domainHasManagedSaveImage(dom, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainManagedSaveRemove: * @dom: pointer to the domain * @flags: extra flags; not used yet, so callers should always pass 0 * * Remove any managed save image for this domain. * * Returns 0 in case of success, and -1 in case of error */ int virDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); if (conn->driver->domainManagedSaveRemove) { int ret; ret = conn->driver->domainManagedSaveRemove(dom, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainOpenConsole: * @dom: a domain object * @dev_name: the console, serial or parallel port device alias, or NULL * @st: a stream to associate with the console * @flags: bitwise-OR of virDomainConsoleFlags * * This opens the backend associated with a console, serial or * parallel port device on a guest, if the backend is supported. * If the @dev_name is omitted, then the first console or serial * device is opened. The console is associated with the passed * in @st stream, which should have been opened in non-blocking * mode for bi-directional I/O. * * By default, when @flags is 0, the open will fail if libvirt * detects that the console is already in use by another client; * passing VIR_DOMAIN_CONSOLE_FORCE will cause libvirt to forcefully * remove the other client prior to opening this console. * * If flag VIR_DOMAIN_CONSOLE_SAFE the console is opened only in the * case where the hypervisor driver supports safe (mutually exclusive) * console handling. * * Older servers did not support either flag, and also did not forbid * simultaneous clients on a console, with potentially confusing results. * When passing @flags of 0 in order to support a wider range of server * versions, it is up to the client to ensure mutual exclusion. * * Returns 0 if the console was opened, -1 on error */ int virDomainOpenConsole(virDomainPtr dom, const char *dev_name, virStreamPtr st, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "dev_name=%s, st=%p, flags=%x", NULLSTR(dev_name), st, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckStreamGoto(st, error); virCheckReadOnlyGoto(conn->flags, error); if (conn != st->conn) { virReportInvalidArg(st, _("stream must match connection of domain '%s'"), dom->name); goto error; } if (conn->driver->domainOpenConsole) { int ret; ret = conn->driver->domainOpenConsole(dom, dev_name, st, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainOpenChannel: * @dom: a domain object * @name: the channel name, or NULL * @st: a stream to associate with the channel * @flags: bitwise-OR of virDomainChannelFlags * * This opens the host interface associated with a channel device on a * guest, if the host interface is supported. If @name is given, it * can match either the device alias (e.g. "channel0"), or the virtio * target name (e.g. "org.qemu.guest_agent.0"). If @name is omitted, * then the first channel is opened. The channel is associated with * the passed in @st stream, which should have been opened in * non-blocking mode for bi-directional I/O. * * By default, when @flags is 0, the open will fail if libvirt detects * that the channel is already in use by another client; passing * VIR_DOMAIN_CHANNEL_FORCE will cause libvirt to forcefully remove the * other client prior to opening this channel. * * Returns 0 if the channel was opened, -1 on error */ int virDomainOpenChannel(virDomainPtr dom, const char *name, virStreamPtr st, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "name=%s, st=%p, flags=%x", NULLSTR(name), st, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckStreamGoto(st, error); virCheckReadOnlyGoto(conn->flags, error); if (conn != st->conn) { virReportInvalidArg(st, _("stream must match connection of domain '%s'"), dom->name); goto error; } if (conn->driver->domainOpenChannel) { int ret; ret = conn->driver->domainOpenChannel(dom, name, st, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return -1; } /** * virDomainBlockJobAbort: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @flags: bitwise-OR of virDomainBlockJobAbortFlags * * Cancel the active block job on the given disk. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * If the current block job for @disk is VIR_DOMAIN_BLOCK_JOB_TYPE_PULL, then * by default, this function performs a synchronous operation and the caller * may assume that the operation has completed when 0 is returned. However, * BlockJob operations may take a long time to cancel, and during this time * further domain interactions may be unresponsive. To avoid this problem, * pass VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC in the @flags argument to enable * asynchronous behavior, returning as soon as possible. When the job has * been canceled, a BlockJob event will be emitted, with status * VIR_DOMAIN_BLOCK_JOB_CANCELED (even if the ABORT_ASYNC flag was not * used); it is also possible to poll virDomainBlockJobInfo() to see if * the job cancellation is still pending. This type of job can be restarted * to pick up from where it left off. * * If the current block job for @disk is VIR_DOMAIN_BLOCK_JOB_TYPE_COPY, then * the default is to abort the mirroring and revert to the source disk; * likewise, if the current job is VIR_DOMAIN_BLOCK_JOB_TYPE_ACTIVE_COMMIT, * the default is to abort without changing the active layer of @disk. * Adding @flags of VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT causes this call to * fail with VIR_ERR_BLOCK_COPY_ACTIVE if the copy or commit is not yet * ready; otherwise it will swap the disk over to the new active image * to end the mirroring or active commit. An event will be issued when the * job is ended, and it is possible to use VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC * to control whether this command waits for the completion of the job. * Restarting a copy or active commit job requires starting over from the * beginning of the first phase. * * Returns -1 in case of failure, 0 when successful. */ int virDomainBlockJobAbort(virDomainPtr dom, const char *disk, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, flags=%x", disk, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (conn->driver->domainBlockJobAbort) { int ret; ret = conn->driver->domainBlockJobAbort(dom, disk, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetBlockJobInfo: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @info: pointer to a virDomainBlockJobInfo structure * @flags: bitwise-OR of virDomainBlockJobInfoFlags * * Request block job information for the given disk. If an operation is active * @info will be updated with the current progress. The units used for the * bandwidth field of @info depends on @flags. If @flags includes * VIR_DOMAIN_BLOCK_JOB_INFO_BANDWIDTH_BYTES, bandwidth is in bytes/second * (although this mode can risk failure due to overflow, depending on both * client and server word size); otherwise, the value is rounded up to MiB/s. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * Returns -1 in case of failure, 0 when nothing found, 1 when info was found. */ int virDomainGetBlockJobInfo(virDomainPtr dom, const char *disk, virDomainBlockJobInfoPtr info, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, info=%p, flags=%x", disk, info, flags); virResetLastError(); if (info) memset(info, 0, sizeof(*info)); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckNonNullArgGoto(disk, error); virCheckNonNullArgGoto(info, error); if (conn->driver->domainGetBlockJobInfo) { int ret; ret = conn->driver->domainGetBlockJobInfo(dom, disk, info, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockJobSetSpeed: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @bandwidth: specify bandwidth limit; flags determine the unit * @flags: bitwise-OR of virDomainBlockJobSetSpeedFlags * * Set the maximimum allowable bandwidth that a block job may consume. If * bandwidth is 0, the limit will revert to the hypervisor default of * unlimited. * * If @flags contains VIR_DOMAIN_BLOCK_JOB_SPEED_BANDWIDTH_BYTES, @bandwidth * is in bytes/second; otherwise, it is in MiB/second. Values larger than * 2^52 bytes/sec may be rejected due to overflow considerations based on * the word size of both client and server, and values larger than 2^31 * bytes/sec may cause overflow problems if later queried by * virDomainGetBlockJobInfo() without scaling. Hypervisors may further * restrict the range of valid bandwidth values. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * Returns -1 in case of failure, 0 when successful. */ int virDomainBlockJobSetSpeed(virDomainPtr dom, const char *disk, unsigned long bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, bandwidth=%lu, flags=%x", disk, bandwidth, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (conn->driver->domainBlockJobSetSpeed) { int ret; ret = conn->driver->domainBlockJobSetSpeed(dom, disk, bandwidth, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockPull: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @bandwidth: (optional) specify bandwidth limit; flags determine the unit * @flags: bitwise-OR of virDomainBlockPullFlags * * Populate a disk image with data from its backing image. Once all data from * its backing image has been pulled, the disk no longer depends on a backing * image. This function pulls data for the entire device in the background. * Progress of the operation can be checked with virDomainGetBlockJobInfo() and * the operation can be aborted with virDomainBlockJobAbort(). When finished, * an asynchronous event is raised to indicate the final status. To move * data in the opposite direction, see virDomainBlockCommit(). * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or (since 0.9.5) the device target shorthand * (the <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * The maximum bandwidth that will be used to do the copy can be * specified with the @bandwidth parameter. If set to 0, there is no * limit. If @flags includes VIR_DOMAIN_BLOCK_PULL_BANDWIDTH_BYTES, * @bandwidth is in bytes/second; otherwise, it is in MiB/second. * Values larger than 2^52 bytes/sec may be rejected due to overflow * considerations based on the word size of both client and server, * and values larger than 2^31 bytes/sec may cause overflow problems * if later queried by virDomainGetBlockJobInfo() without scaling. * Hypervisors may further restrict the range of valid bandwidth * values. Some hypervisors do not support this feature and will * return an error if bandwidth is not 0; in this case, it might still * be possible for a later call to virDomainBlockJobSetSpeed() to * succeed. The actual speed can be determined with * virDomainGetBlockJobInfo(). * * This is shorthand for virDomainBlockRebase() with a NULL base. * * Returns 0 if the operation has started, -1 on failure. */ int virDomainBlockPull(virDomainPtr dom, const char *disk, unsigned long bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, bandwidth=%lu, flags=%x", disk, bandwidth, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (conn->driver->domainBlockPull) { int ret; ret = conn->driver->domainBlockPull(dom, disk, bandwidth, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockRebase: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @base: path to backing file to keep, or device shorthand, * or NULL for no backing file * @bandwidth: (optional) specify bandwidth limit; flags determine the unit * @flags: bitwise-OR of virDomainBlockRebaseFlags * * Populate a disk image with data from its backing image chain, and * setting the backing image to @base, or alternatively copy an entire * backing chain to a new file @base. * * When @flags is 0, this starts a pull, where @base must be the absolute * path of one of the backing images further up the chain, or NULL to * convert the disk image so that it has no backing image. Once all * data from its backing image chain has been pulled, the disk no * longer depends on those intermediate backing images. This function * pulls data for the entire device in the background. Progress of * the operation can be checked with virDomainGetBlockJobInfo() with a * job type of VIR_DOMAIN_BLOCK_JOB_TYPE_PULL, and the operation can be * aborted with virDomainBlockJobAbort(). When finished, an asynchronous * event is raised to indicate the final status, and the job no longer * exists. If the job is aborted, a new one can be started later to * resume from the same point. * * If @flags contains VIR_DOMAIN_BLOCK_REBASE_RELATIVE, the name recorded * into the active disk as the location for @base will be kept relative. * The operation will fail if libvirt can't infer the name. * * When @flags includes VIR_DOMAIN_BLOCK_REBASE_COPY, this starts a copy, * where @base must be the name of a new file to copy the chain to. By * default, the copy will pull the entire source chain into the destination * file, but if @flags also contains VIR_DOMAIN_BLOCK_REBASE_SHALLOW, then * only the top of the source chain will be copied (the source and * destination have a common backing file). By default, @base will be * created with the same file format as the source, but this can be altered * by adding VIR_DOMAIN_BLOCK_REBASE_COPY_RAW to force the copy to be raw * (does not make sense with the shallow flag unless the source is also raw), * or by using VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT to reuse an existing file * which was pre-created with the correct format and metadata and sufficient * size to hold the copy. In case the VIR_DOMAIN_BLOCK_REBASE_SHALLOW flag * is used the pre-created file has to exhibit the same guest visible contents * as the backing file of the original image. This allows a management app to * pre-create files with relative backing file names, rather than the default * of absolute backing file names; as a security precaution, you should * generally only use reuse_ext with the shallow flag and a non-raw * destination file. By default, the copy destination will be treated as * type='file', but using VIR_DOMAIN_BLOCK_REBASE_COPY_DEV treats the * destination as type='block' (affecting how virDomainGetBlockInfo() will * report allocation after pivoting). * * A copy job has two parts; in the first phase, the @bandwidth parameter * affects how fast the source is pulled into the destination, and the job * can only be canceled by reverting to the source file; progress in this * phase can be tracked via the virDomainBlockJobInfo() command, with a * job type of VIR_DOMAIN_BLOCK_JOB_TYPE_COPY. The job transitions to the * second phase when the job info states cur == end, and remains alive to * mirror all further changes to both source and destination. The user * must call virDomainBlockJobAbort() to end the mirroring while choosing * whether to revert to source or pivot to the destination. An event is * issued when the job ends, and depending on the hypervisor, an event may * also be issued when the job transitions from pulling to mirroring. If * the job is aborted, a new job will have to start over from the beginning * of the first phase. * * Some hypervisors will restrict certain actions, such as virDomainSave() * or virDomainDetachDevice(), while a copy job is active; they may * also restrict a copy job to transient domains. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or the device target shorthand (the * <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * The @base parameter can be either a path to a file within the backing * chain, or the device target shorthand (the <target dev='...'/> * sub-element, such as "vda") followed by an index to the backing chain * enclosed in square brackets. Backing chain indexes can be found by * inspecting //disk//backingStore/@index in the domain XML. Thus, for * example, "vda[3]" refers to the backing store with index equal to "3" * in the chain of disk "vda". * * The maximum bandwidth that will be used to do the copy can be * specified with the @bandwidth parameter. If set to 0, there is no * limit. If @flags includes VIR_DOMAIN_BLOCK_REBASE_BANDWIDTH_BYTES, * @bandwidth is in bytes/second; otherwise, it is in MiB/second. * Values larger than 2^52 bytes/sec may be rejected due to overflow * considerations based on the word size of both client and server, * and values larger than 2^31 bytes/sec may cause overflow problems * if later queried by virDomainGetBlockJobInfo() without scaling. * Hypervisors may further restrict the range of valid bandwidth * values. Some hypervisors do not support this feature and will * return an error if bandwidth is not 0; in this case, it might still * be possible for a later call to virDomainBlockJobSetSpeed() to * succeed. The actual speed can be determined with * virDomainGetBlockJobInfo(). * * When @base is NULL and @flags is 0, this is identical to * virDomainBlockPull(). When @flags contains VIR_DOMAIN_BLOCK_REBASE_COPY, * this command is shorthand for virDomainBlockCopy() where the destination * XML encodes @base as a <disk type='file'>, @bandwidth is properly scaled * and passed as a typed parameter, the shallow and reuse external flags * are preserved, and remaining flags control whether the XML encodes a * destination format of raw instead of leaving the destination identical * to the source format or probed from the reused file. * * Returns 0 if the operation has started, -1 on failure. */ int virDomainBlockRebase(virDomainPtr dom, const char *disk, const char *base, unsigned long bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, base=%s, bandwidth=%lu, flags=%x", disk, NULLSTR(base), bandwidth, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (flags & VIR_DOMAIN_BLOCK_REBASE_COPY) { virCheckNonNullArgGoto(base, error); } else if (flags & (VIR_DOMAIN_BLOCK_REBASE_SHALLOW | VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT | VIR_DOMAIN_BLOCK_REBASE_COPY_RAW | VIR_DOMAIN_BLOCK_REBASE_COPY_DEV)) { virReportInvalidArg(flags, "%s", _("use of flags requires a copy job")); goto error; } if (conn->driver->domainBlockRebase) { int ret; ret = conn->driver->domainBlockRebase(dom, disk, base, bandwidth, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockCopy: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @destxml: XML description of the copy destination * @params: Pointer to block copy parameter objects, or NULL * @nparams: Number of block copy parameters (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainBlockCopyFlags * * Copy the guest-visible contents of a disk image to a new file described * by @destxml. The destination XML has a top-level element of <disk>, and * resembles what is used when hot-plugging a disk via virDomainAttachDevice(), * except that only sub-elements related to describing the new host resource * are necessary (sub-elements related to the guest view, such as <target>, * are ignored). It is strongly recommended to include a <driver type='...'/> * format designation for the destination, to avoid the potential of any * security problem that might be caused by probing a file for its format. * * This command starts a long-running copy. By default, the copy will pull * the entire source chain into the destination file, but if @flags also * contains VIR_DOMAIN_BLOCK_COPY_SHALLOW, then only the top of the source * chain will be copied (the source and destination have a common backing * file). The format of the destination file is controlled by the <driver> * sub-element of the XML. The destination will be created unless the * VIR_DOMAIN_BLOCK_COPY_REUSE_EXT flag is present stating that the file * was pre-created with the correct format and metadata and sufficient * size to hold the copy. In case the VIR_DOMAIN_BLOCK_COPY_SHALLOW flag * is used the pre-created file has to exhibit the same guest visible contents * as the backing file of the original image. This allows a management app to * pre-create files with relative backing file names, rather than the default * of absolute backing file names. * * A copy job has two parts; in the first phase, the source is copied into * the destination, and the job can only be canceled by reverting to the * source file; progress in this phase can be tracked via the * virDomainBlockJobInfo() command, with a job type of * VIR_DOMAIN_BLOCK_JOB_TYPE_COPY. The job transitions to the second * phase when the job info states cur == end, and remains alive to mirror * all further changes to both source and destination. The user must * call virDomainBlockJobAbort() to end the mirroring while choosing * whether to revert to source or pivot to the destination. An event is * issued when the job ends, and depending on the hypervisor, an event may * also be issued when the job transitions from pulling to mirroring. If * the job is aborted, a new job will have to start over from the beginning * of the first phase. * * Some hypervisors will restrict certain actions, such as virDomainSave() * or virDomainDetachDevice(), while a copy job is active; they may * also restrict a copy job to transient domains. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or the device target shorthand (the * <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * The @params and @nparams arguments can be used to set hypervisor-specific * tuning parameters, such as maximum bandwidth or granularity. For a * parameter that the hypervisor understands, explicitly specifying 0 * behaves the same as omitting the parameter, to use the hypervisor * default; however, omitting a parameter is less likely to fail. * * This command is a superset of the older virDomainBlockRebase() when used * with the VIR_DOMAIN_BLOCK_REBASE_COPY flag, and offers better control * over the destination format, the ability to copy to a destination that * is not a local file, and the possibility of additional tuning parameters. * * Returns 0 if the operation has started, -1 on failure. */ int virDomainBlockCopy(virDomainPtr dom, const char *disk, const char *destxml, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, destxml=%s, params=%p, nparams=%d, flags=%x", disk, destxml, params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); virCheckNonNullArgGoto(destxml, error); virCheckNonNegativeArgGoto(nparams, error); if (nparams) virCheckNonNullArgGoto(params, error); if (conn->driver->domainBlockCopy) { int ret; ret = conn->driver->domainBlockCopy(dom, disk, destxml, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainBlockCommit: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @base: path to backing file to merge into, or device shorthand, * or NULL for default * @top: path to file within backing chain that contains data to be merged, * or device shorthand, or NULL to merge all possible data * @bandwidth: (optional) specify bandwidth limit; flags determine the unit * @flags: bitwise-OR of virDomainBlockCommitFlags * * Commit changes that were made to temporary top-level files within a disk * image backing file chain into a lower-level base file. In other words, * take all the difference between @base and @top, and update @base to contain * that difference; after the commit, any portion of the chain that previously * depended on @top will now depend on @base, and all files after @base up * to and including @top will now be invalidated. A typical use of this * command is to reduce the length of a backing file chain after taking an * external disk snapshot. To move data in the opposite direction, see * virDomainBlockPull(). * * This command starts a long-running commit block job, whose status may * be tracked by virDomainBlockJobInfo() with a job type of * VIR_DOMAIN_BLOCK_JOB_TYPE_COMMIT, and the operation can be aborted with * virDomainBlockJobAbort(). When finished, an asynchronous event is * raised to indicate the final status, and the job no longer exists. If * the job is aborted, it is up to the hypervisor whether starting a new * job will resume from the same point, or start over. * * As a special case, if @top is the active image (or NULL), and @flags * includes VIR_DOMAIN_BLOCK_COMMIT_ACTIVE, the block job will have a type * of VIR_DOMAIN_BLOCK_JOB_TYPE_ACTIVE_COMMIT, and operates in two phases. * In the first phase, the contents are being committed into @base, and the * job can only be canceled. The job transitions to the second phase when * the job info states cur == end, and remains alive to keep all further * changes to @top synchronized into @base; an event with status * VIR_DOMAIN_BLOCK_JOB_READY is also issued to mark the job transition. * Once in the second phase, the user must choose whether to cancel the job * (keeping @top as the active image, but now containing only the changes * since the time the job ended) or to pivot the job (adjusting to @base as * the active image, and invalidating @top). * * Be aware that this command may invalidate files even if it is aborted; * the user is cautioned against relying on the contents of invalidated * intermediate files such as @top (when @top is not the active image) * without manually rebasing those files to use a backing file of a * read-only copy of @base prior to the point where the commit operation * was started (and such a rebase cannot be safely done until the commit * has successfully completed). However, the domain itself will not have * any issues; the active layer remains valid throughout the entire commit * operation. * * Some hypervisors may support a shortcut where if @flags contains * VIR_DOMAIN_BLOCK_COMMIT_DELETE, then this command will unlink all files * that were invalidated, after the commit successfully completes. * * If @flags contains VIR_DOMAIN_BLOCK_COMMIT_RELATIVE, the name recorded * into the overlay of the @top image (if there is such image) as the * path to the new backing file will be kept relative to other images. * The operation will fail if libvirt can't infer the name. * * By default, if @base is NULL, the commit target will be the bottom of * the backing chain; if @flags contains VIR_DOMAIN_BLOCK_COMMIT_SHALLOW, * then the immediate backing file of @top will be used instead. If @top * is NULL, the active image at the top of the chain will be used. Some * hypervisors place restrictions on how much can be committed, and might * fail if @base is not the immediate backing file of @top, or if @top is * the active layer in use by a running domain but @flags did not include * VIR_DOMAIN_BLOCK_COMMIT_ACTIVE, or if @top is not the top-most file; * restrictions may differ for online vs. offline domains. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or the device target shorthand (the * <target dev='...'/> sub-element, such as "vda"). Valid names * can be found by calling virDomainGetXMLDesc() and inspecting * elements within //domain/devices/disk. * * The @base and @top parameters can be either paths to files within the * backing chain, or the device target shorthand (the <target dev='...'/> * sub-element, such as "vda") followed by an index to the backing chain * enclosed in square brackets. Backing chain indexes can be found by * inspecting //disk//backingStore/@index in the domain XML. Thus, for * example, "vda[3]" refers to the backing store with index equal to "3" * in the chain of disk "vda". * * The maximum bandwidth that will be used to do the commit can be * specified with the @bandwidth parameter. If set to 0, there is no * limit. If @flags includes VIR_DOMAIN_BLOCK_COMMIT_BANDWIDTH_BYTES, * @bandwidth is in bytes/second; otherwise, it is in MiB/second. * Values larger than 2^52 bytes/sec may be rejected due to overflow * considerations based on the word size of both client and server, * and values larger than 2^31 bytes/sec may cause overflow problems * if later queried by virDomainGetBlockJobInfo() without scaling. * Hypervisors may further restrict the range of valid bandwidth * values. Some hypervisors do not support this feature and will * return an error if bandwidth is not 0; in this case, it might still * be possible for a later call to virDomainBlockJobSetSpeed() to * succeed. The actual speed can be determined with * virDomainGetBlockJobInfo(). * * Returns 0 if the operation has started, -1 on failure. */ int virDomainBlockCommit(virDomainPtr dom, const char *disk, const char *base, const char *top, unsigned long bandwidth, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, base=%s, top=%s, bandwidth=%lu, flags=%x", disk, NULLSTR(base), NULLSTR(top), bandwidth, flags); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); if (conn->driver->domainBlockCommit) { int ret; ret = conn->driver->domainBlockCommit(dom, disk, base, top, bandwidth, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainOpenGraphics: * @dom: pointer to domain object * @idx: index of graphics config to open * @fd: file descriptor to attach graphics to * @flags: bitwise-OR of virDomainOpenGraphicsFlags * * This will attempt to connect the file descriptor @fd, to * the graphics backend of @dom. If @dom has multiple graphics * backends configured, then @idx will determine which one is * opened, starting from @idx 0. * * To disable any authentication, pass the VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH * constant for @flags. * * The caller should use an anonymous socketpair to open * @fd before invocation. * * This method can only be used when connected to a local * libvirt hypervisor, over a UNIX domain socket. Attempts * to use this method over a TCP connection will always fail * * Returns 0 on success, -1 on failure */ int virDomainOpenGraphics(virDomainPtr dom, unsigned int idx, int fd, unsigned int flags) { struct stat sb; VIR_DOMAIN_DEBUG(dom, "idx=%u, fd=%d, flags=%x", idx, fd, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNegativeArgGoto(fd, error); if (fstat(fd, &sb) < 0) { virReportSystemError(errno, _("Unable to access file descriptor %d"), fd); goto error; } if (!S_ISSOCK(sb.st_mode)) { virReportInvalidArg(fd, _("fd %d must be a socket"), fd); goto error; } virCheckReadOnlyGoto(dom->conn->flags, error); if (!VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn, VIR_DRV_FEATURE_FD_PASSING)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("fd passing is not supported by this connection")); goto error; } if (dom->conn->driver->domainOpenGraphics) { int ret; ret = dom->conn->driver->domainOpenGraphics(dom, idx, fd, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainOpenGraphicsFD: * @dom: pointer to domain object * @idx: index of graphics config to open * @flags: bitwise-OR of virDomainOpenGraphicsFlags * * This will create a socket pair connected to the graphics backend of @dom. * One end of the socket will be returned on success, and the other end is * handed to the hypervisor. * If @dom has multiple graphics backends configured, then @idx will determine * which one is opened, starting from @idx 0. * * To disable any authentication, pass the VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH * constant for @flags. * * This method can only be used when connected to a local * libvirt hypervisor, over a UNIX domain socket. Attempts * to use this method over a TCP connection will always fail. * * Returns an fd on success, -1 on failure */ int virDomainOpenGraphicsFD(virDomainPtr dom, unsigned int idx, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "idx=%u, flags=%x", idx, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); if (!VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn, VIR_DRV_FEATURE_FD_PASSING)) { virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s", _("fd passing is not supported by this connection")); goto error; } if (dom->conn->driver->domainOpenGraphicsFD) { int ret; ret = dom->conn->driver->domainOpenGraphicsFD(dom, idx, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainSetBlockIoTune: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @params: Pointer to blkio parameter objects * @nparams: Number of blkio parameters (this value can be the same or * less than the number of parameters supported) * @flags: bitwise-OR of virDomainModificationImpact * * Change all or a subset of the per-device block IO tunables. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or the device target shorthand (the <target * dev='...'/> sub-element, such as "xvda"). Valid names can be found * by calling virDomainGetXMLDesc() and inspecting elements * within //domain/devices/disk. * * Returns -1 in case of error, 0 in case of success. */ int virDomainSetBlockIoTune(virDomainPtr dom, const char *disk, virTypedParameterPtr params, int nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=%x", disk, params, nparams, flags); VIR_TYPED_PARAMS_DEBUG(params, nparams); virResetLastError(); virCheckDomainReturn(dom, -1); conn = dom->conn; virCheckReadOnlyGoto(conn->flags, error); virCheckNonNullArgGoto(disk, error); virCheckPositiveArgGoto(nparams, error); virCheckNonNullArgGoto(params, error); if (virTypedParameterValidateSet(dom->conn, params, nparams) < 0) goto error; if (conn->driver->domainSetBlockIoTune) { int ret; ret = conn->driver->domainSetBlockIoTune(dom, disk, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetBlockIoTune: * @dom: pointer to domain object * @disk: path to the block device, or device shorthand * @params: Pointer to blkio parameter object * (return value, allocated by the caller) * @nparams: Pointer to number of blkio parameters * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags * * Get all block IO tunable parameters for a given device. On input, * @nparams gives the size of the @params array; on output, @nparams * gives how many slots were filled with parameter information, which * might be less but will not exceed the input value. * * As a special case, calling with @params as NULL and @nparams as 0 * on input will cause @nparams on output to contain the number of * parameters supported by the hypervisor, either for the given @disk * (note that block devices of different types might support different * parameters), or if @disk is NULL, for all possible disks. The * caller should then allocate @params array, * i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API * again. See virDomainGetMemoryParameters() for more details. * * The @disk parameter is either an unambiguous source name of the * block device (the <source file='...'/> sub-element, such as * "/path/to/image"), or the device target shorthand (the <target * dev='...'/> sub-element, such as "xvda"). Valid names can be found * by calling virDomainGetXMLDesc() and inspecting elements * within //domain/devices/disk. This parameter cannot be NULL * unless @nparams is 0 on input. * * Returns -1 in case of error, 0 in case of success. */ int virDomainGetBlockIoTune(virDomainPtr dom, const char *disk, virTypedParameterPtr params, int *nparams, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=%x", NULLSTR(disk), params, (nparams) ? *nparams : -1, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(nparams, error); virCheckNonNegativeArgGoto(*nparams, error); if (*nparams != 0) { virCheckNonNullArgGoto(params, error); virCheckNonNullArgGoto(disk, error); } if (VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE, VIR_DOMAIN_AFFECT_CONFIG, error); conn = dom->conn; if (conn->driver->domainGetBlockIoTune) { int ret; ret = conn->driver->domainGetBlockIoTune(dom, disk, params, nparams, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetCPUStats: * @domain: domain to query * @params: array to populate on output * @nparams: number of parameters per cpu * @start_cpu: which cpu to start with, or -1 for summary * @ncpus: how many cpus to query * @flags: bitwise-OR of virTypedParameterFlags * * Get statistics relating to CPU usage attributable to a single * domain (in contrast to the statistics returned by * virNodeGetCPUStats() for all processes on the host). @dom * must be running (an inactive domain has no attributable cpu * usage). On input, @params must contain at least @nparams * @ncpus * entries, allocated by the caller. * * If @start_cpu is -1, then @ncpus must be 1, and the returned * results reflect the statistics attributable to the entire * domain (such as user and system time for the process as a * whole). Otherwise, @start_cpu represents which cpu to start * with, and @ncpus represents how many consecutive processors to * query, with statistics attributable per processor (such as * per-cpu usage). If @ncpus is larger than the number of cpus * available to query, then the trailing part of the array will * be unpopulated. * * The remote driver imposes a limit of 128 @ncpus and 16 @nparams; * the number of parameters per cpu should not exceed 16, but if you * have a host with more than 128 CPUs, your program should split * the request into multiple calls. * * As special cases, if @params is NULL and @nparams is 0 and * @ncpus is 1, and the return value will be how many * statistics are available for the given @start_cpu. This number * may be different for @start_cpu of -1 than for any non-negative * value, but will be the same for all non-negative @start_cpu. * Likewise, if @params is NULL and @nparams is 0 and @ncpus is 0, * the number of cpus available to query is returned. From the * host perspective, this would typically match the cpus member * of virNodeGetInfo(), but might be less due to host cpu hotplug. * * For now, @flags is unused, and the statistics all relate to the * usage from the host perspective. It is possible that a future * version will support a flag that queries the cpu usage from the * guest's perspective, where the maximum cpu to query would be * related to virDomainGetVcpusFlags() rather than virNodeGetInfo(). * An individual guest vcpu cannot be reliably mapped back to a * specific host cpu unless a single-processor vcpu pinning was used, * but when @start_cpu is -1, any difference in usage between a host * and guest perspective would serve as a measure of hypervisor overhead. * * Typical use sequence is below. * * getting total stats: set start_cpu as -1, ncpus 1 * * virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0); // nparams * params = calloc(nparams, sizeof(virTypedParameter)) * virDomainGetCPUStats(dom, params, nparams, -1, 1, 0); // total stats. * * getting per-cpu stats: * * virDomainGetCPUStats(dom, NULL, 0, 0, 0, 0); // ncpus * virDomainGetCPUStats(dom, NULL, 0, 0, 1, 0); // nparams * params = calloc(ncpus * nparams, sizeof(virTypedParameter)); * virDomainGetCPUStats(dom, params, nparams, 0, ncpus, 0); // per-cpu stats * * Returns -1 on failure, or the number of statistics that were * populated per cpu on success (this will be less than the total * number of populated @params, unless @ncpus was 1; and may be * less than @nparams). The populated parameters start at each * stride of @nparams, which means the results may be discontiguous; * any unpopulated parameters will be zeroed on success (this includes * skipped elements if @nparams is too large, and tail elements if * @ncpus is too large). The caller is responsible for freeing any * returned string parameters. */ int virDomainGetCPUStats(virDomainPtr domain, virTypedParameterPtr params, unsigned int nparams, int start_cpu, unsigned int ncpus, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, start_cpu=%d, ncpus=%u, flags=%x", params, nparams, start_cpu, ncpus, flags); virResetLastError(); virCheckDomainReturn(domain, -1); conn = domain->conn; /* Special cases: * start_cpu must be non-negative, or else -1 * if start_cpu is -1, ncpus must be 1 * params == NULL must match nparams == 0 * ncpus must be non-zero unless params == NULL * nparams * ncpus must not overflow (RPC may restrict it even more) */ if (start_cpu == -1) { if (ncpus != 1) { virReportInvalidArg(start_cpu, "%s", _("ncpus must be 1 when start_cpu is -1")); goto error; } } else { virCheckNonNegativeArgGoto(start_cpu, error); } if (nparams) virCheckNonNullArgGoto(params, error); else virCheckNullArgGoto(params, error); if (ncpus == 0) virCheckNullArgGoto(params, error); if (nparams && ncpus > UINT_MAX / nparams) { virReportError(VIR_ERR_OVERFLOW, _("input too large: %u * %u"), nparams, ncpus); goto error; } if (VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn, VIR_DRV_FEATURE_TYPED_PARAM_STRING)) flags |= VIR_TYPED_PARAM_STRING_OKAY; if (conn->driver->domainGetCPUStats) { int ret; ret = conn->driver->domainGetCPUStats(domain, params, nparams, start_cpu, ncpus, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return -1; } /** * virDomainGetDiskErrors: * @dom: a domain object * @errors: array to populate on output * @maxerrors: size of @errors array * @flags: extra flags; not used yet, so callers should always pass 0 * * The function populates @errors array with all disks that encountered an * I/O error. Disks with no error will not be returned in the @errors array. * Each disk is identified by its target (the dev attribute of target * subelement in domain XML), such as "vda", and accompanied with the error * that was seen on it. The caller is also responsible for calling free() * on each disk name returned. * * In a special case when @errors is NULL and @maxerrors is 0, the function * returns preferred size of @errors that the caller should use to get all * disk errors. * * Since calling virDomainGetDiskErrors(dom, NULL, 0, 0) to get preferred size * of @errors array and getting the errors are two separate operations, new * disks may be hotplugged to the domain and new errors may be encountered * between the two calls. Thus, this function may not return all disk errors * because the supplied array is not large enough. Such errors may, however, * be detected by listening to domain events. * * Returns number of disks with errors filled in the @errors array or -1 on * error. */ int virDomainGetDiskErrors(virDomainPtr dom, virDomainDiskErrorPtr errors, unsigned int maxerrors, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "errors=%p, maxerrors=%u, flags=%x", errors, maxerrors, flags); virResetLastError(); virCheckDomainReturn(dom, -1); if (maxerrors) virCheckNonNullArgGoto(errors, error); else virCheckNullArgGoto(errors, error); if (dom->conn->driver->domainGetDiskErrors) { int ret = dom->conn->driver->domainGetDiskErrors(dom, errors, maxerrors, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetHostname: * @domain: a domain object * @flags: extra flags; not used yet, so callers should always pass 0 * * Get the hostname for that domain. * * Dependent on hypervisor used, this may require a guest agent to be * available. * * Returns the hostname which must be freed by the caller, or * NULL if there was an error. */ char * virDomainGetHostname(virDomainPtr domain, unsigned int flags) { virConnectPtr conn; VIR_DOMAIN_DEBUG(domain, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(domain, NULL); conn = domain->conn; if (conn->driver->domainGetHostname) { char *ret; ret = conn->driver->domainGetHostname(domain, flags); if (!ret) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(domain->conn); return NULL; } /** * virDomainFSTrim: * @dom: a domain object * @mountPoint: which mount point to trim * @minimum: Minimum contiguous free range to discard in bytes * @flags: extra flags, not used yet, so callers should always pass 0 * * Calls FITRIM within the guest (hence guest agent may be * required depending on hypervisor used). Either call it on each * mounted filesystem (@mountPoint is NULL) or just on specified * @mountPoint. @minimum hints that free ranges smaller than this * may be ignored (this is a hint and the guest may not respect * it). By increasing this value, the fstrim operation will * complete more quickly for filesystems with badly fragmented * free space, although not all blocks will be discarded. * If @minimum is not zero, the command may fail. * * Returns 0 on success, -1 otherwise. */ int virDomainFSTrim(virDomainPtr dom, const char *mountPoint, unsigned long long minimum, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "mountPoint=%s, minimum=%llu, flags=%x", mountPoint, minimum, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); if (dom->conn->driver->domainFSTrim) { int ret = dom->conn->driver->domainFSTrim(dom, mountPoint, minimum, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainFSFreeze: * @dom: a domain object * @mountpoints: list of mount points to be frozen * @nmountpoints: the number of mount points specified in @mountpoints * @flags: extra flags; not used yet, so callers should always pass 0 * * Freeze specified filesystems within the guest (hence guest agent * may be required depending on hypervisor used). If @mountpoints is NULL and * @nmountpoints is 0, every mounted filesystem on the guest is frozen. * In some environments (e.g. QEMU guest with guest agent which doesn't * support mountpoints argument), @mountpoints may need to be NULL. * * Returns the number of frozen filesystems on success, -1 otherwise. */ int virDomainFSFreeze(virDomainPtr dom, const char **mountpoints, unsigned int nmountpoints, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "mountpoints=%p, nmountpoints=%d, flags=%x", mountpoints, nmountpoints, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); if (nmountpoints) virCheckNonNullArgGoto(mountpoints, error); else virCheckNullArgGoto(mountpoints, error); if (dom->conn->driver->domainFSFreeze) { int ret = dom->conn->driver->domainFSFreeze( dom, mountpoints, nmountpoints, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainFSThaw: * @dom: a domain object * @mountpoints: list of mount points to be thawed * @nmountpoints: the number of mount points specified in @mountpoints * @flags: extra flags; not used yet, so callers should always pass 0 * * Thaw specified filesystems within the guest. If @mountpoints is NULL and * @nmountpoints is 0, every mounted filesystem on the guest is thawed. * In some drivers (e.g. QEMU driver), @mountpoints may need to be NULL. * * Returns the number of thawed filesystems on success, -1 otherwise. */ int virDomainFSThaw(virDomainPtr dom, const char **mountpoints, unsigned int nmountpoints, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "flags=%x", flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); if (nmountpoints) virCheckNonNullArgGoto(mountpoints, error); else virCheckNullArgGoto(mountpoints, error); if (dom->conn->driver->domainFSThaw) { int ret = dom->conn->driver->domainFSThaw( dom, mountpoints, nmountpoints, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainGetTime: * @dom: a domain object * @seconds: domain's time in seconds * @nseconds: the nanoscond part of @seconds * @flags: extra flags; not used yet, so callers should always pass 0 * * Extract information about guest time and store it into * @seconds and @nseconds. The @seconds represents the number of * seconds since the UNIX Epoch of 1970-01-01 00:00:00 in UTC. * * Please note that some hypervisors may require guest agent to * be configured and running in order to run this API. * * Returns 0 on success, -1 otherwise. */ int virDomainGetTime(virDomainPtr dom, long long *seconds, unsigned int *nseconds, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "seconds=%p, nseconds=%p, flags=%x", seconds, nseconds, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); if (dom->conn->driver->domainGetTime) { int ret = dom->conn->driver->domainGetTime(dom, seconds, nseconds, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainSetTime: * @dom: a domain object * @seconds: time to set * @nseconds: the nanosecond part of @seconds * @flags: bitwise-OR of virDomainSetTimeFlags * * When a domain is suspended or restored from a file the * domain's OS has no idea that there was a big gap in the time. * Depending on how long the gap was, NTP might not be able to * resynchronize the guest. * * This API tries to set guest time to the given value. The time * to set (@seconds and @nseconds) should be in seconds relative * to the Epoch of 1970-01-01 00:00:00 in UTC. * * Please note that some hypervisors may require guest agent to * be configured and running in order to be able to run this API. * * Returns 0 on success, -1 otherwise. */ int virDomainSetTime(virDomainPtr dom, long long seconds, unsigned int nseconds, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "seconds=%lld, nseconds=%u, flags=%x", seconds, nseconds, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); if (dom->conn->driver->domainSetTime) { int ret = dom->conn->driver->domainSetTime(dom, seconds, nseconds, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainSetUserPassword: * @dom: a domain object * @user: the username that will get a new password * @password: the password to set * @flags: bitwise-OR of virDomainSetUserPasswordFlags * * Sets the @user password to the value specified by @password. * If @flags contain VIR_DOMAIN_PASSWORD_ENCRYPTED, the password * is assumed to be encrypted by the method required by the guest OS. * * Please note that some hypervisors may require guest agent to * be configured and running in order to be able to run this API. * * Returns 0 on success, -1 otherwise. */ int virDomainSetUserPassword(virDomainPtr dom, const char *user, const char *password, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "user=%s, password=%s, flags=%x", NULLSTR(user), NULLSTR(password), flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); virCheckNonNullArgGoto(user, error); virCheckNonNullArgGoto(password, error); if (dom->conn->driver->domainSetUserPassword) { int ret = dom->conn->driver->domainSetUserPassword(dom, user, password, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virConnectGetDomainCapabilities: * @conn: pointer to the hypervisor connection * @emulatorbin: path to emulator * @arch: domain architecture * @machine: machine type * @virttype: virtualization type * @flags: extra flags; not used yet, so callers should always pass 0 * * Prior creating a domain (for instance via virDomainCreateXML * or virDomainDefineXML) it may be suitable to know what the * underlying emulator and/or libvirt is capable of. For * instance, if host, libvirt and qemu is capable of VFIO * passthrough and so on. * * Returns NULL in case of error or an XML string * defining the capabilities. */ char * virConnectGetDomainCapabilities(virConnectPtr conn, const char *emulatorbin, const char *arch, const char *machine, const char *virttype, unsigned int flags) { VIR_DEBUG("conn=%p, emulatorbin=%s, arch=%s, " "machine=%s, virttype=%s, flags=%x", conn, NULLSTR(emulatorbin), NULLSTR(arch), NULLSTR(machine), NULLSTR(virttype), flags); virResetLastError(); virCheckConnectReturn(conn, NULL); if (conn->driver->connectGetDomainCapabilities) { char *ret; ret = conn->driver->connectGetDomainCapabilities(conn, emulatorbin, arch, machine, virttype, flags); if (!ret) goto error; VIR_DEBUG("conn=%p, ret=%s", conn, ret); return ret; } virReportUnsupportedError(); error: virDispatchError(conn); return NULL; } /** * virConnectGetAllDomainStats: * @conn: pointer to the hypervisor connection * @stats: stats to return, binary-OR of virDomainStatsTypes * @retStats: Pointer that will be filled with the array of returned stats * @flags: extra flags; binary-OR of virConnectGetAllDomainStatsFlags * * Query statistics for all domains on a given connection. * * Report statistics of various parameters for a running VM according to @stats * field. The statistics are returned as an array of structures for each queried * domain. The structure contains an array of typed parameters containing the * individual statistics. The typed parameter name for each statistic field * consists of a dot-separated string containing name of the requested group * followed by a group specific description of the statistic value. * * The statistic groups are enabled using the @stats parameter which is a * binary-OR of enum virDomainStatsTypes. The following groups are available * (although not necessarily implemented for each hypervisor): * * VIR_DOMAIN_STATS_STATE: Return domain state and reason for entering that * state. The typed parameter keys are in this format: * "state.state" - state of the VM, returned as int from virDomainState enum * "state.reason" - reason for entering given state, returned as int from * virDomain*Reason enum corresponding to given state. * * VIR_DOMAIN_STATS_CPU_TOTAL: Return CPU statistics and usage information. * The typed parameter keys are in this format: * "cpu.time" - total cpu time spent for this domain in nanoseconds * as unsigned long long. * "cpu.user" - user cpu time spent in nanoseconds as unsigned long long. * "cpu.system" - system cpu time spent in nanoseconds as unsigned long long. * * VIR_DOMAIN_STATS_BALLOON: Return memory balloon device information. * The typed parameter keys are in this format: * "balloon.current" - the memory in kiB currently used * as unsigned long long. * "balloon.maximum" - the maximum memory in kiB allowed * as unsigned long long. * * VIR_DOMAIN_STATS_VCPU: Return virtual CPU statistics. * Due to VCPU hotplug, the vcpu.<num>.* array could be sparse. * The actual size of the array corresponds to "vcpu.current". * The array size will never exceed "vcpu.maximum". * The typed parameter keys are in this format: * "vcpu.current" - current number of online virtual CPUs as unsigned int. * "vcpu.maximum" - maximum number of online virtual CPUs as unsigned int. * "vcpu.<num>.state" - state of the virtual CPU <num>, as int * from virVcpuState enum. * "vcpu.<num>.time" - virtual cpu time spent by virtual CPU <num> * as unsigned long long. * * VIR_DOMAIN_STATS_INTERFACE: Return network interface statistics. * The typed parameter keys are in this format: * "net.count" - number of network interfaces on this domain * as unsigned int. * "net.<num>.name" - name of the interface <num> as string. * "net.<num>.rx.bytes" - bytes received as unsigned long long. * "net.<num>.rx.pkts" - packets received as unsigned long long. * "net.<num>.rx.errs" - receive errors as unsigned long long. * "net.<num>.rx.drop" - receive packets dropped as unsigned long long. * "net.<num>.tx.bytes" - bytes transmitted as unsigned long long. * "net.<num>.tx.pkts" - packets transmitted as unsigned long long. * "net.<num>.tx.errs" - transmission errors as unsigned long long. * "net.<num>.tx.drop" - transmit packets dropped as unsigned long long. * * VIR_DOMAIN_STATS_BLOCK: Return block devices statistics. By default, * this information is limited to the active layer of each <disk> of the * domain (where block.count is equal to the number of disks), but adding * VIR_CONNECT_GET_ALL_DOMAINS_STATS_BACKING to @flags will expand the * array to cover backing chains (block.count corresponds to the number * of host resources used together to provide the guest disks). * The typed parameter keys are in this format: * "block.count" - number of block devices in the subsequent list, * as unsigned int. * "block.<num>.name" - name of the block device <num> as string. * matches the target name (vda/sda/hda) of the * block device. If the backing chain is listed, * this name is the same for all host resources tied * to the same guest device. * "block.<num>.backingIndex" - unsigned int giving the <backingStore> index, * only used when backing images are listed. * "block.<num>.path" - string describing the source of block device <num>, * if it is a file or block device (omitted for network * sources and drives with no media inserted). * "block.<num>.rd.reqs" - number of read requests as unsigned long long. * "block.<num>.rd.bytes" - number of read bytes as unsigned long long. * "block.<num>.rd.times" - total time (ns) spent on reads as * unsigned long long. * "block.<num>.wr.reqs" - number of write requests as unsigned long long. * "block.<num>.wr.bytes" - number of written bytes as unsigned long long. * "block.<num>.wr.times" - total time (ns) spent on writes as * unsigned long long. * "block.<num>.fl.reqs" - total flush requests as unsigned long long. * "block.<num>.fl.times" - total time (ns) spent on cache flushing as * unsigned long long. * "block.<num>.errors" - Xen only: the 'oo_req' value as * unsigned long long. * "block.<num>.allocation" - offset of the highest written sector * as unsigned long long. * "block.<num>.capacity" - logical size in bytes of the block device backing * image as unsigned long long. * "block.<num>.physical" - physical size in bytes of the container of the * backing image as unsigned long long. * * Note that entire stats groups or individual stat fields may be missing from * the output in case they are not supported by the given hypervisor, are not * applicable for the current state of the guest domain, or their retrieval * was not successful. * * Using 0 for @stats returns all stats groups supported by the given * hypervisor. * * Specifying VIR_CONNECT_GET_ALL_DOMAINS_STATS_ENFORCE_STATS as @flags makes * the function return error in case some of the stat types in @stats were * not recognized by the daemon. However, even with this flag, a hypervisor * may omit individual fields within a known group if the information is not * available; as an extreme example, a supported group may produce zero * fields for offline domains if the statistics are meaningful only for a * running domain. * * Similarly to virConnectListAllDomains, @flags can contain various flags to * filter the list of domains to provide stats for. * * VIR_CONNECT_GET_ALL_DOMAINS_STATS_ACTIVE selects online domains while * VIR_CONNECT_GET_ALL_DOMAINS_STATS_INACTIVE selects offline ones. * * VIR_CONNECT_GET_ALL_DOMAINS_STATS_PERSISTENT and * VIR_CONNECT_GET_ALL_DOMAINS_STATS_TRANSIENT allow to filter the list * according to their persistence. * * To filter the list of VMs by domain state @flags can contain * VIR_CONNECT_GET_ALL_DOMAINS_STATS_RUNNING, * VIR_CONNECT_GET_ALL_DOMAINS_STATS_PAUSED, * VIR_CONNECT_GET_ALL_DOMAINS_STATS_SHUTOFF and/or * VIR_CONNECT_GET_ALL_DOMAINS_STATS_OTHER for all other states. * * Returns the count of returned statistics structures on success, -1 on error. * The requested data are returned in the @retStats parameter. The returned * array should be freed by the caller. See virDomainStatsRecordListFree. */ int virConnectGetAllDomainStats(virConnectPtr conn, unsigned int stats, virDomainStatsRecordPtr **retStats, unsigned int flags) { int ret = -1; VIR_DEBUG("conn=%p, stats=0x%x, retStats=%p, flags=0x%x", conn, stats, retStats, flags); virResetLastError(); virCheckConnectReturn(conn, -1); virCheckNonNullArgGoto(retStats, cleanup); if (!conn->driver->connectGetAllDomainStats) { virReportUnsupportedError(); goto cleanup; } ret = conn->driver->connectGetAllDomainStats(conn, NULL, 0, stats, retStats, flags); cleanup: if (ret < 0) virDispatchError(conn); return ret; } /** * virDomainListGetStats: * @doms: NULL terminated array of domains * @stats: stats to return, binary-OR of virDomainStatsTypes * @retStats: Pointer that will be filled with the array of returned stats * @flags: extra flags; binary-OR of virConnectGetAllDomainStatsFlags * * Query statistics for domains provided by @doms. Note that all domains in * @doms must share the same connection. * * Report statistics of various parameters for a running VM according to @stats * field. The statistics are returned as an array of structures for each queried * domain. The structure contains an array of typed parameters containing the * individual statistics. The typed parameter name for each statistic field * consists of a dot-separated string containing name of the requested group * followed by a group specific description of the statistic value. * * The statistic groups are enabled using the @stats parameter which is a * binary-OR of enum virDomainStatsTypes. The stats groups are documented * in virConnectGetAllDomainStats. * * Using 0 for @stats returns all stats groups supported by the given * hypervisor. * * Specifying VIR_CONNECT_GET_ALL_DOMAINS_STATS_ENFORCE_STATS as @flags makes * the function return error in case some of the stat types in @stats were * not recognized by the daemon. However, even with this flag, a hypervisor * may omit individual fields within a known group if the information is not * available; as an extreme example, a supported group may produce zero * fields for offline domains if the statistics are meaningful only for a * running domain. * * Note that any of the domain list filtering flags in @flags may be rejected * by this function. * * Returns the count of returned statistics structures on success, -1 on error. * The requested data are returned in the @retStats parameter. The returned * array should be freed by the caller. See virDomainStatsRecordListFree. * Note that the count of returned stats may be less than the domain count * provided via @doms. */ int virDomainListGetStats(virDomainPtr *doms, unsigned int stats, virDomainStatsRecordPtr **retStats, unsigned int flags) { virConnectPtr conn = NULL; virDomainPtr *nextdom = doms; unsigned int ndoms = 0; int ret = -1; VIR_DEBUG("doms=%p, stats=0x%x, retStats=%p, flags=0x%x", doms, stats, retStats, flags); virResetLastError(); virCheckNonNullArgGoto(doms, cleanup); virCheckNonNullArgGoto(retStats, cleanup); if (!*doms) { virReportError(VIR_ERR_INVALID_ARG, _("doms array in %s must contain at least one domain"), __FUNCTION__); goto cleanup; } conn = doms[0]->conn; virCheckConnectReturn(conn, -1); if (!conn->driver->connectGetAllDomainStats) { virReportUnsupportedError(); goto cleanup; } while (*nextdom) { virDomainPtr dom = *nextdom; virCheckDomainGoto(dom, cleanup); if (dom->conn != conn) { virReportError(VIR_ERR_INVALID_ARG, "%s", _("domains in 'doms' array must belong to a " "single connection")); goto cleanup; } ndoms++; nextdom++; } ret = conn->driver->connectGetAllDomainStats(conn, doms, ndoms, stats, retStats, flags); cleanup: if (ret < 0) virDispatchError(conn); return ret; } /** * virDomainStatsRecordListFree: * @stats: NULL terminated array of virDomainStatsRecords to free * * Convenience function to free a list of domain stats returned by * virDomainListGetStats and virConnectGetAllDomainStats. */ void virDomainStatsRecordListFree(virDomainStatsRecordPtr *stats) { virDomainStatsRecordPtr *next; if (!stats) return; for (next = stats; *next; next++) { virTypedParamsFree((*next)->params, (*next)->nparams); virDomainFree((*next)->dom); VIR_FREE(*next); } VIR_FREE(stats); } /** * virDomainGetFSInfo: * @dom: a domain object * @info: a pointer to a variable to store an array of mount points information * @flags: extra flags; not used yet, so callers should always pass 0 * * Get a list of mapping information for each mounted file systems within the * specified guest and the disks. * * Returns the number of returned mount points, or -1 in case of error. * On success, the array of the information is stored into @info. The caller is * responsible for calling virDomainFSInfoFree() on each array element, then * calling free() on @info. On error, @info is set to NULL. */ int virDomainGetFSInfo(virDomainPtr dom, virDomainFSInfoPtr **info, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "info=%p, flags=%x", info, flags); virResetLastError(); virCheckDomainReturn(dom, -1); virCheckReadOnlyGoto(dom->conn->flags, error); virCheckNonNullArgGoto(info, error); *info = NULL; if (dom->conn->driver->domainGetFSInfo) { int ret = dom->conn->driver->domainGetFSInfo(dom, info, flags); if (ret < 0) goto error; return ret; } virReportUnsupportedError(); error: virDispatchError(dom->conn); return -1; } /** * virDomainFSInfoFree: * @info: pointer to a FSInfo object * * Frees all the memory occupied by @info. */ void virDomainFSInfoFree(virDomainFSInfoPtr info) { size_t i; if (!info) return; VIR_FREE(info->mountpoint); VIR_FREE(info->name); VIR_FREE(info->fstype); for (i = 0; i < info->ndevAlias; i++) VIR_FREE(info->devAlias[i]); VIR_FREE(info->devAlias); VIR_FREE(info); } /** * virDomainInterfaceAddresses: * @dom: domain object * @ifaces: pointer to an array of pointers pointing to interface objects * @source: one of the virDomainInterfaceAddressesSource constants * @flags: currently unused, pass zero * * Return a pointer to the allocated array of pointers to interfaces * present in given domain along with their IP and MAC addresses. Note that * single interface can have multiple or even 0 IP addresses. * * This API dynamically allocates the virDomainInterfacePtr struct based on * how many interfaces domain @dom has, usually there's 1:1 correlation. The * count of the interfaces is returned as the return value. * * If @source is VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE, the DHCP lease * file associated with any virtual networks will be examined to obtain * the interface addresses. This only returns data for interfaces which * are connected to virtual networks managed by libvirt. * * If @source is VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT, a configured * guest agent is needed for successful return from this API. Moreover, if * guest agent is used then the interface name is the one seen by guest OS. * To match such interface with the one from @dom XML use MAC address or IP * range. * * @ifaces->name and @ifaces->hwaddr are never NULL. * * The caller *must* free @ifaces when no longer needed. Usual use case * looks like this: * * virDomainInterfacePtr *ifaces = NULL; * int ifaces_count = 0; * size_t i, j; * virDomainPtr dom = ... obtain a domain here ...; * * if ((ifaces_count = virDomainInterfaceAddresses(dom, &ifaces, * VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE)) < 0) * goto cleanup; * * ... do something with returned values, for example: * for (i = 0; i < ifaces_count; i++) { * printf("name: %s", ifaces[i]->name); * if (ifaces[i]->hwaddr) * printf(" hwaddr: %s", ifaces[i]->hwaddr); * * for (j = 0; j < ifaces[i]->naddrs; j++) { * virDomainIPAddressPtr ip_addr = ifaces[i]->addrs + j; * printf("[addr: %s prefix: %d type: %d]", * ip_addr->addr, ip_addr->prefix, ip_addr->type); * } * printf("\n"); * } * * cleanup: * if (ifaces && ifaces_count > 0) * for (i = 0; i < ifaces_count; i++) * virDomainInterfaceFree(ifaces[i]); * free(ifaces); * * Returns the number of interfaces on success, -1 in case of error. */ int virDomainInterfaceAddresses(virDomainPtr dom, virDomainInterfacePtr **ifaces, unsigned int source, unsigned int flags) { VIR_DOMAIN_DEBUG(dom, "ifaces=%p, source=%d, flags=%x", ifaces, source, flags); virResetLastError(); if (ifaces) *ifaces = NULL; virCheckDomainReturn(dom, -1); virCheckNonNullArgGoto(ifaces, error); if (source == VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT) virCheckReadOnlyGoto(dom->conn->flags, error); if (dom->conn->driver->domainInterfaceAddresses) { int ret; ret = dom->conn->driver->domainInterfaceAddresses(dom, ifaces, source, flags); if (ret < 0) goto error; return ret; } virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__); error: virDispatchError(dom->conn); return -1; } /** * virDomainInterfaceFree: * @iface: an interface object * * Free the interface object. The data structure is * freed and should not be used thereafter. If @iface * is NULL, then this method has no effect. */ void virDomainInterfaceFree(virDomainInterfacePtr iface) { size_t i; if (!iface) return; VIR_FREE(iface->name); VIR_FREE(iface->hwaddr); for (i = 0; i < iface->naddrs; i++) VIR_FREE(iface->addrs[i].addr); VIR_FREE(iface->addrs); VIR_FREE(iface); }
./CrossVul/dataset_final_sorted/CWE-254/c/good_4886_0
crossvul-cpp_data_bad_4872_1
/* * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "server.h" #include "cluster.h" #include "slowlog.h" #include "bio.h" #include "latency.h" #include <time.h> #include <signal.h> #include <sys/wait.h> #include <errno.h> #include <assert.h> #include <ctype.h> #include <stdarg.h> #include <arpa/inet.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/uio.h> #include <sys/un.h> #include <limits.h> #include <float.h> #include <math.h> #include <sys/resource.h> #include <sys/utsname.h> #include <locale.h> #include <sys/socket.h> /* Our shared "common" objects */ struct sharedObjectsStruct shared; /* Global vars that are actually used as constants. The following double * values are used for double on-disk serialization, and are initialized * at runtime to avoid strange compiler optimizations. */ double R_Zero, R_PosInf, R_NegInf, R_Nan; /*================================= Globals ================================= */ /* Global vars */ struct redisServer server; /* server global state */ /* Our command table. * * Every entry is composed of the following fields: * * name: a string representing the command name. * function: pointer to the C function implementing the command. * arity: number of arguments, it is possible to use -N to say >= N * sflags: command flags as string. See below for a table of flags. * flags: flags as bitmask. Computed by Redis using the 'sflags' field. * get_keys_proc: an optional function to get key arguments from a command. * This is only used when the following three fields are not * enough to specify what arguments are keys. * first_key_index: first argument that is a key * last_key_index: last argument that is a key * key_step: step to get all the keys from first to last argument. For instance * in MSET the step is two since arguments are key,val,key,val,... * microseconds: microseconds of total execution time for this command. * calls: total number of calls of this command. * * The flags, microseconds and calls fields are computed by Redis and should * always be set to zero. * * Command flags are expressed using strings where every character represents * a flag. Later the populateCommandTable() function will take care of * populating the real 'flags' field using this characters. * * This is the meaning of the flags: * * w: write command (may modify the key space). * r: read command (will never modify the key space). * m: may increase memory usage once called. Don't allow if out of memory. * a: admin command, like SAVE or SHUTDOWN. * p: Pub/Sub related command. * f: force replication of this command, regardless of server.dirty. * s: command not allowed in scripts. * R: random command. Command is not deterministic, that is, the same command * with the same arguments, with the same key space, may have different * results. For instance SPOP and RANDOMKEY are two random commands. * S: Sort command output array if called from script, so that the output * is deterministic. * l: Allow command while loading the database. * t: Allow command while a slave has stale data but is not allowed to * server this data. Normally no command is accepted in this condition * but just a few. * M: Do not automatically propagate the command on MONITOR. * k: Perform an implicit ASKING for this command, so the command will be * accepted in cluster mode if the slot is marked as 'importing'. * F: Fast command: O(1) or O(log(N)) command that should never delay * its execution as long as the kernel scheduler is giving us time. * Note that commands that may trigger a DEL as a side effect (like SET) * are not fast commands. */ struct redisCommand redisCommandTable[] = { {"get",getCommand,2,"rF",0,NULL,1,1,1,0,0}, {"set",setCommand,-3,"wm",0,NULL,1,1,1,0,0}, {"setnx",setnxCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"setex",setexCommand,4,"wm",0,NULL,1,1,1,0,0}, {"psetex",psetexCommand,4,"wm",0,NULL,1,1,1,0,0}, {"append",appendCommand,3,"wm",0,NULL,1,1,1,0,0}, {"strlen",strlenCommand,2,"rF",0,NULL,1,1,1,0,0}, {"del",delCommand,-2,"w",0,NULL,1,-1,1,0,0}, {"exists",existsCommand,-2,"rF",0,NULL,1,-1,1,0,0}, {"setbit",setbitCommand,4,"wm",0,NULL,1,1,1,0,0}, {"getbit",getbitCommand,3,"rF",0,NULL,1,1,1,0,0}, {"bitfield",bitfieldCommand,-2,"wm",0,NULL,1,1,1,0,0}, {"setrange",setrangeCommand,4,"wm",0,NULL,1,1,1,0,0}, {"getrange",getrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"substr",getrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"incr",incrCommand,2,"wmF",0,NULL,1,1,1,0,0}, {"decr",decrCommand,2,"wmF",0,NULL,1,1,1,0,0}, {"mget",mgetCommand,-2,"r",0,NULL,1,-1,1,0,0}, {"rpush",rpushCommand,-3,"wmF",0,NULL,1,1,1,0,0}, {"lpush",lpushCommand,-3,"wmF",0,NULL,1,1,1,0,0}, {"rpushx",rpushxCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"lpushx",lpushxCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"linsert",linsertCommand,5,"wm",0,NULL,1,1,1,0,0}, {"rpop",rpopCommand,2,"wF",0,NULL,1,1,1,0,0}, {"lpop",lpopCommand,2,"wF",0,NULL,1,1,1,0,0}, {"brpop",brpopCommand,-3,"ws",0,NULL,1,1,1,0,0}, {"brpoplpush",brpoplpushCommand,4,"wms",0,NULL,1,2,1,0,0}, {"blpop",blpopCommand,-3,"ws",0,NULL,1,-2,1,0,0}, {"llen",llenCommand,2,"rF",0,NULL,1,1,1,0,0}, {"lindex",lindexCommand,3,"r",0,NULL,1,1,1,0,0}, {"lset",lsetCommand,4,"wm",0,NULL,1,1,1,0,0}, {"lrange",lrangeCommand,4,"r",0,NULL,1,1,1,0,0}, {"ltrim",ltrimCommand,4,"w",0,NULL,1,1,1,0,0}, {"lrem",lremCommand,4,"w",0,NULL,1,1,1,0,0}, {"rpoplpush",rpoplpushCommand,3,"wm",0,NULL,1,2,1,0,0}, {"sadd",saddCommand,-3,"wmF",0,NULL,1,1,1,0,0}, {"srem",sremCommand,-3,"wF",0,NULL,1,1,1,0,0}, {"smove",smoveCommand,4,"wF",0,NULL,1,2,1,0,0}, {"sismember",sismemberCommand,3,"rF",0,NULL,1,1,1,0,0}, {"scard",scardCommand,2,"rF",0,NULL,1,1,1,0,0}, {"spop",spopCommand,-2,"wRF",0,NULL,1,1,1,0,0}, {"srandmember",srandmemberCommand,-2,"rR",0,NULL,1,1,1,0,0}, {"sinter",sinterCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sinterstore",sinterstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"sunion",sunionCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sunionstore",sunionstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"sdiff",sdiffCommand,-2,"rS",0,NULL,1,-1,1,0,0}, {"sdiffstore",sdiffstoreCommand,-3,"wm",0,NULL,1,-1,1,0,0}, {"smembers",sinterCommand,2,"rS",0,NULL,1,1,1,0,0}, {"sscan",sscanCommand,-3,"rR",0,NULL,1,1,1,0,0}, {"zadd",zaddCommand,-4,"wmF",0,NULL,1,1,1,0,0}, {"zincrby",zincrbyCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"zrem",zremCommand,-3,"wF",0,NULL,1,1,1,0,0}, {"zremrangebyscore",zremrangebyscoreCommand,4,"w",0,NULL,1,1,1,0,0}, {"zremrangebyrank",zremrangebyrankCommand,4,"w",0,NULL,1,1,1,0,0}, {"zremrangebylex",zremrangebylexCommand,4,"w",0,NULL,1,1,1,0,0}, {"zunionstore",zunionstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0}, {"zinterstore",zinterstoreCommand,-4,"wm",0,zunionInterGetKeys,0,0,0,0,0}, {"zrange",zrangeCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrangebyscore",zrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrevrangebyscore",zrevrangebyscoreCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrangebylex",zrangebylexCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zrevrangebylex",zrevrangebylexCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zcount",zcountCommand,4,"rF",0,NULL,1,1,1,0,0}, {"zlexcount",zlexcountCommand,4,"rF",0,NULL,1,1,1,0,0}, {"zrevrange",zrevrangeCommand,-4,"r",0,NULL,1,1,1,0,0}, {"zcard",zcardCommand,2,"rF",0,NULL,1,1,1,0,0}, {"zscore",zscoreCommand,3,"rF",0,NULL,1,1,1,0,0}, {"zrank",zrankCommand,3,"rF",0,NULL,1,1,1,0,0}, {"zrevrank",zrevrankCommand,3,"rF",0,NULL,1,1,1,0,0}, {"zscan",zscanCommand,-3,"rR",0,NULL,1,1,1,0,0}, {"hset",hsetCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hsetnx",hsetnxCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hget",hgetCommand,3,"rF",0,NULL,1,1,1,0,0}, {"hmset",hmsetCommand,-4,"wm",0,NULL,1,1,1,0,0}, {"hmget",hmgetCommand,-3,"r",0,NULL,1,1,1,0,0}, {"hincrby",hincrbyCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hincrbyfloat",hincrbyfloatCommand,4,"wmF",0,NULL,1,1,1,0,0}, {"hdel",hdelCommand,-3,"wF",0,NULL,1,1,1,0,0}, {"hlen",hlenCommand,2,"rF",0,NULL,1,1,1,0,0}, {"hstrlen",hstrlenCommand,3,"rF",0,NULL,1,1,1,0,0}, {"hkeys",hkeysCommand,2,"rS",0,NULL,1,1,1,0,0}, {"hvals",hvalsCommand,2,"rS",0,NULL,1,1,1,0,0}, {"hgetall",hgetallCommand,2,"r",0,NULL,1,1,1,0,0}, {"hexists",hexistsCommand,3,"rF",0,NULL,1,1,1,0,0}, {"hscan",hscanCommand,-3,"rR",0,NULL,1,1,1,0,0}, {"incrby",incrbyCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"decrby",decrbyCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"incrbyfloat",incrbyfloatCommand,3,"wmF",0,NULL,1,1,1,0,0}, {"getset",getsetCommand,3,"wm",0,NULL,1,1,1,0,0}, {"mset",msetCommand,-3,"wm",0,NULL,1,-1,2,0,0}, {"msetnx",msetnxCommand,-3,"wm",0,NULL,1,-1,2,0,0}, {"randomkey",randomkeyCommand,1,"rR",0,NULL,0,0,0,0,0}, {"select",selectCommand,2,"lF",0,NULL,0,0,0,0,0}, {"move",moveCommand,3,"wF",0,NULL,1,1,1,0,0}, {"rename",renameCommand,3,"w",0,NULL,1,2,1,0,0}, {"renamenx",renamenxCommand,3,"wF",0,NULL,1,2,1,0,0}, {"expire",expireCommand,3,"wF",0,NULL,1,1,1,0,0}, {"expireat",expireatCommand,3,"wF",0,NULL,1,1,1,0,0}, {"pexpire",pexpireCommand,3,"wF",0,NULL,1,1,1,0,0}, {"pexpireat",pexpireatCommand,3,"wF",0,NULL,1,1,1,0,0}, {"keys",keysCommand,2,"rS",0,NULL,0,0,0,0,0}, {"scan",scanCommand,-2,"rR",0,NULL,0,0,0,0,0}, {"dbsize",dbsizeCommand,1,"rF",0,NULL,0,0,0,0,0}, {"auth",authCommand,2,"sltF",0,NULL,0,0,0,0,0}, {"ping",pingCommand,-1,"tF",0,NULL,0,0,0,0,0}, {"echo",echoCommand,2,"F",0,NULL,0,0,0,0,0}, {"save",saveCommand,1,"as",0,NULL,0,0,0,0,0}, {"bgsave",bgsaveCommand,-1,"a",0,NULL,0,0,0,0,0}, {"bgrewriteaof",bgrewriteaofCommand,1,"a",0,NULL,0,0,0,0,0}, {"shutdown",shutdownCommand,-1,"alt",0,NULL,0,0,0,0,0}, {"lastsave",lastsaveCommand,1,"RF",0,NULL,0,0,0,0,0}, {"type",typeCommand,2,"rF",0,NULL,1,1,1,0,0}, {"multi",multiCommand,1,"sF",0,NULL,0,0,0,0,0}, {"exec",execCommand,1,"sM",0,NULL,0,0,0,0,0}, {"discard",discardCommand,1,"sF",0,NULL,0,0,0,0,0}, {"sync",syncCommand,1,"ars",0,NULL,0,0,0,0,0}, {"psync",syncCommand,3,"ars",0,NULL,0,0,0,0,0}, {"replconf",replconfCommand,-1,"aslt",0,NULL,0,0,0,0,0}, {"flushdb",flushdbCommand,1,"w",0,NULL,0,0,0,0,0}, {"flushall",flushallCommand,1,"w",0,NULL,0,0,0,0,0}, {"sort",sortCommand,-2,"wm",0,sortGetKeys,1,1,1,0,0}, {"info",infoCommand,-1,"lt",0,NULL,0,0,0,0,0}, {"monitor",monitorCommand,1,"as",0,NULL,0,0,0,0,0}, {"ttl",ttlCommand,2,"rF",0,NULL,1,1,1,0,0}, {"touch",touchCommand,-2,"rF",0,NULL,1,1,1,0,0}, {"pttl",pttlCommand,2,"rF",0,NULL,1,1,1,0,0}, {"persist",persistCommand,2,"wF",0,NULL,1,1,1,0,0}, {"slaveof",slaveofCommand,3,"ast",0,NULL,0,0,0,0,0}, {"role",roleCommand,1,"lst",0,NULL,0,0,0,0,0}, {"debug",debugCommand,-1,"as",0,NULL,0,0,0,0,0}, {"config",configCommand,-2,"lat",0,NULL,0,0,0,0,0}, {"subscribe",subscribeCommand,-2,"pslt",0,NULL,0,0,0,0,0}, {"unsubscribe",unsubscribeCommand,-1,"pslt",0,NULL,0,0,0,0,0}, {"psubscribe",psubscribeCommand,-2,"pslt",0,NULL,0,0,0,0,0}, {"punsubscribe",punsubscribeCommand,-1,"pslt",0,NULL,0,0,0,0,0}, {"publish",publishCommand,3,"pltF",0,NULL,0,0,0,0,0}, {"pubsub",pubsubCommand,-2,"pltR",0,NULL,0,0,0,0,0}, {"watch",watchCommand,-2,"sF",0,NULL,1,-1,1,0,0}, {"unwatch",unwatchCommand,1,"sF",0,NULL,0,0,0,0,0}, {"cluster",clusterCommand,-2,"a",0,NULL,0,0,0,0,0}, {"restore",restoreCommand,-4,"wm",0,NULL,1,1,1,0,0}, {"restore-asking",restoreCommand,-4,"wmk",0,NULL,1,1,1,0,0}, {"migrate",migrateCommand,-6,"w",0,migrateGetKeys,0,0,0,0,0}, {"asking",askingCommand,1,"F",0,NULL,0,0,0,0,0}, {"readonly",readonlyCommand,1,"F",0,NULL,0,0,0,0,0}, {"readwrite",readwriteCommand,1,"F",0,NULL,0,0,0,0,0}, {"dump",dumpCommand,2,"r",0,NULL,1,1,1,0,0}, {"object",objectCommand,3,"r",0,NULL,2,2,2,0,0}, {"client",clientCommand,-2,"as",0,NULL,0,0,0,0,0}, {"eval",evalCommand,-3,"s",0,evalGetKeys,0,0,0,0,0}, {"evalsha",evalShaCommand,-3,"s",0,evalGetKeys,0,0,0,0,0}, {"slowlog",slowlogCommand,-2,"a",0,NULL,0,0,0,0,0}, {"script",scriptCommand,-2,"s",0,NULL,0,0,0,0,0}, {"time",timeCommand,1,"RF",0,NULL,0,0,0,0,0}, {"bitop",bitopCommand,-4,"wm",0,NULL,2,-1,1,0,0}, {"bitcount",bitcountCommand,-2,"r",0,NULL,1,1,1,0,0}, {"bitpos",bitposCommand,-3,"r",0,NULL,1,1,1,0,0}, {"wait",waitCommand,3,"s",0,NULL,0,0,0,0,0}, {"command",commandCommand,0,"lt",0,NULL,0,0,0,0,0}, {"geoadd",geoaddCommand,-5,"wm",0,NULL,1,1,1,0,0}, {"georadius",georadiusCommand,-6,"w",0,NULL,1,1,1,0,0}, {"georadiusbymember",georadiusByMemberCommand,-5,"w",0,NULL,1,1,1,0,0}, {"geohash",geohashCommand,-2,"r",0,NULL,1,1,1,0,0}, {"geopos",geoposCommand,-2,"r",0,NULL,1,1,1,0,0}, {"geodist",geodistCommand,-4,"r",0,NULL,1,1,1,0,0}, {"pfselftest",pfselftestCommand,1,"a",0,NULL,0,0,0,0,0}, {"pfadd",pfaddCommand,-2,"wmF",0,NULL,1,1,1,0,0}, {"pfcount",pfcountCommand,-2,"r",0,NULL,1,-1,1,0,0}, {"pfmerge",pfmergeCommand,-2,"wm",0,NULL,1,-1,1,0,0}, {"pfdebug",pfdebugCommand,-3,"w",0,NULL,0,0,0,0,0}, {"latency",latencyCommand,-2,"aslt",0,NULL,0,0,0,0,0} }; struct evictionPoolEntry *evictionPoolAlloc(void); /*============================ Utility functions ============================ */ /* Low level logging. To use only for very big messages, otherwise * serverLog() is to prefer. */ void serverLogRaw(int level, const char *msg) { const int syslogLevelMap[] = { LOG_DEBUG, LOG_INFO, LOG_NOTICE, LOG_WARNING }; const char *c = ".-*#"; FILE *fp; char buf[64]; int rawmode = (level & LL_RAW); int log_to_stdout = server.logfile[0] == '\0'; level &= 0xff; /* clear flags */ if (level < server.verbosity) return; fp = log_to_stdout ? stdout : fopen(server.logfile,"a"); if (!fp) return; if (rawmode) { fprintf(fp,"%s",msg); } else { int off; struct timeval tv; int role_char; pid_t pid = getpid(); gettimeofday(&tv,NULL); off = strftime(buf,sizeof(buf),"%d %b %H:%M:%S.",localtime(&tv.tv_sec)); snprintf(buf+off,sizeof(buf)-off,"%03d",(int)tv.tv_usec/1000); if (server.sentinel_mode) { role_char = 'X'; /* Sentinel. */ } else if (pid != server.pid) { role_char = 'C'; /* RDB / AOF writing child. */ } else { role_char = (server.masterhost ? 'S':'M'); /* Slave or Master. */ } fprintf(fp,"%d:%c %s %c %s\n", (int)getpid(),role_char, buf,c[level],msg); } fflush(fp); if (!log_to_stdout) fclose(fp); if (server.syslog_enabled) syslog(syslogLevelMap[level], "%s", msg); } /* Like serverLogRaw() but with printf-alike support. This is the function that * is used across the code. The raw version is only used in order to dump * the INFO output on crash. */ void serverLog(int level, const char *fmt, ...) { va_list ap; char msg[LOG_MAX_LEN]; if ((level&0xff) < server.verbosity) return; va_start(ap, fmt); vsnprintf(msg, sizeof(msg), fmt, ap); va_end(ap); serverLogRaw(level,msg); } /* Log a fixed message without printf-alike capabilities, in a way that is * safe to call from a signal handler. * * We actually use this only for signals that are not fatal from the point * of view of Redis. Signals that are going to kill the server anyway and * where we need printf-alike features are served by serverLog(). */ void serverLogFromHandler(int level, const char *msg) { int fd; int log_to_stdout = server.logfile[0] == '\0'; char buf[64]; if ((level&0xff) < server.verbosity || (log_to_stdout && server.daemonize)) return; fd = log_to_stdout ? STDOUT_FILENO : open(server.logfile, O_APPEND|O_CREAT|O_WRONLY, 0644); if (fd == -1) return; ll2string(buf,sizeof(buf),getpid()); if (write(fd,buf,strlen(buf)) == -1) goto err; if (write(fd,":signal-handler (",17) == -1) goto err; ll2string(buf,sizeof(buf),time(NULL)); if (write(fd,buf,strlen(buf)) == -1) goto err; if (write(fd,") ",2) == -1) goto err; if (write(fd,msg,strlen(msg)) == -1) goto err; if (write(fd,"\n",1) == -1) goto err; err: if (!log_to_stdout) close(fd); } /* Return the UNIX time in microseconds */ long long ustime(void) { struct timeval tv; long long ust; gettimeofday(&tv, NULL); ust = ((long long)tv.tv_sec)*1000000; ust += tv.tv_usec; return ust; } /* Return the UNIX time in milliseconds */ mstime_t mstime(void) { return ustime()/1000; } /* After an RDB dump or AOF rewrite we exit from children using _exit() instead of * exit(), because the latter may interact with the same file objects used by * the parent process. However if we are testing the coverage normal exit() is * used in order to obtain the right coverage information. */ void exitFromChild(int retcode) { #ifdef COVERAGE_TEST exit(retcode); #else _exit(retcode); #endif } /*====================== Hash table type implementation ==================== */ /* This is a hash table type that uses the SDS dynamic strings library as * keys and redis objects as values (objects can hold SDS strings, * lists, sets). */ void dictVanillaFree(void *privdata, void *val) { DICT_NOTUSED(privdata); zfree(val); } void dictListDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); listRelease((list*)val); } int dictSdsKeyCompare(void *privdata, const void *key1, const void *key2) { int l1,l2; DICT_NOTUSED(privdata); l1 = sdslen((sds)key1); l2 = sdslen((sds)key2); if (l1 != l2) return 0; return memcmp(key1, key2, l1) == 0; } /* A case insensitive version used for the command lookup table and other * places where case insensitive non binary-safe comparison is needed. */ int dictSdsKeyCaseCompare(void *privdata, const void *key1, const void *key2) { DICT_NOTUSED(privdata); return strcasecmp(key1, key2) == 0; } void dictObjectDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); if (val == NULL) return; /* Values of swapped out keys as set to NULL */ decrRefCount(val); } void dictSdsDestructor(void *privdata, void *val) { DICT_NOTUSED(privdata); sdsfree(val); } int dictObjKeyCompare(void *privdata, const void *key1, const void *key2) { const robj *o1 = key1, *o2 = key2; return dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); } unsigned int dictObjHash(const void *key) { const robj *o = key; return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); } unsigned int dictSdsHash(const void *key) { return dictGenHashFunction((unsigned char*)key, sdslen((char*)key)); } unsigned int dictSdsCaseHash(const void *key) { return dictGenCaseHashFunction((unsigned char*)key, sdslen((char*)key)); } int dictEncObjKeyCompare(void *privdata, const void *key1, const void *key2) { robj *o1 = (robj*) key1, *o2 = (robj*) key2; int cmp; if (o1->encoding == OBJ_ENCODING_INT && o2->encoding == OBJ_ENCODING_INT) return o1->ptr == o2->ptr; o1 = getDecodedObject(o1); o2 = getDecodedObject(o2); cmp = dictSdsKeyCompare(privdata,o1->ptr,o2->ptr); decrRefCount(o1); decrRefCount(o2); return cmp; } unsigned int dictEncObjHash(const void *key) { robj *o = (robj*) key; if (sdsEncodedObject(o)) { return dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); } else { if (o->encoding == OBJ_ENCODING_INT) { char buf[32]; int len; len = ll2string(buf,32,(long)o->ptr); return dictGenHashFunction((unsigned char*)buf, len); } else { unsigned int hash; o = getDecodedObject(o); hash = dictGenHashFunction(o->ptr, sdslen((sds)o->ptr)); decrRefCount(o); return hash; } } } /* Sets type hash table */ dictType setDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictObjectDestructor, /* key destructor */ NULL /* val destructor */ }; /* Sorted sets hash (note: a skiplist is used in addition to the hash table) */ dictType zsetDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictObjectDestructor, /* key destructor */ NULL /* val destructor */ }; /* Db->dict, keys are sds strings, vals are Redis objects. */ dictType dbDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ dictSdsDestructor, /* key destructor */ dictObjectDestructor /* val destructor */ }; /* server.lua_scripts sha (as sds string) -> scripts (as robj) cache. */ dictType shaScriptObjectDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ dictObjectDestructor /* val destructor */ }; /* Db->expires */ dictType keyptrDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ NULL, /* key destructor */ NULL /* val destructor */ }; /* Command table. sds string -> command struct pointer. */ dictType commandTableDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Hash type hash table (note that small hashes are represented with ziplists) */ dictType hashDictType = { dictEncObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictEncObjKeyCompare, /* key compare */ dictObjectDestructor, /* key destructor */ dictObjectDestructor /* val destructor */ }; /* Keylist hash table type has unencoded redis objects as keys and * lists as values. It's used for blocking operations (BLPOP) and to * map swapped keys to a list of clients waiting for this keys to be loaded. */ dictType keylistDictType = { dictObjHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictObjKeyCompare, /* key compare */ dictObjectDestructor, /* key destructor */ dictListDestructor /* val destructor */ }; /* Cluster nodes hash table, mapping nodes addresses 1.2.3.4:6379 to * clusterNode structures. */ dictType clusterNodesDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Cluster re-addition blacklist. This maps node IDs to the time * we can re-add this node. The goal is to avoid readding a removed * node for some time. */ dictType clusterNodesBlackListDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Migrate cache dict type. */ dictType migrateCacheDictType = { dictSdsHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* Replication cached script dict (server.repl_scriptcache_dict). * Keys are sds SHA1 strings, while values are not used at all in the current * implementation. */ dictType replScriptCacheDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; int htNeedsResize(dict *dict) { long long size, used; size = dictSlots(dict); used = dictSize(dict); return (size > DICT_HT_INITIAL_SIZE && (used*100/size < HASHTABLE_MIN_FILL)); } /* If the percentage of used slots in the HT reaches HASHTABLE_MIN_FILL * we resize the hash table to save memory */ void tryResizeHashTables(int dbid) { if (htNeedsResize(server.db[dbid].dict)) dictResize(server.db[dbid].dict); if (htNeedsResize(server.db[dbid].expires)) dictResize(server.db[dbid].expires); } /* Our hash table implementation performs rehashing incrementally while * we write/read from the hash table. Still if the server is idle, the hash * table will use two tables for a long time. So we try to use 1 millisecond * of CPU time at every call of this function to perform some rehahsing. * * The function returns 1 if some rehashing was performed, otherwise 0 * is returned. */ int incrementallyRehash(int dbid) { /* Keys dictionary */ if (dictIsRehashing(server.db[dbid].dict)) { dictRehashMilliseconds(server.db[dbid].dict,1); return 1; /* already used our millisecond for this loop... */ } /* Expires */ if (dictIsRehashing(server.db[dbid].expires)) { dictRehashMilliseconds(server.db[dbid].expires,1); return 1; /* already used our millisecond for this loop... */ } return 0; } /* This function is called once a background process of some kind terminates, * as we want to avoid resizing the hash tables when there is a child in order * to play well with copy-on-write (otherwise when a resize happens lots of * memory pages are copied). The goal of this function is to update the ability * for dict.c to resize the hash tables accordingly to the fact we have o not * running childs. */ void updateDictResizePolicy(void) { if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) dictEnableResize(); else dictDisableResize(); } /* ======================= Cron: called every 100 ms ======================== */ /* Helper function for the activeExpireCycle() function. * This function will try to expire the key that is stored in the hash table * entry 'de' of the 'expires' hash table of a Redis database. * * If the key is found to be expired, it is removed from the database and * 1 is returned. Otherwise no operation is performed and 0 is returned. * * When a key is expired, server.stat_expiredkeys is incremented. * * The parameter 'now' is the current time in milliseconds as is passed * to the function to avoid too many gettimeofday() syscalls. */ int activeExpireCycleTryExpire(redisDb *db, dictEntry *de, long long now) { long long t = dictGetSignedIntegerVal(de); if (now > t) { sds key = dictGetKey(de); robj *keyobj = createStringObject(key,sdslen(key)); propagateExpire(db,keyobj); dbDelete(db,keyobj); notifyKeyspaceEvent(NOTIFY_EXPIRED, "expired",keyobj,db->id); decrRefCount(keyobj); server.stat_expiredkeys++; return 1; } else { return 0; } } /* Try to expire a few timed out keys. The algorithm used is adaptive and * will use few CPU cycles if there are few expiring keys, otherwise * it will get more aggressive to avoid that too much memory is used by * keys that can be removed from the keyspace. * * No more than CRON_DBS_PER_CALL databases are tested at every * iteration. * * This kind of call is used when Redis detects that timelimit_exit is * true, so there is more work to do, and we do it more incrementally from * the beforeSleep() function of the event loop. * * Expire cycle type: * * If type is ACTIVE_EXPIRE_CYCLE_FAST the function will try to run a * "fast" expire cycle that takes no longer than EXPIRE_FAST_CYCLE_DURATION * microseconds, and is not repeated again before the same amount of time. * * If type is ACTIVE_EXPIRE_CYCLE_SLOW, that normal expire cycle is * executed, where the time limit is a percentage of the REDIS_HZ period * as specified by the REDIS_EXPIRELOOKUPS_TIME_PERC define. */ void activeExpireCycle(int type) { /* This function has some global state in order to continue the work * incrementally across calls. */ static unsigned int current_db = 0; /* Last DB tested. */ static int timelimit_exit = 0; /* Time limit hit in previous call? */ static long long last_fast_cycle = 0; /* When last fast cycle ran. */ int j, iteration = 0; int dbs_per_call = CRON_DBS_PER_CALL; long long start = ustime(), timelimit; if (type == ACTIVE_EXPIRE_CYCLE_FAST) { /* Don't start a fast cycle if the previous cycle did not exited * for time limt. Also don't repeat a fast cycle for the same period * as the fast cycle total duration itself. */ if (!timelimit_exit) return; if (start < last_fast_cycle + ACTIVE_EXPIRE_CYCLE_FAST_DURATION*2) return; last_fast_cycle = start; } /* We usually should test CRON_DBS_PER_CALL per iteration, with * two exceptions: * * 1) Don't test more DBs than we have. * 2) If last time we hit the time limit, we want to scan all DBs * in this iteration, as there is work to do in some DB and we don't want * expired keys to use memory for too much time. */ if (dbs_per_call > server.dbnum || timelimit_exit) dbs_per_call = server.dbnum; /* We can use at max ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC percentage of CPU time * per iteration. Since this function gets called with a frequency of * server.hz times per second, the following is the max amount of * microseconds we can spend in this function. */ timelimit = 1000000*ACTIVE_EXPIRE_CYCLE_SLOW_TIME_PERC/server.hz/100; timelimit_exit = 0; if (timelimit <= 0) timelimit = 1; if (type == ACTIVE_EXPIRE_CYCLE_FAST) timelimit = ACTIVE_EXPIRE_CYCLE_FAST_DURATION; /* in microseconds. */ for (j = 0; j < dbs_per_call; j++) { int expired; redisDb *db = server.db+(current_db % server.dbnum); /* Increment the DB now so we are sure if we run out of time * in the current DB we'll restart from the next. This allows to * distribute the time evenly across DBs. */ current_db++; /* Continue to expire if at the end of the cycle more than 25% * of the keys were expired. */ do { unsigned long num, slots; long long now, ttl_sum; int ttl_samples; /* If there is nothing to expire try next DB ASAP. */ if ((num = dictSize(db->expires)) == 0) { db->avg_ttl = 0; break; } slots = dictSlots(db->expires); now = mstime(); /* When there are less than 1% filled slots getting random * keys is expensive, so stop here waiting for better times... * The dictionary will be resized asap. */ if (num && slots > DICT_HT_INITIAL_SIZE && (num*100/slots < 1)) break; /* The main collection cycle. Sample random keys among keys * with an expire set, checking for expired ones. */ expired = 0; ttl_sum = 0; ttl_samples = 0; if (num > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP) num = ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP; while (num--) { dictEntry *de; long long ttl; if ((de = dictGetRandomKey(db->expires)) == NULL) break; ttl = dictGetSignedIntegerVal(de)-now; if (activeExpireCycleTryExpire(db,de,now)) expired++; if (ttl > 0) { /* We want the average TTL of keys yet not expired. */ ttl_sum += ttl; ttl_samples++; } } /* Update the average TTL stats for this database. */ if (ttl_samples) { long long avg_ttl = ttl_sum/ttl_samples; /* Do a simple running average with a few samples. * We just use the current estimate with a weight of 2% * and the previous estimate with a weight of 98%. */ if (db->avg_ttl == 0) db->avg_ttl = avg_ttl; db->avg_ttl = (db->avg_ttl/50)*49 + (avg_ttl/50); } /* We can't block forever here even if there are many keys to * expire. So after a given amount of milliseconds return to the * caller waiting for the other active expire cycle. */ iteration++; if ((iteration & 0xf) == 0) { /* check once every 16 iterations. */ long long elapsed = ustime()-start; latencyAddSampleIfNeeded("expire-cycle",elapsed/1000); if (elapsed > timelimit) timelimit_exit = 1; } if (timelimit_exit) return; /* We don't repeat the cycle if there are less than 25% of keys * found expired in the current DB. */ } while (expired > ACTIVE_EXPIRE_CYCLE_LOOKUPS_PER_LOOP/4); } } unsigned int getLRUClock(void) { return (mstime()/LRU_CLOCK_RESOLUTION) & LRU_CLOCK_MAX; } /* Add a sample to the operations per second array of samples. */ void trackInstantaneousMetric(int metric, long long current_reading) { long long t = mstime() - server.inst_metric[metric].last_sample_time; long long ops = current_reading - server.inst_metric[metric].last_sample_count; long long ops_sec; ops_sec = t > 0 ? (ops*1000/t) : 0; server.inst_metric[metric].samples[server.inst_metric[metric].idx] = ops_sec; server.inst_metric[metric].idx++; server.inst_metric[metric].idx %= STATS_METRIC_SAMPLES; server.inst_metric[metric].last_sample_time = mstime(); server.inst_metric[metric].last_sample_count = current_reading; } /* Return the mean of all the samples. */ long long getInstantaneousMetric(int metric) { int j; long long sum = 0; for (j = 0; j < STATS_METRIC_SAMPLES; j++) sum += server.inst_metric[metric].samples[j]; return sum / STATS_METRIC_SAMPLES; } /* Check for timeouts. Returns non-zero if the client was terminated. * The function gets the current time in milliseconds as argument since * it gets called multiple times in a loop, so calling gettimeofday() for * each iteration would be costly without any actual gain. */ int clientsCronHandleTimeout(client *c, mstime_t now_ms) { time_t now = now_ms/1000; if (server.maxidletime && !(c->flags & CLIENT_SLAVE) && /* no timeout for slaves */ !(c->flags & CLIENT_MASTER) && /* no timeout for masters */ !(c->flags & CLIENT_BLOCKED) && /* no timeout for BLPOP */ !(c->flags & CLIENT_PUBSUB) && /* no timeout for Pub/Sub clients */ (now - c->lastinteraction > server.maxidletime)) { serverLog(LL_VERBOSE,"Closing idle client"); freeClient(c); return 1; } else if (c->flags & CLIENT_BLOCKED) { /* Blocked OPS timeout is handled with milliseconds resolution. * However note that the actual resolution is limited by * server.hz. */ if (c->bpop.timeout != 0 && c->bpop.timeout < now_ms) { /* Handle blocking operation specific timeout. */ replyToBlockedClientTimedOut(c); unblockClient(c); } else if (server.cluster_enabled) { /* Cluster: handle unblock & redirect of clients blocked * into keys no longer served by this server. */ if (clusterRedirectBlockedClientIfNeeded(c)) unblockClient(c); } } return 0; } /* The client query buffer is an sds.c string that can end with a lot of * free space not used, this function reclaims space if needed. * * The function always returns 0 as it never terminates the client. */ int clientsCronResizeQueryBuffer(client *c) { size_t querybuf_size = sdsAllocSize(c->querybuf); time_t idletime = server.unixtime - c->lastinteraction; /* There are two conditions to resize the query buffer: * 1) Query buffer is > BIG_ARG and too big for latest peak. * 2) Client is inactive and the buffer is bigger than 1k. */ if (((querybuf_size > PROTO_MBULK_BIG_ARG) && (querybuf_size/(c->querybuf_peak+1)) > 2) || (querybuf_size > 1024 && idletime > 2)) { /* Only resize the query buffer if it is actually wasting space. */ if (sdsavail(c->querybuf) > 1024) { c->querybuf = sdsRemoveFreeSpace(c->querybuf); } } /* Reset the peak again to capture the peak memory usage in the next * cycle. */ c->querybuf_peak = 0; return 0; } #define CLIENTS_CRON_MIN_ITERATIONS 5 void clientsCron(void) { /* Make sure to process at least numclients/server.hz of clients * per call. Since this function is called server.hz times per second * we are sure that in the worst case we process all the clients in 1 * second. */ int numclients = listLength(server.clients); int iterations = numclients/server.hz; mstime_t now = mstime(); /* Process at least a few clients while we are at it, even if we need * to process less than CLIENTS_CRON_MIN_ITERATIONS to meet our contract * of processing each client once per second. */ if (iterations < CLIENTS_CRON_MIN_ITERATIONS) iterations = (numclients < CLIENTS_CRON_MIN_ITERATIONS) ? numclients : CLIENTS_CRON_MIN_ITERATIONS; while(listLength(server.clients) && iterations--) { client *c; listNode *head; /* Rotate the list, take the current head, process. * This way if the client must be removed from the list it's the * first element and we don't incur into O(N) computation. */ listRotate(server.clients); head = listFirst(server.clients); c = listNodeValue(head); /* The following functions do different service checks on the client. * The protocol is that they return non-zero if the client was * terminated. */ if (clientsCronHandleTimeout(c,now)) continue; if (clientsCronResizeQueryBuffer(c)) continue; } } /* This function handles 'background' operations we are required to do * incrementally in Redis databases, such as active key expiring, resizing, * rehashing. */ void databasesCron(void) { /* Expire keys by random sampling. Not required for slaves * as master will synthesize DELs for us. */ if (server.active_expire_enabled && server.masterhost == NULL) activeExpireCycle(ACTIVE_EXPIRE_CYCLE_SLOW); /* Perform hash tables rehashing if needed, but only if there are no * other processes saving the DB on disk. Otherwise rehashing is bad * as will cause a lot of copy-on-write of memory pages. */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1) { /* We use global counters so if we stop the computation at a given * DB we'll be able to start from the successive in the next * cron loop iteration. */ static unsigned int resize_db = 0; static unsigned int rehash_db = 0; int dbs_per_call = CRON_DBS_PER_CALL; int j; /* Don't test more DBs than we have. */ if (dbs_per_call > server.dbnum) dbs_per_call = server.dbnum; /* Resize */ for (j = 0; j < dbs_per_call; j++) { tryResizeHashTables(resize_db % server.dbnum); resize_db++; } /* Rehash */ if (server.activerehashing) { for (j = 0; j < dbs_per_call; j++) { int work_done = incrementallyRehash(rehash_db % server.dbnum); rehash_db++; if (work_done) { /* If the function did some work, stop here, we'll do * more at the next cron loop. */ break; } } } } } /* We take a cached value of the unix time in the global state because with * virtual memory and aging there is to store the current time in objects at * every object access, and accuracy is not needed. To access a global var is * a lot faster than calling time(NULL) */ void updateCachedTime(void) { server.unixtime = time(NULL); server.mstime = mstime(); } /* This is our timer interrupt, called server.hz times per second. * Here is where we do a number of things that need to be done asynchronously. * For instance: * * - Active expired keys collection (it is also performed in a lazy way on * lookup). * - Software watchdog. * - Update some statistic. * - Incremental rehashing of the DBs hash tables. * - Triggering BGSAVE / AOF rewrite, and handling of terminated children. * - Clients timeout of different kinds. * - Replication reconnection. * - Many more... * * Everything directly called here will be called server.hz times per second, * so in order to throttle execution of things we want to do less frequently * a macro is used: run_with_period(milliseconds) { .... } */ int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData) { int j; UNUSED(eventLoop); UNUSED(id); UNUSED(clientData); /* Software watchdog: deliver the SIGALRM that will reach the signal * handler if we don't return here fast enough. */ if (server.watchdog_period) watchdogScheduleSignal(server.watchdog_period); /* Update the time cache. */ updateCachedTime(); run_with_period(100) { trackInstantaneousMetric(STATS_METRIC_COMMAND,server.stat_numcommands); trackInstantaneousMetric(STATS_METRIC_NET_INPUT, server.stat_net_input_bytes); trackInstantaneousMetric(STATS_METRIC_NET_OUTPUT, server.stat_net_output_bytes); } /* We have just LRU_BITS bits per object for LRU information. * So we use an (eventually wrapping) LRU clock. * * Note that even if the counter wraps it's not a big problem, * everything will still work but some object will appear younger * to Redis. However for this to happen a given object should never be * touched for all the time needed to the counter to wrap, which is * not likely. * * Note that you can change the resolution altering the * LRU_CLOCK_RESOLUTION define. */ server.lruclock = getLRUClock(); /* Record the max memory used since the server was started. */ if (zmalloc_used_memory() > server.stat_peak_memory) server.stat_peak_memory = zmalloc_used_memory(); /* Sample the RSS here since this is a relatively slow call. */ server.resident_set_size = zmalloc_get_rss(); /* We received a SIGTERM, shutting down here in a safe way, as it is * not ok doing so inside the signal handler. */ if (server.shutdown_asap) { if (prepareForShutdown(SHUTDOWN_NOFLAGS) == C_OK) exit(0); serverLog(LL_WARNING,"SIGTERM received but errors trying to shut down the server, check the logs for more information"); server.shutdown_asap = 0; } /* Show some info about non-empty databases */ run_with_period(5000) { for (j = 0; j < server.dbnum; j++) { long long size, used, vkeys; size = dictSlots(server.db[j].dict); used = dictSize(server.db[j].dict); vkeys = dictSize(server.db[j].expires); if (used || vkeys) { serverLog(LL_VERBOSE,"DB %d: %lld keys (%lld volatile) in %lld slots HT.",j,used,vkeys,size); /* dictPrintStats(server.dict); */ } } } /* Show information about connected clients */ if (!server.sentinel_mode) { run_with_period(5000) { serverLog(LL_VERBOSE, "%lu clients connected (%lu slaves), %zu bytes in use", listLength(server.clients)-listLength(server.slaves), listLength(server.slaves), zmalloc_used_memory()); } } /* We need to do a few operations on clients asynchronously. */ clientsCron(); /* Handle background operations on Redis databases. */ databasesCron(); /* Start a scheduled AOF rewrite if this was requested by the user while * a BGSAVE was in progress. */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.aof_rewrite_scheduled) { rewriteAppendOnlyFileBackground(); } /* Check if a background saving or AOF rewrite in progress terminated. */ if (server.rdb_child_pid != -1 || server.aof_child_pid != -1 || ldbPendingChildren()) { int statloc; pid_t pid; if ((pid = wait3(&statloc,WNOHANG,NULL)) != 0) { int exitcode = WEXITSTATUS(statloc); int bysignal = 0; if (WIFSIGNALED(statloc)) bysignal = WTERMSIG(statloc); if (pid == -1) { serverLog(LL_WARNING,"wait3() returned an error: %s. " "rdb_child_pid = %d, aof_child_pid = %d", strerror(errno), (int) server.rdb_child_pid, (int) server.aof_child_pid); } else if (pid == server.rdb_child_pid) { backgroundSaveDoneHandler(exitcode,bysignal); } else if (pid == server.aof_child_pid) { backgroundRewriteDoneHandler(exitcode,bysignal); } else { if (!ldbRemoveChild(pid)) { serverLog(LL_WARNING, "Warning, detected child with unmatched pid: %ld", (long)pid); } } updateDictResizePolicy(); } } else { /* If there is not a background saving/rewrite in progress check if * we have to save/rewrite now */ for (j = 0; j < server.saveparamslen; j++) { struct saveparam *sp = server.saveparams+j; /* Save if we reached the given amount of changes, * the given amount of seconds, and if the latest bgsave was * successful or if, in case of an error, at least * CONFIG_BGSAVE_RETRY_DELAY seconds already elapsed. */ if (server.dirty >= sp->changes && server.unixtime-server.lastsave > sp->seconds && (server.unixtime-server.lastbgsave_try > CONFIG_BGSAVE_RETRY_DELAY || server.lastbgsave_status == C_OK)) { serverLog(LL_NOTICE,"%d changes in %d seconds. Saving...", sp->changes, (int)sp->seconds); rdbSaveBackground(server.rdb_filename); break; } } /* Trigger an AOF rewrite if needed */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.aof_rewrite_perc && server.aof_current_size > server.aof_rewrite_min_size) { long long base = server.aof_rewrite_base_size ? server.aof_rewrite_base_size : 1; long long growth = (server.aof_current_size*100/base) - 100; if (growth >= server.aof_rewrite_perc) { serverLog(LL_NOTICE,"Starting automatic rewriting of AOF on %lld%% growth",growth); rewriteAppendOnlyFileBackground(); } } } /* AOF postponed flush: Try at every cron cycle if the slow fsync * completed. */ if (server.aof_flush_postponed_start) flushAppendOnlyFile(0); /* AOF write errors: in this case we have a buffer to flush as well and * clear the AOF error in case of success to make the DB writable again, * however to try every second is enough in case of 'hz' is set to * an higher frequency. */ run_with_period(1000) { if (server.aof_last_write_status == C_ERR) flushAppendOnlyFile(0); } /* Close clients that need to be closed asynchronous */ freeClientsInAsyncFreeQueue(); /* Clear the paused clients flag if needed. */ clientsArePaused(); /* Don't check return value, just use the side effect. */ /* Replication cron function -- used to reconnect to master, * detect transfer failures, start background RDB transfers and so forth. */ run_with_period(1000) replicationCron(); /* Run the Redis Cluster cron. */ run_with_period(100) { if (server.cluster_enabled) clusterCron(); } /* Run the Sentinel timer if we are in sentinel mode. */ run_with_period(100) { if (server.sentinel_mode) sentinelTimer(); } /* Cleanup expired MIGRATE cached sockets. */ run_with_period(1000) { migrateCloseTimedoutSockets(); } /* Start a scheduled BGSAVE if the corresponding flag is set. This is * useful when we are forced to postpone a BGSAVE because an AOF * rewrite is in progress. * * Note: this code must be after the replicationCron() call above so * make sure when refactoring this file to keep this order. This is useful * because we want to give priority to RDB savings for replication. */ if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.rdb_bgsave_scheduled && (server.unixtime-server.lastbgsave_try > CONFIG_BGSAVE_RETRY_DELAY || server.lastbgsave_status == C_OK)) { if (rdbSaveBackground(server.rdb_filename) == C_OK) server.rdb_bgsave_scheduled = 0; } server.cronloops++; return 1000/server.hz; } /* This function gets called every time Redis is entering the * main loop of the event driven library, that is, before to sleep * for ready file descriptors. */ void beforeSleep(struct aeEventLoop *eventLoop) { UNUSED(eventLoop); /* Call the Redis Cluster before sleep function. Note that this function * may change the state of Redis Cluster (from ok to fail or vice versa), * so it's a good idea to call it before serving the unblocked clients * later in this function. */ if (server.cluster_enabled) clusterBeforeSleep(); /* Run a fast expire cycle (the called function will return * ASAP if a fast cycle is not needed). */ if (server.active_expire_enabled && server.masterhost == NULL) activeExpireCycle(ACTIVE_EXPIRE_CYCLE_FAST); /* Send all the slaves an ACK request if at least one client blocked * during the previous event loop iteration. */ if (server.get_ack_from_slaves) { robj *argv[3]; argv[0] = createStringObject("REPLCONF",8); argv[1] = createStringObject("GETACK",6); argv[2] = createStringObject("*",1); /* Not used argument. */ replicationFeedSlaves(server.slaves, server.slaveseldb, argv, 3); decrRefCount(argv[0]); decrRefCount(argv[1]); decrRefCount(argv[2]); server.get_ack_from_slaves = 0; } /* Unblock all the clients blocked for synchronous replication * in WAIT. */ if (listLength(server.clients_waiting_acks)) processClientsWaitingReplicas(); /* Try to process pending commands for clients that were just unblocked. */ if (listLength(server.unblocked_clients)) processUnblockedClients(); /* Write the AOF buffer on disk */ flushAppendOnlyFile(0); /* Handle writes with pending output buffers. */ handleClientsWithPendingWrites(); } /* =========================== Server initialization ======================== */ void createSharedObjects(void) { int j; shared.crlf = createObject(OBJ_STRING,sdsnew("\r\n")); shared.ok = createObject(OBJ_STRING,sdsnew("+OK\r\n")); shared.err = createObject(OBJ_STRING,sdsnew("-ERR\r\n")); shared.emptybulk = createObject(OBJ_STRING,sdsnew("$0\r\n\r\n")); shared.czero = createObject(OBJ_STRING,sdsnew(":0\r\n")); shared.cone = createObject(OBJ_STRING,sdsnew(":1\r\n")); shared.cnegone = createObject(OBJ_STRING,sdsnew(":-1\r\n")); shared.nullbulk = createObject(OBJ_STRING,sdsnew("$-1\r\n")); shared.nullmultibulk = createObject(OBJ_STRING,sdsnew("*-1\r\n")); shared.emptymultibulk = createObject(OBJ_STRING,sdsnew("*0\r\n")); shared.pong = createObject(OBJ_STRING,sdsnew("+PONG\r\n")); shared.queued = createObject(OBJ_STRING,sdsnew("+QUEUED\r\n")); shared.emptyscan = createObject(OBJ_STRING,sdsnew("*2\r\n$1\r\n0\r\n*0\r\n")); shared.wrongtypeerr = createObject(OBJ_STRING,sdsnew( "-WRONGTYPE Operation against a key holding the wrong kind of value\r\n")); shared.nokeyerr = createObject(OBJ_STRING,sdsnew( "-ERR no such key\r\n")); shared.syntaxerr = createObject(OBJ_STRING,sdsnew( "-ERR syntax error\r\n")); shared.sameobjecterr = createObject(OBJ_STRING,sdsnew( "-ERR source and destination objects are the same\r\n")); shared.outofrangeerr = createObject(OBJ_STRING,sdsnew( "-ERR index out of range\r\n")); shared.noscripterr = createObject(OBJ_STRING,sdsnew( "-NOSCRIPT No matching script. Please use EVAL.\r\n")); shared.loadingerr = createObject(OBJ_STRING,sdsnew( "-LOADING Redis is loading the dataset in memory\r\n")); shared.slowscripterr = createObject(OBJ_STRING,sdsnew( "-BUSY Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.\r\n")); shared.masterdownerr = createObject(OBJ_STRING,sdsnew( "-MASTERDOWN Link with MASTER is down and slave-serve-stale-data is set to 'no'.\r\n")); shared.bgsaveerr = createObject(OBJ_STRING,sdsnew( "-MISCONF Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.\r\n")); shared.roslaveerr = createObject(OBJ_STRING,sdsnew( "-READONLY You can't write against a read only slave.\r\n")); shared.noautherr = createObject(OBJ_STRING,sdsnew( "-NOAUTH Authentication required.\r\n")); shared.oomerr = createObject(OBJ_STRING,sdsnew( "-OOM command not allowed when used memory > 'maxmemory'.\r\n")); shared.execaborterr = createObject(OBJ_STRING,sdsnew( "-EXECABORT Transaction discarded because of previous errors.\r\n")); shared.noreplicaserr = createObject(OBJ_STRING,sdsnew( "-NOREPLICAS Not enough good slaves to write.\r\n")); shared.busykeyerr = createObject(OBJ_STRING,sdsnew( "-BUSYKEY Target key name already exists.\r\n")); shared.space = createObject(OBJ_STRING,sdsnew(" ")); shared.colon = createObject(OBJ_STRING,sdsnew(":")); shared.plus = createObject(OBJ_STRING,sdsnew("+")); for (j = 0; j < PROTO_SHARED_SELECT_CMDS; j++) { char dictid_str[64]; int dictid_len; dictid_len = ll2string(dictid_str,sizeof(dictid_str),j); shared.select[j] = createObject(OBJ_STRING, sdscatprintf(sdsempty(), "*2\r\n$6\r\nSELECT\r\n$%d\r\n%s\r\n", dictid_len, dictid_str)); } shared.messagebulk = createStringObject("$7\r\nmessage\r\n",13); shared.pmessagebulk = createStringObject("$8\r\npmessage\r\n",14); shared.subscribebulk = createStringObject("$9\r\nsubscribe\r\n",15); shared.unsubscribebulk = createStringObject("$11\r\nunsubscribe\r\n",18); shared.psubscribebulk = createStringObject("$10\r\npsubscribe\r\n",17); shared.punsubscribebulk = createStringObject("$12\r\npunsubscribe\r\n",19); shared.del = createStringObject("DEL",3); shared.rpop = createStringObject("RPOP",4); shared.lpop = createStringObject("LPOP",4); shared.lpush = createStringObject("LPUSH",5); for (j = 0; j < OBJ_SHARED_INTEGERS; j++) { shared.integers[j] = createObject(OBJ_STRING,(void*)(long)j); shared.integers[j]->encoding = OBJ_ENCODING_INT; } for (j = 0; j < OBJ_SHARED_BULKHDR_LEN; j++) { shared.mbulkhdr[j] = createObject(OBJ_STRING, sdscatprintf(sdsempty(),"*%d\r\n",j)); shared.bulkhdr[j] = createObject(OBJ_STRING, sdscatprintf(sdsempty(),"$%d\r\n",j)); } /* The following two shared objects, minstring and maxstrings, are not * actually used for their value but as a special object meaning * respectively the minimum possible string and the maximum possible * string in string comparisons for the ZRANGEBYLEX command. */ shared.minstring = createStringObject("minstring",9); shared.maxstring = createStringObject("maxstring",9); } void initServerConfig(void) { int j; getRandomHexChars(server.runid,CONFIG_RUN_ID_SIZE); server.configfile = NULL; server.executable = NULL; server.hz = CONFIG_DEFAULT_HZ; server.runid[CONFIG_RUN_ID_SIZE] = '\0'; server.arch_bits = (sizeof(long) == 8) ? 64 : 32; server.port = CONFIG_DEFAULT_SERVER_PORT; server.tcp_backlog = CONFIG_DEFAULT_TCP_BACKLOG; server.bindaddr_count = 0; server.unixsocket = NULL; server.unixsocketperm = CONFIG_DEFAULT_UNIX_SOCKET_PERM; server.ipfd_count = 0; server.sofd = -1; server.protected_mode = CONFIG_DEFAULT_PROTECTED_MODE; server.dbnum = CONFIG_DEFAULT_DBNUM; server.verbosity = CONFIG_DEFAULT_VERBOSITY; server.maxidletime = CONFIG_DEFAULT_CLIENT_TIMEOUT; server.tcpkeepalive = CONFIG_DEFAULT_TCP_KEEPALIVE; server.active_expire_enabled = 1; server.client_max_querybuf_len = PROTO_MAX_QUERYBUF_LEN; server.saveparams = NULL; server.loading = 0; server.logfile = zstrdup(CONFIG_DEFAULT_LOGFILE); server.syslog_enabled = CONFIG_DEFAULT_SYSLOG_ENABLED; server.syslog_ident = zstrdup(CONFIG_DEFAULT_SYSLOG_IDENT); server.syslog_facility = LOG_LOCAL0; server.daemonize = CONFIG_DEFAULT_DAEMONIZE; server.supervised = 0; server.supervised_mode = SUPERVISED_NONE; server.aof_state = AOF_OFF; server.aof_fsync = CONFIG_DEFAULT_AOF_FSYNC; server.aof_no_fsync_on_rewrite = CONFIG_DEFAULT_AOF_NO_FSYNC_ON_REWRITE; server.aof_rewrite_perc = AOF_REWRITE_PERC; server.aof_rewrite_min_size = AOF_REWRITE_MIN_SIZE; server.aof_rewrite_base_size = 0; server.aof_rewrite_scheduled = 0; server.aof_last_fsync = time(NULL); server.aof_rewrite_time_last = -1; server.aof_rewrite_time_start = -1; server.aof_lastbgrewrite_status = C_OK; server.aof_delayed_fsync = 0; server.aof_fd = -1; server.aof_selected_db = -1; /* Make sure the first time will not match */ server.aof_flush_postponed_start = 0; server.aof_rewrite_incremental_fsync = CONFIG_DEFAULT_AOF_REWRITE_INCREMENTAL_FSYNC; server.aof_load_truncated = CONFIG_DEFAULT_AOF_LOAD_TRUNCATED; server.pidfile = NULL; server.rdb_filename = zstrdup(CONFIG_DEFAULT_RDB_FILENAME); server.aof_filename = zstrdup(CONFIG_DEFAULT_AOF_FILENAME); server.requirepass = NULL; server.rdb_compression = CONFIG_DEFAULT_RDB_COMPRESSION; server.rdb_checksum = CONFIG_DEFAULT_RDB_CHECKSUM; server.stop_writes_on_bgsave_err = CONFIG_DEFAULT_STOP_WRITES_ON_BGSAVE_ERROR; server.activerehashing = CONFIG_DEFAULT_ACTIVE_REHASHING; server.notify_keyspace_events = 0; server.maxclients = CONFIG_DEFAULT_MAX_CLIENTS; server.bpop_blocked_clients = 0; server.maxmemory = CONFIG_DEFAULT_MAXMEMORY; server.maxmemory_policy = CONFIG_DEFAULT_MAXMEMORY_POLICY; server.maxmemory_samples = CONFIG_DEFAULT_MAXMEMORY_SAMPLES; server.hash_max_ziplist_entries = OBJ_HASH_MAX_ZIPLIST_ENTRIES; server.hash_max_ziplist_value = OBJ_HASH_MAX_ZIPLIST_VALUE; server.list_max_ziplist_size = OBJ_LIST_MAX_ZIPLIST_SIZE; server.list_compress_depth = OBJ_LIST_COMPRESS_DEPTH; server.set_max_intset_entries = OBJ_SET_MAX_INTSET_ENTRIES; server.zset_max_ziplist_entries = OBJ_ZSET_MAX_ZIPLIST_ENTRIES; server.zset_max_ziplist_value = OBJ_ZSET_MAX_ZIPLIST_VALUE; server.hll_sparse_max_bytes = CONFIG_DEFAULT_HLL_SPARSE_MAX_BYTES; server.shutdown_asap = 0; server.repl_ping_slave_period = CONFIG_DEFAULT_REPL_PING_SLAVE_PERIOD; server.repl_timeout = CONFIG_DEFAULT_REPL_TIMEOUT; server.repl_min_slaves_to_write = CONFIG_DEFAULT_MIN_SLAVES_TO_WRITE; server.repl_min_slaves_max_lag = CONFIG_DEFAULT_MIN_SLAVES_MAX_LAG; server.cluster_enabled = 0; server.cluster_node_timeout = CLUSTER_DEFAULT_NODE_TIMEOUT; server.cluster_migration_barrier = CLUSTER_DEFAULT_MIGRATION_BARRIER; server.cluster_slave_validity_factor = CLUSTER_DEFAULT_SLAVE_VALIDITY; server.cluster_require_full_coverage = CLUSTER_DEFAULT_REQUIRE_FULL_COVERAGE; server.cluster_configfile = zstrdup(CONFIG_DEFAULT_CLUSTER_CONFIG_FILE); server.migrate_cached_sockets = dictCreate(&migrateCacheDictType,NULL); server.next_client_id = 1; /* Client IDs, start from 1 .*/ server.loading_process_events_interval_bytes = (1024*1024*2); server.lruclock = getLRUClock(); resetServerSaveParams(); appendServerSaveParams(60*60,1); /* save after 1 hour and 1 change */ appendServerSaveParams(300,100); /* save after 5 minutes and 100 changes */ appendServerSaveParams(60,10000); /* save after 1 minute and 10000 changes */ /* Replication related */ server.masterauth = NULL; server.masterhost = NULL; server.masterport = 6379; server.master = NULL; server.cached_master = NULL; server.repl_master_initial_offset = -1; server.repl_state = REPL_STATE_NONE; server.repl_syncio_timeout = CONFIG_REPL_SYNCIO_TIMEOUT; server.repl_serve_stale_data = CONFIG_DEFAULT_SLAVE_SERVE_STALE_DATA; server.repl_slave_ro = CONFIG_DEFAULT_SLAVE_READ_ONLY; server.repl_down_since = 0; /* Never connected, repl is down since EVER. */ server.repl_disable_tcp_nodelay = CONFIG_DEFAULT_REPL_DISABLE_TCP_NODELAY; server.repl_diskless_sync = CONFIG_DEFAULT_REPL_DISKLESS_SYNC; server.repl_diskless_sync_delay = CONFIG_DEFAULT_REPL_DISKLESS_SYNC_DELAY; server.slave_priority = CONFIG_DEFAULT_SLAVE_PRIORITY; server.slave_announce_ip = CONFIG_DEFAULT_SLAVE_ANNOUNCE_IP; server.slave_announce_port = CONFIG_DEFAULT_SLAVE_ANNOUNCE_PORT; server.master_repl_offset = 0; /* Replication partial resync backlog */ server.repl_backlog = NULL; server.repl_backlog_size = CONFIG_DEFAULT_REPL_BACKLOG_SIZE; server.repl_backlog_histlen = 0; server.repl_backlog_idx = 0; server.repl_backlog_off = 0; server.repl_backlog_time_limit = CONFIG_DEFAULT_REPL_BACKLOG_TIME_LIMIT; server.repl_no_slaves_since = time(NULL); /* Client output buffer limits */ for (j = 0; j < CLIENT_TYPE_OBUF_COUNT; j++) server.client_obuf_limits[j] = clientBufferLimitsDefaults[j]; /* Double constants initialization */ R_Zero = 0.0; R_PosInf = 1.0/R_Zero; R_NegInf = -1.0/R_Zero; R_Nan = R_Zero/R_Zero; /* Command table -- we initiialize it here as it is part of the * initial configuration, since command names may be changed via * redis.conf using the rename-command directive. */ server.commands = dictCreate(&commandTableDictType,NULL); server.orig_commands = dictCreate(&commandTableDictType,NULL); populateCommandTable(); server.delCommand = lookupCommandByCString("del"); server.multiCommand = lookupCommandByCString("multi"); server.lpushCommand = lookupCommandByCString("lpush"); server.lpopCommand = lookupCommandByCString("lpop"); server.rpopCommand = lookupCommandByCString("rpop"); server.sremCommand = lookupCommandByCString("srem"); server.execCommand = lookupCommandByCString("exec"); /* Slow log */ server.slowlog_log_slower_than = CONFIG_DEFAULT_SLOWLOG_LOG_SLOWER_THAN; server.slowlog_max_len = CONFIG_DEFAULT_SLOWLOG_MAX_LEN; /* Latency monitor */ server.latency_monitor_threshold = CONFIG_DEFAULT_LATENCY_MONITOR_THRESHOLD; /* Debugging */ server.assert_failed = "<no assertion failed>"; server.assert_file = "<no file>"; server.assert_line = 0; server.bug_report_start = 0; server.watchdog_period = 0; } extern char **environ; /* Restart the server, executing the same executable that started this * instance, with the same arguments and configuration file. * * The function is designed to directly call execve() so that the new * server instance will retain the PID of the previous one. * * The list of flags, that may be bitwise ORed together, alter the * behavior of this function: * * RESTART_SERVER_NONE No flags. * RESTART_SERVER_GRACEFULLY Do a proper shutdown before restarting. * RESTART_SERVER_CONFIG_REWRITE Rewrite the config file before restarting. * * On success the function does not return, because the process turns into * a different process. On error C_ERR is returned. */ int restartServer(int flags, mstime_t delay) { int j; /* Check if we still have accesses to the executable that started this * server instance. */ if (access(server.executable,X_OK) == -1) return C_ERR; /* Config rewriting. */ if (flags & RESTART_SERVER_CONFIG_REWRITE && server.configfile && rewriteConfig(server.configfile) == -1) return C_ERR; /* Perform a proper shutdown. */ if (flags & RESTART_SERVER_GRACEFULLY && prepareForShutdown(SHUTDOWN_NOFLAGS) != C_OK) return C_ERR; /* Close all file descriptors, with the exception of stdin, stdout, strerr * which are useful if we restart a Redis server which is not daemonized. */ for (j = 3; j < (int)server.maxclients + 1024; j++) close(j); /* Execute the server with the original command line. */ if (delay) usleep(delay*1000); execve(server.executable,server.exec_argv,environ); /* If an error occurred here, there is nothing we can do, but exit. */ _exit(1); return C_ERR; /* Never reached. */ } /* This function will try to raise the max number of open files accordingly to * the configured max number of clients. It also reserves a number of file * descriptors (CONFIG_MIN_RESERVED_FDS) for extra operations of * persistence, listening sockets, log files and so forth. * * If it will not be possible to set the limit accordingly to the configured * max number of clients, the function will do the reverse setting * server.maxclients to the value that we can actually handle. */ void adjustOpenFilesLimit(void) { rlim_t maxfiles = server.maxclients+CONFIG_MIN_RESERVED_FDS; struct rlimit limit; if (getrlimit(RLIMIT_NOFILE,&limit) == -1) { serverLog(LL_WARNING,"Unable to obtain the current NOFILE limit (%s), assuming 1024 and setting the max clients configuration accordingly.", strerror(errno)); server.maxclients = 1024-CONFIG_MIN_RESERVED_FDS; } else { rlim_t oldlimit = limit.rlim_cur; /* Set the max number of files if the current limit is not enough * for our needs. */ if (oldlimit < maxfiles) { rlim_t bestlimit; int setrlimit_error = 0; /* Try to set the file limit to match 'maxfiles' or at least * to the higher value supported less than maxfiles. */ bestlimit = maxfiles; while(bestlimit > oldlimit) { rlim_t decr_step = 16; limit.rlim_cur = bestlimit; limit.rlim_max = bestlimit; if (setrlimit(RLIMIT_NOFILE,&limit) != -1) break; setrlimit_error = errno; /* We failed to set file limit to 'bestlimit'. Try with a * smaller limit decrementing by a few FDs per iteration. */ if (bestlimit < decr_step) break; bestlimit -= decr_step; } /* Assume that the limit we get initially is still valid if * our last try was even lower. */ if (bestlimit < oldlimit) bestlimit = oldlimit; if (bestlimit < maxfiles) { int old_maxclients = server.maxclients; server.maxclients = bestlimit-CONFIG_MIN_RESERVED_FDS; if (server.maxclients < 1) { serverLog(LL_WARNING,"Your current 'ulimit -n' " "of %llu is not enough for the server to start. " "Please increase your open file limit to at least " "%llu. Exiting.", (unsigned long long) oldlimit, (unsigned long long) maxfiles); exit(1); } serverLog(LL_WARNING,"You requested maxclients of %d " "requiring at least %llu max file descriptors.", old_maxclients, (unsigned long long) maxfiles); serverLog(LL_WARNING,"Server can't set maximum open files " "to %llu because of OS error: %s.", (unsigned long long) maxfiles, strerror(setrlimit_error)); serverLog(LL_WARNING,"Current maximum open files is %llu. " "maxclients has been reduced to %d to compensate for " "low ulimit. " "If you need higher maxclients increase 'ulimit -n'.", (unsigned long long) bestlimit, server.maxclients); } else { serverLog(LL_NOTICE,"Increased maximum number of open files " "to %llu (it was originally set to %llu).", (unsigned long long) maxfiles, (unsigned long long) oldlimit); } } } } /* Check that server.tcp_backlog can be actually enforced in Linux according * to the value of /proc/sys/net/core/somaxconn, or warn about it. */ void checkTcpBacklogSettings(void) { #ifdef HAVE_PROC_SOMAXCONN FILE *fp = fopen("/proc/sys/net/core/somaxconn","r"); char buf[1024]; if (!fp) return; if (fgets(buf,sizeof(buf),fp) != NULL) { int somaxconn = atoi(buf); if (somaxconn > 0 && somaxconn < server.tcp_backlog) { serverLog(LL_WARNING,"WARNING: The TCP backlog setting of %d cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of %d.", server.tcp_backlog, somaxconn); } } fclose(fp); #endif } /* Initialize a set of file descriptors to listen to the specified 'port' * binding the addresses specified in the Redis server configuration. * * The listening file descriptors are stored in the integer array 'fds' * and their number is set in '*count'. * * The addresses to bind are specified in the global server.bindaddr array * and their number is server.bindaddr_count. If the server configuration * contains no specific addresses to bind, this function will try to * bind * (all addresses) for both the IPv4 and IPv6 protocols. * * On success the function returns C_OK. * * On error the function returns C_ERR. For the function to be on * error, at least one of the server.bindaddr addresses was * impossible to bind, or no bind addresses were specified in the server * configuration but the function is not able to bind * for at least * one of the IPv4 or IPv6 protocols. */ int listenToPort(int port, int *fds, int *count) { int j; /* Force binding of 0.0.0.0 if no bind address is specified, always * entering the loop if j == 0. */ if (server.bindaddr_count == 0) server.bindaddr[0] = NULL; for (j = 0; j < server.bindaddr_count || j == 0; j++) { if (server.bindaddr[j] == NULL) { int unsupported = 0; /* Bind * for both IPv6 and IPv4, we enter here only if * server.bindaddr_count == 0. */ fds[*count] = anetTcp6Server(server.neterr,port,NULL, server.tcp_backlog); if (fds[*count] != ANET_ERR) { anetNonBlock(NULL,fds[*count]); (*count)++; } else if (errno == EAFNOSUPPORT) { unsupported++; serverLog(LL_WARNING,"Not listening to IPv6: unsupproted"); } if (*count == 1 || unsupported) { /* Bind the IPv4 address as well. */ fds[*count] = anetTcpServer(server.neterr,port,NULL, server.tcp_backlog); if (fds[*count] != ANET_ERR) { anetNonBlock(NULL,fds[*count]); (*count)++; } else if (errno == EAFNOSUPPORT) { unsupported++; serverLog(LL_WARNING,"Not listening to IPv4: unsupproted"); } } /* Exit the loop if we were able to bind * on IPv4 and IPv6, * otherwise fds[*count] will be ANET_ERR and we'll print an * error and return to the caller with an error. */ if (*count + unsupported == 2) break; } else if (strchr(server.bindaddr[j],':')) { /* Bind IPv6 address. */ fds[*count] = anetTcp6Server(server.neterr,port,server.bindaddr[j], server.tcp_backlog); } else { /* Bind IPv4 address. */ fds[*count] = anetTcpServer(server.neterr,port,server.bindaddr[j], server.tcp_backlog); } if (fds[*count] == ANET_ERR) { serverLog(LL_WARNING, "Creating Server TCP listening socket %s:%d: %s", server.bindaddr[j] ? server.bindaddr[j] : "*", port, server.neterr); return C_ERR; } anetNonBlock(NULL,fds[*count]); (*count)++; } return C_OK; } /* Resets the stats that we expose via INFO or other means that we want * to reset via CONFIG RESETSTAT. The function is also used in order to * initialize these fields in initServer() at server startup. */ void resetServerStats(void) { int j; server.stat_numcommands = 0; server.stat_numconnections = 0; server.stat_expiredkeys = 0; server.stat_evictedkeys = 0; server.stat_keyspace_misses = 0; server.stat_keyspace_hits = 0; server.stat_fork_time = 0; server.stat_fork_rate = 0; server.stat_rejected_conn = 0; server.stat_sync_full = 0; server.stat_sync_partial_ok = 0; server.stat_sync_partial_err = 0; for (j = 0; j < STATS_METRIC_COUNT; j++) { server.inst_metric[j].idx = 0; server.inst_metric[j].last_sample_time = mstime(); server.inst_metric[j].last_sample_count = 0; memset(server.inst_metric[j].samples,0, sizeof(server.inst_metric[j].samples)); } server.stat_net_input_bytes = 0; server.stat_net_output_bytes = 0; server.aof_delayed_fsync = 0; } void initServer(void) { int j; signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); setupSignalHandlers(); if (server.syslog_enabled) { openlog(server.syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT, server.syslog_facility); } server.pid = getpid(); server.current_client = NULL; server.clients = listCreate(); server.clients_to_close = listCreate(); server.slaves = listCreate(); server.monitors = listCreate(); server.clients_pending_write = listCreate(); server.slaveseldb = -1; /* Force to emit the first SELECT command. */ server.unblocked_clients = listCreate(); server.ready_keys = listCreate(); server.clients_waiting_acks = listCreate(); server.get_ack_from_slaves = 0; server.clients_paused = 0; server.system_memory_size = zmalloc_get_memory_size(); createSharedObjects(); adjustOpenFilesLimit(); server.el = aeCreateEventLoop(server.maxclients+CONFIG_FDSET_INCR); server.db = zmalloc(sizeof(redisDb)*server.dbnum); /* Open the TCP listening socket for the user commands. */ if (server.port != 0 && listenToPort(server.port,server.ipfd,&server.ipfd_count) == C_ERR) exit(1); /* Open the listening Unix domain socket. */ if (server.unixsocket != NULL) { unlink(server.unixsocket); /* don't care if this fails */ server.sofd = anetUnixServer(server.neterr,server.unixsocket, server.unixsocketperm, server.tcp_backlog); if (server.sofd == ANET_ERR) { serverLog(LL_WARNING, "Opening Unix socket: %s", server.neterr); exit(1); } anetNonBlock(NULL,server.sofd); } /* Abort if there are no listening sockets at all. */ if (server.ipfd_count == 0 && server.sofd < 0) { serverLog(LL_WARNING, "Configured to not listen anywhere, exiting."); exit(1); } /* Create the Redis databases, and initialize other internal state. */ for (j = 0; j < server.dbnum; j++) { server.db[j].dict = dictCreate(&dbDictType,NULL); server.db[j].expires = dictCreate(&keyptrDictType,NULL); server.db[j].blocking_keys = dictCreate(&keylistDictType,NULL); server.db[j].ready_keys = dictCreate(&setDictType,NULL); server.db[j].watched_keys = dictCreate(&keylistDictType,NULL); server.db[j].eviction_pool = evictionPoolAlloc(); server.db[j].id = j; server.db[j].avg_ttl = 0; } server.pubsub_channels = dictCreate(&keylistDictType,NULL); server.pubsub_patterns = listCreate(); listSetFreeMethod(server.pubsub_patterns,freePubsubPattern); listSetMatchMethod(server.pubsub_patterns,listMatchPubsubPattern); server.cronloops = 0; server.rdb_child_pid = -1; server.aof_child_pid = -1; server.rdb_child_type = RDB_CHILD_TYPE_NONE; server.rdb_bgsave_scheduled = 0; aofRewriteBufferReset(); server.aof_buf = sdsempty(); server.lastsave = time(NULL); /* At startup we consider the DB saved. */ server.lastbgsave_try = 0; /* At startup we never tried to BGSAVE. */ server.rdb_save_time_last = -1; server.rdb_save_time_start = -1; server.dirty = 0; resetServerStats(); /* A few stats we don't want to reset: server startup time, and peak mem. */ server.stat_starttime = time(NULL); server.stat_peak_memory = 0; server.resident_set_size = 0; server.lastbgsave_status = C_OK; server.aof_last_write_status = C_OK; server.aof_last_write_errno = 0; server.repl_good_slaves_count = 0; updateCachedTime(); /* Create the serverCron() time event, that's our main way to process * background operations. */ if(aeCreateTimeEvent(server.el, 1, serverCron, NULL, NULL) == AE_ERR) { serverPanic("Can't create the serverCron time event."); exit(1); } /* Create an event handler for accepting new connections in TCP and Unix * domain sockets. */ for (j = 0; j < server.ipfd_count; j++) { if (aeCreateFileEvent(server.el, server.ipfd[j], AE_READABLE, acceptTcpHandler,NULL) == AE_ERR) { serverPanic( "Unrecoverable error creating server.ipfd file event."); } } if (server.sofd > 0 && aeCreateFileEvent(server.el,server.sofd,AE_READABLE, acceptUnixHandler,NULL) == AE_ERR) serverPanic("Unrecoverable error creating server.sofd file event."); /* Open the AOF file if needed. */ if (server.aof_state == AOF_ON) { server.aof_fd = open(server.aof_filename, O_WRONLY|O_APPEND|O_CREAT,0644); if (server.aof_fd == -1) { serverLog(LL_WARNING, "Can't open the append-only file: %s", strerror(errno)); exit(1); } } /* 32 bit instances are limited to 4GB of address space, so if there is * no explicit limit in the user provided configuration we set a limit * at 3 GB using maxmemory with 'noeviction' policy'. This avoids * useless crashes of the Redis instance for out of memory. */ if (server.arch_bits == 32 && server.maxmemory == 0) { serverLog(LL_WARNING,"Warning: 32 bit instance detected but no memory limit set. Setting 3 GB maxmemory limit with 'noeviction' policy now."); server.maxmemory = 3072LL*(1024*1024); /* 3 GB */ server.maxmemory_policy = MAXMEMORY_NO_EVICTION; } if (server.cluster_enabled) clusterInit(); replicationScriptCacheInit(); scriptingInit(1); slowlogInit(); latencyMonitorInit(); bioInit(); } /* Populates the Redis Command Table starting from the hard coded list * we have on top of redis.c file. */ void populateCommandTable(void) { int j; int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; char *f = c->sflags; int retval1, retval2; while(*f != '\0') { switch(*f) { case 'w': c->flags |= CMD_WRITE; break; case 'r': c->flags |= CMD_READONLY; break; case 'm': c->flags |= CMD_DENYOOM; break; case 'a': c->flags |= CMD_ADMIN; break; case 'p': c->flags |= CMD_PUBSUB; break; case 's': c->flags |= CMD_NOSCRIPT; break; case 'R': c->flags |= CMD_RANDOM; break; case 'S': c->flags |= CMD_SORT_FOR_SCRIPT; break; case 'l': c->flags |= CMD_LOADING; break; case 't': c->flags |= CMD_STALE; break; case 'M': c->flags |= CMD_SKIP_MONITOR; break; case 'k': c->flags |= CMD_ASKING; break; case 'F': c->flags |= CMD_FAST; break; default: serverPanic("Unsupported command flag"); break; } f++; } retval1 = dictAdd(server.commands, sdsnew(c->name), c); /* Populate an additional dictionary that will be unaffected * by rename-command statements in redis.conf. */ retval2 = dictAdd(server.orig_commands, sdsnew(c->name), c); serverAssert(retval1 == DICT_OK && retval2 == DICT_OK); } } void resetCommandTableStats(void) { int numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); int j; for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; c->microseconds = 0; c->calls = 0; } } /* ========================== Redis OP Array API ============================ */ void redisOpArrayInit(redisOpArray *oa) { oa->ops = NULL; oa->numops = 0; } int redisOpArrayAppend(redisOpArray *oa, struct redisCommand *cmd, int dbid, robj **argv, int argc, int target) { redisOp *op; oa->ops = zrealloc(oa->ops,sizeof(redisOp)*(oa->numops+1)); op = oa->ops+oa->numops; op->cmd = cmd; op->dbid = dbid; op->argv = argv; op->argc = argc; op->target = target; oa->numops++; return oa->numops; } void redisOpArrayFree(redisOpArray *oa) { while(oa->numops) { int j; redisOp *op; oa->numops--; op = oa->ops+oa->numops; for (j = 0; j < op->argc; j++) decrRefCount(op->argv[j]); zfree(op->argv); } zfree(oa->ops); } /* ====================== Commands lookup and execution ===================== */ struct redisCommand *lookupCommand(sds name) { return dictFetchValue(server.commands, name); } struct redisCommand *lookupCommandByCString(char *s) { struct redisCommand *cmd; sds name = sdsnew(s); cmd = dictFetchValue(server.commands, name); sdsfree(name); return cmd; } /* Lookup the command in the current table, if not found also check in * the original table containing the original command names unaffected by * redis.conf rename-command statement. * * This is used by functions rewriting the argument vector such as * rewriteClientCommandVector() in order to set client->cmd pointer * correctly even if the command was renamed. */ struct redisCommand *lookupCommandOrOriginal(sds name) { struct redisCommand *cmd = dictFetchValue(server.commands, name); if (!cmd) cmd = dictFetchValue(server.orig_commands,name); return cmd; } /* Propagate the specified command (in the context of the specified database id) * to AOF and Slaves. * * flags are an xor between: * + PROPAGATE_NONE (no propagation of command at all) * + PROPAGATE_AOF (propagate into the AOF file if is enabled) * + PROPAGATE_REPL (propagate into the replication link) * * This should not be used inside commands implementation. Use instead * alsoPropagate(), preventCommandPropagation(), forceCommandPropagation(). */ void propagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int flags) { if (server.aof_state != AOF_OFF && flags & PROPAGATE_AOF) feedAppendOnlyFile(cmd,dbid,argv,argc); if (flags & PROPAGATE_REPL) replicationFeedSlaves(server.slaves,dbid,argv,argc); } /* Used inside commands to schedule the propagation of additional commands * after the current command is propagated to AOF / Replication. * * 'cmd' must be a pointer to the Redis command to replicate, dbid is the * database ID the command should be propagated into. * Arguments of the command to propagte are passed as an array of redis * objects pointers of len 'argc', using the 'argv' vector. * * The function does not take a reference to the passed 'argv' vector, * so it is up to the caller to release the passed argv (but it is usually * stack allocated). The function autoamtically increments ref count of * passed objects, so the caller does not need to. */ void alsoPropagate(struct redisCommand *cmd, int dbid, robj **argv, int argc, int target) { robj **argvcopy; int j; if (server.loading) return; /* No propagation during loading. */ argvcopy = zmalloc(sizeof(robj*)*argc); for (j = 0; j < argc; j++) { argvcopy[j] = argv[j]; incrRefCount(argv[j]); } redisOpArrayAppend(&server.also_propagate,cmd,dbid,argvcopy,argc,target); } /* It is possible to call the function forceCommandPropagation() inside a * Redis command implementation in order to to force the propagation of a * specific command execution into AOF / Replication. */ void forceCommandPropagation(client *c, int flags) { if (flags & PROPAGATE_REPL) c->flags |= CLIENT_FORCE_REPL; if (flags & PROPAGATE_AOF) c->flags |= CLIENT_FORCE_AOF; } /* Avoid that the executed command is propagated at all. This way we * are free to just propagate what we want using the alsoPropagate() * API. */ void preventCommandPropagation(client *c) { c->flags |= CLIENT_PREVENT_PROP; } /* AOF specific version of preventCommandPropagation(). */ void preventCommandAOF(client *c) { c->flags |= CLIENT_PREVENT_AOF_PROP; } /* Replication specific version of preventCommandPropagation(). */ void preventCommandReplication(client *c) { c->flags |= CLIENT_PREVENT_REPL_PROP; } /* Call() is the core of Redis execution of a command. * * The following flags can be passed: * CMD_CALL_NONE No flags. * CMD_CALL_SLOWLOG Check command speed and log in the slow log if needed. * CMD_CALL_STATS Populate command stats. * CMD_CALL_PROPAGATE_AOF Append command to AOF if it modified the dataset * or if the client flags are forcing propagation. * CMD_CALL_PROPAGATE_REPL Send command to salves if it modified the dataset * or if the client flags are forcing propagation. * CMD_CALL_PROPAGATE Alias for PROPAGATE_AOF|PROPAGATE_REPL. * CMD_CALL_FULL Alias for SLOWLOG|STATS|PROPAGATE. * * The exact propagation behavior depends on the client flags. * Specifically: * * 1. If the client flags CLIENT_FORCE_AOF or CLIENT_FORCE_REPL are set * and assuming the corresponding CMD_CALL_PROPAGATE_AOF/REPL is set * in the call flags, then the command is propagated even if the * dataset was not affected by the command. * 2. If the client flags CLIENT_PREVENT_REPL_PROP or CLIENT_PREVENT_AOF_PROP * are set, the propagation into AOF or to slaves is not performed even * if the command modified the dataset. * * Note that regardless of the client flags, if CMD_CALL_PROPAGATE_AOF * or CMD_CALL_PROPAGATE_REPL are not set, then respectively AOF or * slaves propagation will never occur. * * Client flags are modified by the implementation of a given command * using the following API: * * forceCommandPropagation(client *c, int flags); * preventCommandPropagation(client *c); * preventCommandAOF(client *c); * preventCommandReplication(client *c); * */ void call(client *c, int flags) { long long dirty, start, duration; int client_old_flags = c->flags; /* Sent the command to clients in MONITOR mode, only if the commands are * not generated from reading an AOF. */ if (listLength(server.monitors) && !server.loading && !(c->cmd->flags & (CMD_SKIP_MONITOR|CMD_ADMIN))) { replicationFeedMonitors(c,server.monitors,c->db->id,c->argv,c->argc); } /* Initialization: clear the flags that must be set by the command on * demand, and initialize the array for additional commands propagation. */ c->flags &= ~(CLIENT_FORCE_AOF|CLIENT_FORCE_REPL|CLIENT_PREVENT_PROP); redisOpArrayInit(&server.also_propagate); /* Call the command. */ dirty = server.dirty; start = ustime(); c->cmd->proc(c); duration = ustime()-start; dirty = server.dirty-dirty; if (dirty < 0) dirty = 0; /* When EVAL is called loading the AOF we don't want commands called * from Lua to go into the slowlog or to populate statistics. */ if (server.loading && c->flags & CLIENT_LUA) flags &= ~(CMD_CALL_SLOWLOG | CMD_CALL_STATS); /* If the caller is Lua, we want to force the EVAL caller to propagate * the script if the command flag or client flag are forcing the * propagation. */ if (c->flags & CLIENT_LUA && server.lua_caller) { if (c->flags & CLIENT_FORCE_REPL) server.lua_caller->flags |= CLIENT_FORCE_REPL; if (c->flags & CLIENT_FORCE_AOF) server.lua_caller->flags |= CLIENT_FORCE_AOF; } /* Log the command into the Slow log if needed, and populate the * per-command statistics that we show in INFO commandstats. */ if (flags & CMD_CALL_SLOWLOG && c->cmd->proc != execCommand) { char *latency_event = (c->cmd->flags & CMD_FAST) ? "fast-command" : "command"; latencyAddSampleIfNeeded(latency_event,duration/1000); slowlogPushEntryIfNeeded(c->argv,c->argc,duration); } if (flags & CMD_CALL_STATS) { c->lastcmd->microseconds += duration; c->lastcmd->calls++; } /* Propagate the command into the AOF and replication link */ if (flags & CMD_CALL_PROPAGATE && (c->flags & CLIENT_PREVENT_PROP) != CLIENT_PREVENT_PROP) { int propagate_flags = PROPAGATE_NONE; /* Check if the command operated changes in the data set. If so * set for replication / AOF propagation. */ if (dirty) propagate_flags |= (PROPAGATE_AOF|PROPAGATE_REPL); /* If the client forced AOF / replication of the command, set * the flags regardless of the command effects on the data set. */ if (c->flags & CLIENT_FORCE_REPL) propagate_flags |= PROPAGATE_REPL; if (c->flags & CLIENT_FORCE_AOF) propagate_flags |= PROPAGATE_AOF; /* However prevent AOF / replication propagation if the command * implementatino called preventCommandPropagation() or similar, * or if we don't have the call() flags to do so. */ if (c->flags & CLIENT_PREVENT_REPL_PROP || !(flags & CMD_CALL_PROPAGATE_REPL)) propagate_flags &= ~PROPAGATE_REPL; if (c->flags & CLIENT_PREVENT_AOF_PROP || !(flags & CMD_CALL_PROPAGATE_AOF)) propagate_flags &= ~PROPAGATE_AOF; /* Call propagate() only if at least one of AOF / replication * propagation is needed. */ if (propagate_flags != PROPAGATE_NONE) propagate(c->cmd,c->db->id,c->argv,c->argc,propagate_flags); } /* Restore the old replication flags, since call() can be executed * recursively. */ c->flags &= ~(CLIENT_FORCE_AOF|CLIENT_FORCE_REPL|CLIENT_PREVENT_PROP); c->flags |= client_old_flags & (CLIENT_FORCE_AOF|CLIENT_FORCE_REPL|CLIENT_PREVENT_PROP); /* Handle the alsoPropagate() API to handle commands that want to propagate * multiple separated commands. Note that alsoPropagate() is not affected * by CLIENT_PREVENT_PROP flag. */ if (server.also_propagate.numops) { int j; redisOp *rop; if (flags & CMD_CALL_PROPAGATE) { for (j = 0; j < server.also_propagate.numops; j++) { rop = &server.also_propagate.ops[j]; int target = rop->target; /* Whatever the command wish is, we honor the call() flags. */ if (!(flags&CMD_CALL_PROPAGATE_AOF)) target &= ~PROPAGATE_AOF; if (!(flags&CMD_CALL_PROPAGATE_REPL)) target &= ~PROPAGATE_REPL; if (target) propagate(rop->cmd,rop->dbid,rop->argv,rop->argc,target); } } redisOpArrayFree(&server.also_propagate); } server.stat_numcommands++; } /* If this function gets called we already read a whole * command, arguments are in the client argv/argc fields. * processCommand() execute the command or prepare the * server for a bulk read from the client. * * If C_OK is returned the client is still alive and valid and * other operations can be performed by the caller. Otherwise * if C_ERR is returned the client was destroyed (i.e. after QUIT). */ int processCommand(client *c) { /* The QUIT command is handled separately. Normal command procs will * go through checking for replication and QUIT will cause trouble * when FORCE_REPLICATION is enabled and would be implemented in * a regular command proc. */ if (!strcasecmp(c->argv[0]->ptr,"quit")) { addReply(c,shared.ok); c->flags |= CLIENT_CLOSE_AFTER_REPLY; return C_ERR; } /* Now lookup the command and check ASAP about trivial error conditions * such as wrong arity, bad command name and so forth. */ c->cmd = c->lastcmd = lookupCommand(c->argv[0]->ptr); if (!c->cmd) { flagTransaction(c); addReplyErrorFormat(c,"unknown command '%s'", (char*)c->argv[0]->ptr); return C_OK; } else if ((c->cmd->arity > 0 && c->cmd->arity != c->argc) || (c->argc < -c->cmd->arity)) { flagTransaction(c); addReplyErrorFormat(c,"wrong number of arguments for '%s' command", c->cmd->name); return C_OK; } /* Check if the user is authenticated */ if (server.requirepass && !c->authenticated && c->cmd->proc != authCommand) { flagTransaction(c); addReply(c,shared.noautherr); return C_OK; } /* If cluster is enabled perform the cluster redirection here. * However we don't perform the redirection if: * 1) The sender of this command is our master. * 2) The command has no key arguments. */ if (server.cluster_enabled && !(c->flags & CLIENT_MASTER) && !(c->flags & CLIENT_LUA && server.lua_caller->flags & CLIENT_MASTER) && !(c->cmd->getkeys_proc == NULL && c->cmd->firstkey == 0 && c->cmd->proc != execCommand)) { int hashslot; int error_code; clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc, &hashslot,&error_code); if (n == NULL || n != server.cluster->myself) { if (c->cmd->proc == execCommand) { discardTransaction(c); } else { flagTransaction(c); } clusterRedirectClient(c,n,hashslot,error_code); return C_OK; } } /* Handle the maxmemory directive. * * First we try to free some memory if possible (if there are volatile * keys in the dataset). If there are not the only thing we can do * is returning an error. */ if (server.maxmemory) { int retval = freeMemoryIfNeeded(); /* freeMemoryIfNeeded may flush slave output buffers. This may result * into a slave, that may be the active client, to be freed. */ if (server.current_client == NULL) return C_ERR; /* It was impossible to free enough memory, and the command the client * is trying to execute is denied during OOM conditions? Error. */ if ((c->cmd->flags & CMD_DENYOOM) && retval == C_ERR) { flagTransaction(c); addReply(c, shared.oomerr); return C_OK; } } /* Don't accept write commands if there are problems persisting on disk * and if this is a master instance. */ if (((server.stop_writes_on_bgsave_err && server.saveparamslen > 0 && server.lastbgsave_status == C_ERR) || server.aof_last_write_status == C_ERR) && server.masterhost == NULL && (c->cmd->flags & CMD_WRITE || c->cmd->proc == pingCommand)) { flagTransaction(c); if (server.aof_last_write_status == C_OK) addReply(c, shared.bgsaveerr); else addReplySds(c, sdscatprintf(sdsempty(), "-MISCONF Errors writing to the AOF file: %s\r\n", strerror(server.aof_last_write_errno))); return C_OK; } /* Don't accept write commands if there are not enough good slaves and * user configured the min-slaves-to-write option. */ if (server.masterhost == NULL && server.repl_min_slaves_to_write && server.repl_min_slaves_max_lag && c->cmd->flags & CMD_WRITE && server.repl_good_slaves_count < server.repl_min_slaves_to_write) { flagTransaction(c); addReply(c, shared.noreplicaserr); return C_OK; } /* Don't accept write commands if this is a read only slave. But * accept write commands if this is our master. */ if (server.masterhost && server.repl_slave_ro && !(c->flags & CLIENT_MASTER) && c->cmd->flags & CMD_WRITE) { addReply(c, shared.roslaveerr); return C_OK; } /* Only allow SUBSCRIBE and UNSUBSCRIBE in the context of Pub/Sub */ if (c->flags & CLIENT_PUBSUB && c->cmd->proc != pingCommand && c->cmd->proc != subscribeCommand && c->cmd->proc != unsubscribeCommand && c->cmd->proc != psubscribeCommand && c->cmd->proc != punsubscribeCommand) { addReplyError(c,"only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context"); return C_OK; } /* Only allow INFO and SLAVEOF when slave-serve-stale-data is no and * we are a slave with a broken link with master. */ if (server.masterhost && server.repl_state != REPL_STATE_CONNECTED && server.repl_serve_stale_data == 0 && !(c->cmd->flags & CMD_STALE)) { flagTransaction(c); addReply(c, shared.masterdownerr); return C_OK; } /* Loading DB? Return an error if the command has not the * CMD_LOADING flag. */ if (server.loading && !(c->cmd->flags & CMD_LOADING)) { addReply(c, shared.loadingerr); return C_OK; } /* Lua script too slow? Only allow a limited number of commands. */ if (server.lua_timedout && c->cmd->proc != authCommand && c->cmd->proc != replconfCommand && !(c->cmd->proc == shutdownCommand && c->argc == 2 && tolower(((char*)c->argv[1]->ptr)[0]) == 'n') && !(c->cmd->proc == scriptCommand && c->argc == 2 && tolower(((char*)c->argv[1]->ptr)[0]) == 'k')) { flagTransaction(c); addReply(c, shared.slowscripterr); return C_OK; } /* Exec the command */ if (c->flags & CLIENT_MULTI && c->cmd->proc != execCommand && c->cmd->proc != discardCommand && c->cmd->proc != multiCommand && c->cmd->proc != watchCommand) { queueMultiCommand(c); addReply(c,shared.queued); } else { call(c,CMD_CALL_FULL); c->woff = server.master_repl_offset; if (listLength(server.ready_keys)) handleClientsBlockedOnLists(); } return C_OK; } /*================================== Shutdown =============================== */ /* Close listening sockets. Also unlink the unix domain socket if * unlink_unix_socket is non-zero. */ void closeListeningSockets(int unlink_unix_socket) { int j; for (j = 0; j < server.ipfd_count; j++) close(server.ipfd[j]); if (server.sofd != -1) close(server.sofd); if (server.cluster_enabled) for (j = 0; j < server.cfd_count; j++) close(server.cfd[j]); if (unlink_unix_socket && server.unixsocket) { serverLog(LL_NOTICE,"Removing the unix socket file."); unlink(server.unixsocket); /* don't care if this fails */ } } int prepareForShutdown(int flags) { int save = flags & SHUTDOWN_SAVE; int nosave = flags & SHUTDOWN_NOSAVE; serverLog(LL_WARNING,"User requested shutdown..."); /* Kill all the Lua debugger forked sessions. */ ldbKillForkedSessions(); /* Kill the saving child if there is a background saving in progress. We want to avoid race conditions, for instance our saving child may overwrite the synchronous saving did by SHUTDOWN. */ if (server.rdb_child_pid != -1) { serverLog(LL_WARNING,"There is a child saving an .rdb. Killing it!"); kill(server.rdb_child_pid,SIGUSR1); rdbRemoveTempFile(server.rdb_child_pid); } if (server.aof_state != AOF_OFF) { /* Kill the AOF saving child as the AOF we already have may be longer * but contains the full dataset anyway. */ if (server.aof_child_pid != -1) { /* If we have AOF enabled but haven't written the AOF yet, don't * shutdown or else the dataset will be lost. */ if (server.aof_state == AOF_WAIT_REWRITE) { serverLog(LL_WARNING, "Writing initial AOF, can't exit."); return C_ERR; } serverLog(LL_WARNING, "There is a child rewriting the AOF. Killing it!"); kill(server.aof_child_pid,SIGUSR1); } /* Append only file: fsync() the AOF and exit */ serverLog(LL_NOTICE,"Calling fsync() on the AOF file."); aof_fsync(server.aof_fd); } /* Create a new RDB file before exiting. */ if ((server.saveparamslen > 0 && !nosave) || save) { serverLog(LL_NOTICE,"Saving the final RDB snapshot before exiting."); /* Snapshotting. Perform a SYNC SAVE and exit */ if (rdbSave(server.rdb_filename) != C_OK) { /* Ooops.. error saving! The best we can do is to continue * operating. Note that if there was a background saving process, * in the next cron() Redis will be notified that the background * saving aborted, handling special stuff like slaves pending for * synchronization... */ serverLog(LL_WARNING,"Error trying to save the DB, can't exit."); return C_ERR; } } /* Remove the pid file if possible and needed. */ if (server.daemonize || server.pidfile) { serverLog(LL_NOTICE,"Removing the pid file."); unlink(server.pidfile); } /* Best effort flush of slave output buffers, so that we hopefully * send them pending writes. */ flushSlavesOutputBuffers(); /* Close the listening sockets. Apparently this allows faster restarts. */ closeListeningSockets(1); serverLog(LL_WARNING,"%s is now ready to exit, bye bye...", server.sentinel_mode ? "Sentinel" : "Redis"); return C_OK; } /*================================== Commands =============================== */ /* Return zero if strings are the same, non-zero if they are not. * The comparison is performed in a way that prevents an attacker to obtain * information about the nature of the strings just monitoring the execution * time of the function. * * Note that limiting the comparison length to strings up to 512 bytes we * can avoid leaking any information about the password length and any * possible branch misprediction related leak. */ int time_independent_strcmp(char *a, char *b) { char bufa[CONFIG_AUTHPASS_MAX_LEN], bufb[CONFIG_AUTHPASS_MAX_LEN]; /* The above two strlen perform len(a) + len(b) operations where either * a or b are fixed (our password) length, and the difference is only * relative to the length of the user provided string, so no information * leak is possible in the following two lines of code. */ unsigned int alen = strlen(a); unsigned int blen = strlen(b); unsigned int j; int diff = 0; /* We can't compare strings longer than our static buffers. * Note that this will never pass the first test in practical circumstances * so there is no info leak. */ if (alen > sizeof(bufa) || blen > sizeof(bufb)) return 1; memset(bufa,0,sizeof(bufa)); /* Constant time. */ memset(bufb,0,sizeof(bufb)); /* Constant time. */ /* Again the time of the following two copies is proportional to * len(a) + len(b) so no info is leaked. */ memcpy(bufa,a,alen); memcpy(bufb,b,blen); /* Always compare all the chars in the two buffers without * conditional expressions. */ for (j = 0; j < sizeof(bufa); j++) { diff |= (bufa[j] ^ bufb[j]); } /* Length must be equal as well. */ diff |= alen ^ blen; return diff; /* If zero strings are the same. */ } void authCommand(client *c) { if (!server.requirepass) { addReplyError(c,"Client sent AUTH, but no password is set"); } else if (!time_independent_strcmp(c->argv[1]->ptr, server.requirepass)) { c->authenticated = 1; addReply(c,shared.ok); } else { c->authenticated = 0; addReplyError(c,"invalid password"); } } /* The PING command. It works in a different way if the client is in * in Pub/Sub mode. */ void pingCommand(client *c) { /* The command takes zero or one arguments. */ if (c->argc > 2) { addReplyErrorFormat(c,"wrong number of arguments for '%s' command", c->cmd->name); return; } if (c->flags & CLIENT_PUBSUB) { addReply(c,shared.mbulkhdr[2]); addReplyBulkCBuffer(c,"pong",4); if (c->argc == 1) addReplyBulkCBuffer(c,"",0); else addReplyBulk(c,c->argv[1]); } else { if (c->argc == 1) addReply(c,shared.pong); else addReplyBulk(c,c->argv[1]); } } void echoCommand(client *c) { addReplyBulk(c,c->argv[1]); } void timeCommand(client *c) { struct timeval tv; /* gettimeofday() can only fail if &tv is a bad address so we * don't check for errors. */ gettimeofday(&tv,NULL); addReplyMultiBulkLen(c,2); addReplyBulkLongLong(c,tv.tv_sec); addReplyBulkLongLong(c,tv.tv_usec); } /* Helper function for addReplyCommand() to output flags. */ int addReplyCommandFlag(client *c, struct redisCommand *cmd, int f, char *reply) { if (cmd->flags & f) { addReplyStatus(c, reply); return 1; } return 0; } /* Output the representation of a Redis command. Used by the COMMAND command. */ void addReplyCommand(client *c, struct redisCommand *cmd) { if (!cmd) { addReply(c, shared.nullbulk); } else { /* We are adding: command name, arg count, flags, first, last, offset */ addReplyMultiBulkLen(c, 6); addReplyBulkCString(c, cmd->name); addReplyLongLong(c, cmd->arity); int flagcount = 0; void *flaglen = addDeferredMultiBulkLength(c); flagcount += addReplyCommandFlag(c,cmd,CMD_WRITE, "write"); flagcount += addReplyCommandFlag(c,cmd,CMD_READONLY, "readonly"); flagcount += addReplyCommandFlag(c,cmd,CMD_DENYOOM, "denyoom"); flagcount += addReplyCommandFlag(c,cmd,CMD_ADMIN, "admin"); flagcount += addReplyCommandFlag(c,cmd,CMD_PUBSUB, "pubsub"); flagcount += addReplyCommandFlag(c,cmd,CMD_NOSCRIPT, "noscript"); flagcount += addReplyCommandFlag(c,cmd,CMD_RANDOM, "random"); flagcount += addReplyCommandFlag(c,cmd,CMD_SORT_FOR_SCRIPT,"sort_for_script"); flagcount += addReplyCommandFlag(c,cmd,CMD_LOADING, "loading"); flagcount += addReplyCommandFlag(c,cmd,CMD_STALE, "stale"); flagcount += addReplyCommandFlag(c,cmd,CMD_SKIP_MONITOR, "skip_monitor"); flagcount += addReplyCommandFlag(c,cmd,CMD_ASKING, "asking"); flagcount += addReplyCommandFlag(c,cmd,CMD_FAST, "fast"); if (cmd->getkeys_proc) { addReplyStatus(c, "movablekeys"); flagcount += 1; } setDeferredMultiBulkLength(c, flaglen, flagcount); addReplyLongLong(c, cmd->firstkey); addReplyLongLong(c, cmd->lastkey); addReplyLongLong(c, cmd->keystep); } } /* COMMAND <subcommand> <args> */ void commandCommand(client *c) { dictIterator *di; dictEntry *de; if (c->argc == 1) { addReplyMultiBulkLen(c, dictSize(server.commands)); di = dictGetIterator(server.commands); while ((de = dictNext(di)) != NULL) { addReplyCommand(c, dictGetVal(de)); } dictReleaseIterator(di); } else if (!strcasecmp(c->argv[1]->ptr, "info")) { int i; addReplyMultiBulkLen(c, c->argc-2); for (i = 2; i < c->argc; i++) { addReplyCommand(c, dictFetchValue(server.commands, c->argv[i]->ptr)); } } else if (!strcasecmp(c->argv[1]->ptr, "count") && c->argc == 2) { addReplyLongLong(c, dictSize(server.commands)); } else if (!strcasecmp(c->argv[1]->ptr,"getkeys") && c->argc >= 3) { struct redisCommand *cmd = lookupCommand(c->argv[2]->ptr); int *keys, numkeys, j; if (!cmd) { addReplyErrorFormat(c,"Invalid command specified"); return; } else if ((cmd->arity > 0 && cmd->arity != c->argc-2) || ((c->argc-2) < -cmd->arity)) { addReplyError(c,"Invalid number of arguments specified for command"); return; } keys = getKeysFromCommand(cmd,c->argv+2,c->argc-2,&numkeys); addReplyMultiBulkLen(c,numkeys); for (j = 0; j < numkeys; j++) addReplyBulk(c,c->argv[keys[j]+2]); getKeysFreeResult(keys); } else { addReplyError(c, "Unknown subcommand or wrong number of arguments."); return; } } /* Convert an amount of bytes into a human readable string in the form * of 100B, 2G, 100M, 4K, and so forth. */ void bytesToHuman(char *s, unsigned long long n) { double d; if (n < 1024) { /* Bytes */ sprintf(s,"%lluB",n); return; } else if (n < (1024*1024)) { d = (double)n/(1024); sprintf(s,"%.2fK",d); } else if (n < (1024LL*1024*1024)) { d = (double)n/(1024*1024); sprintf(s,"%.2fM",d); } else if (n < (1024LL*1024*1024*1024)) { d = (double)n/(1024LL*1024*1024); sprintf(s,"%.2fG",d); } else if (n < (1024LL*1024*1024*1024*1024)) { d = (double)n/(1024LL*1024*1024*1024); sprintf(s,"%.2fT",d); } else if (n < (1024LL*1024*1024*1024*1024*1024)) { d = (double)n/(1024LL*1024*1024*1024*1024); sprintf(s,"%.2fP",d); } else { /* Let's hope we never need this */ sprintf(s,"%lluB",n); } } /* Create the string returned by the INFO command. This is decoupled * by the INFO command itself as we need to report the same information * on memory corruption problems. */ sds genRedisInfoString(char *section) { sds info = sdsempty(); time_t uptime = server.unixtime-server.stat_starttime; int j, numcommands; struct rusage self_ru, c_ru; unsigned long lol, bib; int allsections = 0, defsections = 0; int sections = 0; if (section == NULL) section = "default"; allsections = strcasecmp(section,"all") == 0; defsections = strcasecmp(section,"default") == 0; getrusage(RUSAGE_SELF, &self_ru); getrusage(RUSAGE_CHILDREN, &c_ru); getClientsMaxBuffers(&lol,&bib); /* Server */ if (allsections || defsections || !strcasecmp(section,"server")) { static int call_uname = 1; static struct utsname name; char *mode; if (server.cluster_enabled) mode = "cluster"; else if (server.sentinel_mode) mode = "sentinel"; else mode = "standalone"; if (sections++) info = sdscat(info,"\r\n"); if (call_uname) { /* Uname can be slow and is always the same output. Cache it. */ uname(&name); call_uname = 0; } info = sdscatprintf(info, "# Server\r\n" "redis_version:%s\r\n" "redis_git_sha1:%s\r\n" "redis_git_dirty:%d\r\n" "redis_build_id:%llx\r\n" "redis_mode:%s\r\n" "os:%s %s %s\r\n" "arch_bits:%d\r\n" "multiplexing_api:%s\r\n" "gcc_version:%d.%d.%d\r\n" "process_id:%ld\r\n" "run_id:%s\r\n" "tcp_port:%d\r\n" "uptime_in_seconds:%jd\r\n" "uptime_in_days:%jd\r\n" "hz:%d\r\n" "lru_clock:%ld\r\n" "executable:%s\r\n" "config_file:%s\r\n", REDIS_VERSION, redisGitSHA1(), strtol(redisGitDirty(),NULL,10) > 0, (unsigned long long) redisBuildId(), mode, name.sysname, name.release, name.machine, server.arch_bits, aeGetApiName(), #ifdef __GNUC__ __GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__, #else 0,0,0, #endif (long) getpid(), server.runid, server.port, (intmax_t)uptime, (intmax_t)(uptime/(3600*24)), server.hz, (unsigned long) server.lruclock, server.executable ? server.executable : "", server.configfile ? server.configfile : ""); } /* Clients */ if (allsections || defsections || !strcasecmp(section,"clients")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Clients\r\n" "connected_clients:%lu\r\n" "client_longest_output_list:%lu\r\n" "client_biggest_input_buf:%lu\r\n" "blocked_clients:%d\r\n", listLength(server.clients)-listLength(server.slaves), lol, bib, server.bpop_blocked_clients); } /* Memory */ if (allsections || defsections || !strcasecmp(section,"memory")) { char hmem[64]; char peak_hmem[64]; char total_system_hmem[64]; char used_memory_lua_hmem[64]; char used_memory_rss_hmem[64]; char maxmemory_hmem[64]; size_t zmalloc_used = zmalloc_used_memory(); size_t total_system_mem = server.system_memory_size; const char *evict_policy = evictPolicyToString(); long long memory_lua = (long long)lua_gc(server.lua,LUA_GCCOUNT,0)*1024; /* Peak memory is updated from time to time by serverCron() so it * may happen that the instantaneous value is slightly bigger than * the peak value. This may confuse users, so we update the peak * if found smaller than the current memory usage. */ if (zmalloc_used > server.stat_peak_memory) server.stat_peak_memory = zmalloc_used; bytesToHuman(hmem,zmalloc_used); bytesToHuman(peak_hmem,server.stat_peak_memory); bytesToHuman(total_system_hmem,total_system_mem); bytesToHuman(used_memory_lua_hmem,memory_lua); bytesToHuman(used_memory_rss_hmem,server.resident_set_size); bytesToHuman(maxmemory_hmem,server.maxmemory); if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Memory\r\n" "used_memory:%zu\r\n" "used_memory_human:%s\r\n" "used_memory_rss:%zu\r\n" "used_memory_rss_human:%s\r\n" "used_memory_peak:%zu\r\n" "used_memory_peak_human:%s\r\n" "total_system_memory:%lu\r\n" "total_system_memory_human:%s\r\n" "used_memory_lua:%lld\r\n" "used_memory_lua_human:%s\r\n" "maxmemory:%lld\r\n" "maxmemory_human:%s\r\n" "maxmemory_policy:%s\r\n" "mem_fragmentation_ratio:%.2f\r\n" "mem_allocator:%s\r\n", zmalloc_used, hmem, server.resident_set_size, used_memory_rss_hmem, server.stat_peak_memory, peak_hmem, (unsigned long)total_system_mem, total_system_hmem, memory_lua, used_memory_lua_hmem, server.maxmemory, maxmemory_hmem, evict_policy, zmalloc_get_fragmentation_ratio(server.resident_set_size), ZMALLOC_LIB ); } /* Persistence */ if (allsections || defsections || !strcasecmp(section,"persistence")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Persistence\r\n" "loading:%d\r\n" "rdb_changes_since_last_save:%lld\r\n" "rdb_bgsave_in_progress:%d\r\n" "rdb_last_save_time:%jd\r\n" "rdb_last_bgsave_status:%s\r\n" "rdb_last_bgsave_time_sec:%jd\r\n" "rdb_current_bgsave_time_sec:%jd\r\n" "aof_enabled:%d\r\n" "aof_rewrite_in_progress:%d\r\n" "aof_rewrite_scheduled:%d\r\n" "aof_last_rewrite_time_sec:%jd\r\n" "aof_current_rewrite_time_sec:%jd\r\n" "aof_last_bgrewrite_status:%s\r\n" "aof_last_write_status:%s\r\n", server.loading, server.dirty, server.rdb_child_pid != -1, (intmax_t)server.lastsave, (server.lastbgsave_status == C_OK) ? "ok" : "err", (intmax_t)server.rdb_save_time_last, (intmax_t)((server.rdb_child_pid == -1) ? -1 : time(NULL)-server.rdb_save_time_start), server.aof_state != AOF_OFF, server.aof_child_pid != -1, server.aof_rewrite_scheduled, (intmax_t)server.aof_rewrite_time_last, (intmax_t)((server.aof_child_pid == -1) ? -1 : time(NULL)-server.aof_rewrite_time_start), (server.aof_lastbgrewrite_status == C_OK) ? "ok" : "err", (server.aof_last_write_status == C_OK) ? "ok" : "err"); if (server.aof_state != AOF_OFF) { info = sdscatprintf(info, "aof_current_size:%lld\r\n" "aof_base_size:%lld\r\n" "aof_pending_rewrite:%d\r\n" "aof_buffer_length:%zu\r\n" "aof_rewrite_buffer_length:%lu\r\n" "aof_pending_bio_fsync:%llu\r\n" "aof_delayed_fsync:%lu\r\n", (long long) server.aof_current_size, (long long) server.aof_rewrite_base_size, server.aof_rewrite_scheduled, sdslen(server.aof_buf), aofRewriteBufferSize(), bioPendingJobsOfType(BIO_AOF_FSYNC), server.aof_delayed_fsync); } if (server.loading) { double perc; time_t eta, elapsed; off_t remaining_bytes = server.loading_total_bytes- server.loading_loaded_bytes; perc = ((double)server.loading_loaded_bytes / (server.loading_total_bytes+1)) * 100; elapsed = time(NULL)-server.loading_start_time; if (elapsed == 0) { eta = 1; /* A fake 1 second figure if we don't have enough info */ } else { eta = (elapsed*remaining_bytes)/(server.loading_loaded_bytes+1); } info = sdscatprintf(info, "loading_start_time:%jd\r\n" "loading_total_bytes:%llu\r\n" "loading_loaded_bytes:%llu\r\n" "loading_loaded_perc:%.2f\r\n" "loading_eta_seconds:%jd\r\n", (intmax_t) server.loading_start_time, (unsigned long long) server.loading_total_bytes, (unsigned long long) server.loading_loaded_bytes, perc, (intmax_t)eta ); } } /* Stats */ if (allsections || defsections || !strcasecmp(section,"stats")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Stats\r\n" "total_connections_received:%lld\r\n" "total_commands_processed:%lld\r\n" "instantaneous_ops_per_sec:%lld\r\n" "total_net_input_bytes:%lld\r\n" "total_net_output_bytes:%lld\r\n" "instantaneous_input_kbps:%.2f\r\n" "instantaneous_output_kbps:%.2f\r\n" "rejected_connections:%lld\r\n" "sync_full:%lld\r\n" "sync_partial_ok:%lld\r\n" "sync_partial_err:%lld\r\n" "expired_keys:%lld\r\n" "evicted_keys:%lld\r\n" "keyspace_hits:%lld\r\n" "keyspace_misses:%lld\r\n" "pubsub_channels:%ld\r\n" "pubsub_patterns:%lu\r\n" "latest_fork_usec:%lld\r\n" "migrate_cached_sockets:%ld\r\n", server.stat_numconnections, server.stat_numcommands, getInstantaneousMetric(STATS_METRIC_COMMAND), server.stat_net_input_bytes, server.stat_net_output_bytes, (float)getInstantaneousMetric(STATS_METRIC_NET_INPUT)/1024, (float)getInstantaneousMetric(STATS_METRIC_NET_OUTPUT)/1024, server.stat_rejected_conn, server.stat_sync_full, server.stat_sync_partial_ok, server.stat_sync_partial_err, server.stat_expiredkeys, server.stat_evictedkeys, server.stat_keyspace_hits, server.stat_keyspace_misses, dictSize(server.pubsub_channels), listLength(server.pubsub_patterns), server.stat_fork_time, dictSize(server.migrate_cached_sockets)); } /* Replication */ if (allsections || defsections || !strcasecmp(section,"replication")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Replication\r\n" "role:%s\r\n", server.masterhost == NULL ? "master" : "slave"); if (server.masterhost) { long long slave_repl_offset = 1; if (server.master) slave_repl_offset = server.master->reploff; else if (server.cached_master) slave_repl_offset = server.cached_master->reploff; info = sdscatprintf(info, "master_host:%s\r\n" "master_port:%d\r\n" "master_link_status:%s\r\n" "master_last_io_seconds_ago:%d\r\n" "master_sync_in_progress:%d\r\n" "slave_repl_offset:%lld\r\n" ,server.masterhost, server.masterport, (server.repl_state == REPL_STATE_CONNECTED) ? "up" : "down", server.master ? ((int)(server.unixtime-server.master->lastinteraction)) : -1, server.repl_state == REPL_STATE_TRANSFER, slave_repl_offset ); if (server.repl_state == REPL_STATE_TRANSFER) { info = sdscatprintf(info, "master_sync_left_bytes:%lld\r\n" "master_sync_last_io_seconds_ago:%d\r\n" , (long long) (server.repl_transfer_size - server.repl_transfer_read), (int)(server.unixtime-server.repl_transfer_lastio) ); } if (server.repl_state != REPL_STATE_CONNECTED) { info = sdscatprintf(info, "master_link_down_since_seconds:%jd\r\n", (intmax_t)server.unixtime-server.repl_down_since); } info = sdscatprintf(info, "slave_priority:%d\r\n" "slave_read_only:%d\r\n", server.slave_priority, server.repl_slave_ro); } info = sdscatprintf(info, "connected_slaves:%lu\r\n", listLength(server.slaves)); /* If min-slaves-to-write is active, write the number of slaves * currently considered 'good'. */ if (server.repl_min_slaves_to_write && server.repl_min_slaves_max_lag) { info = sdscatprintf(info, "min_slaves_good_slaves:%d\r\n", server.repl_good_slaves_count); } if (listLength(server.slaves)) { int slaveid = 0; listNode *ln; listIter li; listRewind(server.slaves,&li); while((ln = listNext(&li))) { client *slave = listNodeValue(ln); char *state = NULL; char ip[NET_IP_STR_LEN], *slaveip = slave->slave_ip; int port; long lag = 0; if (slaveip[0] == '\0') { if (anetPeerToString(slave->fd,ip,sizeof(ip),&port) == -1) continue; slaveip = ip; } switch(slave->replstate) { case SLAVE_STATE_WAIT_BGSAVE_START: case SLAVE_STATE_WAIT_BGSAVE_END: state = "wait_bgsave"; break; case SLAVE_STATE_SEND_BULK: state = "send_bulk"; break; case SLAVE_STATE_ONLINE: state = "online"; break; } if (state == NULL) continue; if (slave->replstate == SLAVE_STATE_ONLINE) lag = time(NULL) - slave->repl_ack_time; info = sdscatprintf(info, "slave%d:ip=%s,port=%d,state=%s," "offset=%lld,lag=%ld\r\n", slaveid,slaveip,slave->slave_listening_port,state, slave->repl_ack_off, lag); slaveid++; } } info = sdscatprintf(info, "master_repl_offset:%lld\r\n" "repl_backlog_active:%d\r\n" "repl_backlog_size:%lld\r\n" "repl_backlog_first_byte_offset:%lld\r\n" "repl_backlog_histlen:%lld\r\n", server.master_repl_offset, server.repl_backlog != NULL, server.repl_backlog_size, server.repl_backlog_off, server.repl_backlog_histlen); } /* CPU */ if (allsections || defsections || !strcasecmp(section,"cpu")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# CPU\r\n" "used_cpu_sys:%.2f\r\n" "used_cpu_user:%.2f\r\n" "used_cpu_sys_children:%.2f\r\n" "used_cpu_user_children:%.2f\r\n", (float)self_ru.ru_stime.tv_sec+(float)self_ru.ru_stime.tv_usec/1000000, (float)self_ru.ru_utime.tv_sec+(float)self_ru.ru_utime.tv_usec/1000000, (float)c_ru.ru_stime.tv_sec+(float)c_ru.ru_stime.tv_usec/1000000, (float)c_ru.ru_utime.tv_sec+(float)c_ru.ru_utime.tv_usec/1000000); } /* cmdtime */ if (allsections || !strcasecmp(section,"commandstats")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Commandstats\r\n"); numcommands = sizeof(redisCommandTable)/sizeof(struct redisCommand); for (j = 0; j < numcommands; j++) { struct redisCommand *c = redisCommandTable+j; if (!c->calls) continue; info = sdscatprintf(info, "cmdstat_%s:calls=%lld,usec=%lld,usec_per_call=%.2f\r\n", c->name, c->calls, c->microseconds, (c->calls == 0) ? 0 : ((float)c->microseconds/c->calls)); } } /* Cluster */ if (allsections || defsections || !strcasecmp(section,"cluster")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Cluster\r\n" "cluster_enabled:%d\r\n", server.cluster_enabled); } /* Key space */ if (allsections || defsections || !strcasecmp(section,"keyspace")) { if (sections++) info = sdscat(info,"\r\n"); info = sdscatprintf(info, "# Keyspace\r\n"); for (j = 0; j < server.dbnum; j++) { long long keys, vkeys; keys = dictSize(server.db[j].dict); vkeys = dictSize(server.db[j].expires); if (keys || vkeys) { info = sdscatprintf(info, "db%d:keys=%lld,expires=%lld,avg_ttl=%lld\r\n", j, keys, vkeys, server.db[j].avg_ttl); } } } return info; } void infoCommand(client *c) { char *section = c->argc == 2 ? c->argv[1]->ptr : "default"; if (c->argc > 2) { addReply(c,shared.syntaxerr); return; } addReplyBulkSds(c, genRedisInfoString(section)); } void monitorCommand(client *c) { /* ignore MONITOR if already slave or in monitor mode */ if (c->flags & CLIENT_SLAVE) return; c->flags |= (CLIENT_SLAVE|CLIENT_MONITOR); listAddNodeTail(server.monitors,c); addReply(c,shared.ok); } /* ============================ Maxmemory directive ======================== */ /* freeMemoryIfNeeded() gets called when 'maxmemory' is set on the config * file to limit the max memory used by the server, before processing a * command. * * The goal of the function is to free enough memory to keep Redis under the * configured memory limit. * * The function starts calculating how many bytes should be freed to keep * Redis under the limit, and enters a loop selecting the best keys to * evict accordingly to the configured policy. * * If all the bytes needed to return back under the limit were freed the * function returns C_OK, otherwise C_ERR is returned, and the caller * should block the execution of commands that will result in more memory * used by the server. * * ------------------------------------------------------------------------ * * LRU approximation algorithm * * Redis uses an approximation of the LRU algorithm that runs in constant * memory. Every time there is a key to expire, we sample N keys (with * N very small, usually in around 5) to populate a pool of best keys to * evict of M keys (the pool size is defined by MAXMEMORY_EVICTION_POOL_SIZE). * * The N keys sampled are added in the pool of good keys to expire (the one * with an old access time) if they are better than one of the current keys * in the pool. * * After the pool is populated, the best key we have in the pool is expired. * However note that we don't remove keys from the pool when they are deleted * so the pool may contain keys that no longer exist. * * When we try to evict a key, and all the entries in the pool don't exist * we populate it again. This time we'll be sure that the pool has at least * one key that can be evicted, if there is at least one key that can be * evicted in the whole database. */ /* Create a new eviction pool. */ struct evictionPoolEntry *evictionPoolAlloc(void) { struct evictionPoolEntry *ep; int j; ep = zmalloc(sizeof(*ep)*MAXMEMORY_EVICTION_POOL_SIZE); for (j = 0; j < MAXMEMORY_EVICTION_POOL_SIZE; j++) { ep[j].idle = 0; ep[j].key = NULL; } return ep; } /* This is an helper function for freeMemoryIfNeeded(), it is used in order * to populate the evictionPool with a few entries every time we want to * expire a key. Keys with idle time smaller than one of the current * keys are added. Keys are always added if there are free entries. * * We insert keys on place in ascending order, so keys with the smaller * idle time are on the left, and keys with the higher idle time on the * right. */ #define EVICTION_SAMPLES_ARRAY_SIZE 16 void evictionPoolPopulate(dict *sampledict, dict *keydict, struct evictionPoolEntry *pool) { int j, k, count; dictEntry *_samples[EVICTION_SAMPLES_ARRAY_SIZE]; dictEntry **samples; /* Try to use a static buffer: this function is a big hit... * Note: it was actually measured that this helps. */ if (server.maxmemory_samples <= EVICTION_SAMPLES_ARRAY_SIZE) { samples = _samples; } else { samples = zmalloc(sizeof(samples[0])*server.maxmemory_samples); } count = dictGetSomeKeys(sampledict,samples,server.maxmemory_samples); for (j = 0; j < count; j++) { unsigned long long idle; sds key; robj *o; dictEntry *de; de = samples[j]; key = dictGetKey(de); /* If the dictionary we are sampling from is not the main * dictionary (but the expires one) we need to lookup the key * again in the key dictionary to obtain the value object. */ if (sampledict != keydict) de = dictFind(keydict, key); o = dictGetVal(de); idle = estimateObjectIdleTime(o); /* Insert the element inside the pool. * First, find the first empty bucket or the first populated * bucket that has an idle time smaller than our idle time. */ k = 0; while (k < MAXMEMORY_EVICTION_POOL_SIZE && pool[k].key && pool[k].idle < idle) k++; if (k == 0 && pool[MAXMEMORY_EVICTION_POOL_SIZE-1].key != NULL) { /* Can't insert if the element is < the worst element we have * and there are no empty buckets. */ continue; } else if (k < MAXMEMORY_EVICTION_POOL_SIZE && pool[k].key == NULL) { /* Inserting into empty position. No setup needed before insert. */ } else { /* Inserting in the middle. Now k points to the first element * greater than the element to insert. */ if (pool[MAXMEMORY_EVICTION_POOL_SIZE-1].key == NULL) { /* Free space on the right? Insert at k shifting * all the elements from k to end to the right. */ memmove(pool+k+1,pool+k, sizeof(pool[0])*(MAXMEMORY_EVICTION_POOL_SIZE-k-1)); } else { /* No free space on right? Insert at k-1 */ k--; /* Shift all elements on the left of k (included) to the * left, so we discard the element with smaller idle time. */ sdsfree(pool[0].key); memmove(pool,pool+1,sizeof(pool[0])*k); } } pool[k].key = sdsdup(key); pool[k].idle = idle; } if (samples != _samples) zfree(samples); } int freeMemoryIfNeeded(void) { size_t mem_used, mem_tofree, mem_freed; int slaves = listLength(server.slaves); mstime_t latency, eviction_latency; /* Remove the size of slaves output buffers and AOF buffer from the * count of used memory. */ mem_used = zmalloc_used_memory(); if (slaves) { listIter li; listNode *ln; listRewind(server.slaves,&li); while((ln = listNext(&li))) { client *slave = listNodeValue(ln); unsigned long obuf_bytes = getClientOutputBufferMemoryUsage(slave); if (obuf_bytes > mem_used) mem_used = 0; else mem_used -= obuf_bytes; } } if (server.aof_state != AOF_OFF) { mem_used -= sdslen(server.aof_buf); mem_used -= aofRewriteBufferSize(); } /* Check if we are over the memory limit. */ if (mem_used <= server.maxmemory) return C_OK; if (server.maxmemory_policy == MAXMEMORY_NO_EVICTION) return C_ERR; /* We need to free memory, but policy forbids. */ /* Compute how much memory we need to free. */ mem_tofree = mem_used - server.maxmemory; mem_freed = 0; latencyStartMonitor(latency); while (mem_freed < mem_tofree) { int j, k, keys_freed = 0; for (j = 0; j < server.dbnum; j++) { long bestval = 0; /* just to prevent warning */ sds bestkey = NULL; dictEntry *de; redisDb *db = server.db+j; dict *dict; if (server.maxmemory_policy == MAXMEMORY_ALLKEYS_LRU || server.maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM) { dict = server.db[j].dict; } else { dict = server.db[j].expires; } if (dictSize(dict) == 0) continue; /* volatile-random and allkeys-random policy */ if (server.maxmemory_policy == MAXMEMORY_ALLKEYS_RANDOM || server.maxmemory_policy == MAXMEMORY_VOLATILE_RANDOM) { de = dictGetRandomKey(dict); bestkey = dictGetKey(de); } /* volatile-lru and allkeys-lru policy */ else if (server.maxmemory_policy == MAXMEMORY_ALLKEYS_LRU || server.maxmemory_policy == MAXMEMORY_VOLATILE_LRU) { struct evictionPoolEntry *pool = db->eviction_pool; while(bestkey == NULL) { evictionPoolPopulate(dict, db->dict, db->eviction_pool); /* Go backward from best to worst element to evict. */ for (k = MAXMEMORY_EVICTION_POOL_SIZE-1; k >= 0; k--) { if (pool[k].key == NULL) continue; de = dictFind(dict,pool[k].key); /* Remove the entry from the pool. */ sdsfree(pool[k].key); /* Shift all elements on its right to left. */ memmove(pool+k,pool+k+1, sizeof(pool[0])*(MAXMEMORY_EVICTION_POOL_SIZE-k-1)); /* Clear the element on the right which is empty * since we shifted one position to the left. */ pool[MAXMEMORY_EVICTION_POOL_SIZE-1].key = NULL; pool[MAXMEMORY_EVICTION_POOL_SIZE-1].idle = 0; /* If the key exists, is our pick. Otherwise it is * a ghost and we need to try the next element. */ if (de) { bestkey = dictGetKey(de); break; } else { /* Ghost... */ continue; } } } } /* volatile-ttl */ else if (server.maxmemory_policy == MAXMEMORY_VOLATILE_TTL) { for (k = 0; k < server.maxmemory_samples; k++) { sds thiskey; long thisval; de = dictGetRandomKey(dict); thiskey = dictGetKey(de); thisval = (long) dictGetVal(de); /* Expire sooner (minor expire unix timestamp) is better * candidate for deletion */ if (bestkey == NULL || thisval < bestval) { bestkey = thiskey; bestval = thisval; } } } /* Finally remove the selected key. */ if (bestkey) { long long delta; robj *keyobj = createStringObject(bestkey,sdslen(bestkey)); propagateExpire(db,keyobj); /* We compute the amount of memory freed by dbDelete() alone. * It is possible that actually the memory needed to propagate * the DEL in AOF and replication link is greater than the one * we are freeing removing the key, but we can't account for * that otherwise we would never exit the loop. * * AOF and Output buffer memory will be freed eventually so * we only care about memory used by the key space. */ delta = (long long) zmalloc_used_memory(); latencyStartMonitor(eviction_latency); dbDelete(db,keyobj); latencyEndMonitor(eviction_latency); latencyAddSampleIfNeeded("eviction-del",eviction_latency); latencyRemoveNestedEvent(latency,eviction_latency); delta -= (long long) zmalloc_used_memory(); mem_freed += delta; server.stat_evictedkeys++; notifyKeyspaceEvent(NOTIFY_EVICTED, "evicted", keyobj, db->id); decrRefCount(keyobj); keys_freed++; /* When the memory to free starts to be big enough, we may * start spending so much time here that is impossible to * deliver data to the slaves fast enough, so we force the * transmission here inside the loop. */ if (slaves) flushSlavesOutputBuffers(); } } if (!keys_freed) { latencyEndMonitor(latency); latencyAddSampleIfNeeded("eviction-cycle",latency); return C_ERR; /* nothing to free... */ } } latencyEndMonitor(latency); latencyAddSampleIfNeeded("eviction-cycle",latency); return C_OK; } /* =================================== Main! ================================ */ #ifdef __linux__ int linuxOvercommitMemoryValue(void) { FILE *fp = fopen("/proc/sys/vm/overcommit_memory","r"); char buf[64]; if (!fp) return -1; if (fgets(buf,64,fp) == NULL) { fclose(fp); return -1; } fclose(fp); return atoi(buf); } void linuxMemoryWarnings(void) { if (linuxOvercommitMemoryValue() == 0) { serverLog(LL_WARNING,"WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect."); } if (THPIsEnabled()) { serverLog(LL_WARNING,"WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled."); } } #endif /* __linux__ */ void createPidFile(void) { /* If pidfile requested, but no pidfile defined, use * default pidfile path */ if (!server.pidfile) server.pidfile = zstrdup(CONFIG_DEFAULT_PID_FILE); /* Try to write the pid file in a best-effort way. */ FILE *fp = fopen(server.pidfile,"w"); if (fp) { fprintf(fp,"%d\n",(int)getpid()); fclose(fp); } } void daemonize(void) { int fd; if (fork() != 0) exit(0); /* parent exits */ setsid(); /* create a new session */ /* Every output goes to /dev/null. If Redis is daemonized but * the 'logfile' is set to 'stdout' in the configuration file * it will not log at all. */ if ((fd = open("/dev/null", O_RDWR, 0)) != -1) { dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); if (fd > STDERR_FILENO) close(fd); } } void version(void) { printf("Redis server v=%s sha=%s:%d malloc=%s bits=%d build=%llx\n", REDIS_VERSION, redisGitSHA1(), atoi(redisGitDirty()) > 0, ZMALLOC_LIB, sizeof(long) == 4 ? 32 : 64, (unsigned long long) redisBuildId()); exit(0); } void usage(void) { fprintf(stderr,"Usage: ./redis-server [/path/to/redis.conf] [options]\n"); fprintf(stderr," ./redis-server - (read config from stdin)\n"); fprintf(stderr," ./redis-server -v or --version\n"); fprintf(stderr," ./redis-server -h or --help\n"); fprintf(stderr," ./redis-server --test-memory <megabytes>\n\n"); fprintf(stderr,"Examples:\n"); fprintf(stderr," ./redis-server (run the server with default conf)\n"); fprintf(stderr," ./redis-server /etc/redis/6379.conf\n"); fprintf(stderr," ./redis-server --port 7777\n"); fprintf(stderr," ./redis-server --port 7777 --slaveof 127.0.0.1 8888\n"); fprintf(stderr," ./redis-server /etc/myredis.conf --loglevel verbose\n\n"); fprintf(stderr,"Sentinel mode:\n"); fprintf(stderr," ./redis-server /etc/sentinel.conf --sentinel\n"); exit(1); } void redisAsciiArt(void) { #include "asciilogo.h" char *buf = zmalloc(1024*16); char *mode; if (server.cluster_enabled) mode = "cluster"; else if (server.sentinel_mode) mode = "sentinel"; else mode = "standalone"; if (server.syslog_enabled) { serverLog(LL_NOTICE, "Redis %s (%s/%d) %s bit, %s mode, port %d, pid %ld ready to start.", REDIS_VERSION, redisGitSHA1(), strtol(redisGitDirty(),NULL,10) > 0, (sizeof(long) == 8) ? "64" : "32", mode, server.port, (long) getpid() ); } else { snprintf(buf,1024*16,ascii_logo, REDIS_VERSION, redisGitSHA1(), strtol(redisGitDirty(),NULL,10) > 0, (sizeof(long) == 8) ? "64" : "32", mode, server.port, (long) getpid() ); serverLogRaw(LL_NOTICE|LL_RAW,buf); } zfree(buf); } static void sigShutdownHandler(int sig) { char *msg; switch (sig) { case SIGINT: msg = "Received SIGINT scheduling shutdown..."; break; case SIGTERM: msg = "Received SIGTERM scheduling shutdown..."; break; default: msg = "Received shutdown signal, scheduling shutdown..."; }; /* SIGINT is often delivered via Ctrl+C in an interactive session. * If we receive the signal the second time, we interpret this as * the user really wanting to quit ASAP without waiting to persist * on disk. */ if (server.shutdown_asap && sig == SIGINT) { serverLogFromHandler(LL_WARNING, "You insist... exiting now."); rdbRemoveTempFile(getpid()); exit(1); /* Exit with an error since this was not a clean shutdown. */ } else if (server.loading) { exit(0); } serverLogFromHandler(LL_WARNING, msg); server.shutdown_asap = 1; } void setupSignalHandlers(void) { struct sigaction act; /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used. * Otherwise, sa_handler is used. */ sigemptyset(&act.sa_mask); act.sa_flags = 0; act.sa_handler = sigShutdownHandler; sigaction(SIGTERM, &act, NULL); sigaction(SIGINT, &act, NULL); #ifdef HAVE_BACKTRACE sigemptyset(&act.sa_mask); act.sa_flags = SA_NODEFER | SA_RESETHAND | SA_SIGINFO; act.sa_sigaction = sigsegvHandler; sigaction(SIGSEGV, &act, NULL); sigaction(SIGBUS, &act, NULL); sigaction(SIGFPE, &act, NULL); sigaction(SIGILL, &act, NULL); #endif return; } void memtest(size_t megabytes, int passes); /* Returns 1 if there is --sentinel among the arguments or if * argv[0] is exactly "redis-sentinel". */ int checkForSentinelMode(int argc, char **argv) { int j; if (strstr(argv[0],"redis-sentinel") != NULL) return 1; for (j = 1; j < argc; j++) if (!strcmp(argv[j],"--sentinel")) return 1; return 0; } /* Function called at startup to load RDB or AOF file in memory. */ void loadDataFromDisk(void) { long long start = ustime(); if (server.aof_state == AOF_ON) { if (loadAppendOnlyFile(server.aof_filename) == C_OK) serverLog(LL_NOTICE,"DB loaded from append only file: %.3f seconds",(float)(ustime()-start)/1000000); } else { if (rdbLoad(server.rdb_filename) == C_OK) { serverLog(LL_NOTICE,"DB loaded from disk: %.3f seconds", (float)(ustime()-start)/1000000); } else if (errno != ENOENT) { serverLog(LL_WARNING,"Fatal error loading the DB: %s. Exiting.",strerror(errno)); exit(1); } } } void redisOutOfMemoryHandler(size_t allocation_size) { serverLog(LL_WARNING,"Out Of Memory allocating %zu bytes!", allocation_size); serverPanic("Redis aborting for OUT OF MEMORY"); } void redisSetProcTitle(char *title) { #ifdef USE_SETPROCTITLE char *server_mode = ""; if (server.cluster_enabled) server_mode = " [cluster]"; else if (server.sentinel_mode) server_mode = " [sentinel]"; setproctitle("%s %s:%d%s", title, server.bindaddr_count ? server.bindaddr[0] : "*", server.port, server_mode); #else UNUSED(title); #endif } /* * Check whether systemd or upstart have been used to start redis. */ int redisSupervisedUpstart(void) { const char *upstart_job = getenv("UPSTART_JOB"); if (!upstart_job) { serverLog(LL_WARNING, "upstart supervision requested, but UPSTART_JOB not found"); return 0; } serverLog(LL_NOTICE, "supervised by upstart, will stop to signal readiness"); raise(SIGSTOP); unsetenv("UPSTART_JOB"); return 1; } int redisSupervisedSystemd(void) { const char *notify_socket = getenv("NOTIFY_SOCKET"); int fd = 1; struct sockaddr_un su; struct iovec iov; struct msghdr hdr; int sendto_flags = 0; if (!notify_socket) { serverLog(LL_WARNING, "systemd supervision requested, but NOTIFY_SOCKET not found"); return 0; } if ((strchr("@/", notify_socket[0])) == NULL || strlen(notify_socket) < 2) { return 0; } serverLog(LL_NOTICE, "supervised by systemd, will signal readiness"); if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) { serverLog(LL_WARNING, "Can't connect to systemd socket %s", notify_socket); return 0; } memset(&su, 0, sizeof(su)); su.sun_family = AF_UNIX; strncpy (su.sun_path, notify_socket, sizeof(su.sun_path) -1); su.sun_path[sizeof(su.sun_path) - 1] = '\0'; if (notify_socket[0] == '@') su.sun_path[0] = '\0'; memset(&iov, 0, sizeof(iov)); iov.iov_base = "READY=1"; iov.iov_len = strlen("READY=1"); memset(&hdr, 0, sizeof(hdr)); hdr.msg_name = &su; hdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) + strlen(notify_socket); hdr.msg_iov = &iov; hdr.msg_iovlen = 1; unsetenv("NOTIFY_SOCKET"); #ifdef HAVE_MSG_NOSIGNAL sendto_flags |= MSG_NOSIGNAL; #endif if (sendmsg(fd, &hdr, sendto_flags) < 0) { serverLog(LL_WARNING, "Can't send notification to systemd"); close(fd); return 0; } close(fd); return 1; } int redisIsSupervised(int mode) { if (mode == SUPERVISED_AUTODETECT) { const char *upstart_job = getenv("UPSTART_JOB"); const char *notify_socket = getenv("NOTIFY_SOCKET"); if (upstart_job) { redisSupervisedUpstart(); } else if (notify_socket) { redisSupervisedSystemd(); } } else if (mode == SUPERVISED_UPSTART) { return redisSupervisedUpstart(); } else if (mode == SUPERVISED_SYSTEMD) { return redisSupervisedSystemd(); } return 0; } int main(int argc, char **argv) { struct timeval tv; int j; #ifdef REDIS_TEST if (argc == 3 && !strcasecmp(argv[1], "test")) { if (!strcasecmp(argv[2], "ziplist")) { return ziplistTest(argc, argv); } else if (!strcasecmp(argv[2], "quicklist")) { quicklistTest(argc, argv); } else if (!strcasecmp(argv[2], "intset")) { return intsetTest(argc, argv); } else if (!strcasecmp(argv[2], "zipmap")) { return zipmapTest(argc, argv); } else if (!strcasecmp(argv[2], "sha1test")) { return sha1Test(argc, argv); } else if (!strcasecmp(argv[2], "util")) { return utilTest(argc, argv); } else if (!strcasecmp(argv[2], "sds")) { return sdsTest(argc, argv); } else if (!strcasecmp(argv[2], "endianconv")) { return endianconvTest(argc, argv); } else if (!strcasecmp(argv[2], "crc64")) { return crc64Test(argc, argv); } return -1; /* test not found */ } #endif /* We need to initialize our libraries, and the server configuration. */ #ifdef INIT_SETPROCTITLE_REPLACEMENT spt_init(argc, argv); #endif setlocale(LC_COLLATE,""); zmalloc_enable_thread_safeness(); zmalloc_set_oom_handler(redisOutOfMemoryHandler); srand(time(NULL)^getpid()); gettimeofday(&tv,NULL); dictSetHashFunctionSeed(tv.tv_sec^tv.tv_usec^getpid()); server.sentinel_mode = checkForSentinelMode(argc,argv); initServerConfig(); /* Store the executable path and arguments in a safe place in order * to be able to restart the server later. */ server.executable = getAbsolutePath(argv[0]); server.exec_argv = zmalloc(sizeof(char*)*(argc+1)); server.exec_argv[argc] = NULL; for (j = 0; j < argc; j++) server.exec_argv[j] = zstrdup(argv[j]); /* We need to init sentinel right now as parsing the configuration file * in sentinel mode will have the effect of populating the sentinel * data structures with master nodes to monitor. */ if (server.sentinel_mode) { initSentinelConfig(); initSentinel(); } /* Check if we need to start in redis-check-rdb mode. We just execute * the program main. However the program is part of the Redis executable * so that we can easily execute an RDB check on loading errors. */ if (strstr(argv[0],"redis-check-rdb") != NULL) redis_check_rdb_main(argc,argv); if (argc >= 2) { j = 1; /* First option to parse in argv[] */ sds options = sdsempty(); char *configfile = NULL; /* Handle special options --help and --version */ if (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0) version(); if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) usage(); if (strcmp(argv[1], "--test-memory") == 0) { if (argc == 3) { memtest(atoi(argv[2]),50); exit(0); } else { fprintf(stderr,"Please specify the amount of memory to test in megabytes.\n"); fprintf(stderr,"Example: ./redis-server --test-memory 4096\n\n"); exit(1); } } /* First argument is the config file name? */ if (argv[j][0] != '-' || argv[j][1] != '-') { configfile = argv[j]; server.configfile = getAbsolutePath(configfile); /* Replace the config file in server.exec_argv with * its absoulte path. */ zfree(server.exec_argv[j]); server.exec_argv[j] = zstrdup(server.configfile); j++; } /* All the other options are parsed and conceptually appended to the * configuration file. For instance --port 6380 will generate the * string "port 6380\n" to be parsed after the actual file name * is parsed, if any. */ while(j != argc) { if (argv[j][0] == '-' && argv[j][1] == '-') { /* Option name */ if (!strcmp(argv[j], "--check-rdb")) { /* Argument has no options, need to skip for parsing. */ j++; continue; } if (sdslen(options)) options = sdscat(options,"\n"); options = sdscat(options,argv[j]+2); options = sdscat(options," "); } else { /* Option argument */ options = sdscatrepr(options,argv[j],strlen(argv[j])); options = sdscat(options," "); } j++; } if (server.sentinel_mode && configfile && *configfile == '-') { serverLog(LL_WARNING, "Sentinel config from STDIN not allowed."); serverLog(LL_WARNING, "Sentinel needs config file on disk to save state. Exiting..."); exit(1); } resetServerSaveParams(); loadServerConfig(configfile,options); sdsfree(options); } else { serverLog(LL_WARNING, "Warning: no config file specified, using the default config. In order to specify a config file use %s /path/to/%s.conf", argv[0], server.sentinel_mode ? "sentinel" : "redis"); } server.supervised = redisIsSupervised(server.supervised_mode); int background = server.daemonize && !server.supervised; if (background) daemonize(); initServer(); if (background || server.pidfile) createPidFile(); redisSetProcTitle(argv[0]); redisAsciiArt(); checkTcpBacklogSettings(); if (!server.sentinel_mode) { /* Things not needed when running in Sentinel mode. */ serverLog(LL_WARNING,"Server started, Redis version " REDIS_VERSION); #ifdef __linux__ linuxMemoryWarnings(); #endif loadDataFromDisk(); if (server.cluster_enabled) { if (verifyClusterConfigWithData() == C_ERR) { serverLog(LL_WARNING, "You can't have keys in a DB different than DB 0 when in " "Cluster mode. Exiting."); exit(1); } } if (server.ipfd_count > 0) serverLog(LL_NOTICE,"The server is now ready to accept connections on port %d", server.port); if (server.sofd > 0) serverLog(LL_NOTICE,"The server is now ready to accept connections at %s", server.unixsocket); } else { sentinelIsRunning(); } /* Warning the user about suspicious maxmemory setting. */ if (server.maxmemory > 0 && server.maxmemory < 1024*1024) { serverLog(LL_WARNING,"WARNING: You specified a maxmemory value that is less than 1MB (current value is %llu bytes). Are you sure this is what you really want?", server.maxmemory); } aeSetBeforeSleepProc(server.el,beforeSleep); aeMain(server.el); aeDeleteEventLoop(server.el); return 0; } /* The End */
./CrossVul/dataset_final_sorted/CWE-254/c/bad_4872_1
crossvul-cpp_data_good_1548_0
/* * fs/dcache.c * * Complete reimplementation * (C) 1997 Thomas Schoebel-Theuer, * with heavy changes by Linus Torvalds */ /* * Notes on the allocation strategy: * * The dcache is a master of the icache - whenever a dcache entry * exists, the inode will always exist. "iput()" is done either when * the dcache entry is deleted or garbage collected. */ #include <linux/syscalls.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/fs.h> #include <linux/fsnotify.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/hash.h> #include <linux/cache.h> #include <linux/export.h> #include <linux/mount.h> #include <linux/file.h> #include <asm/uaccess.h> #include <linux/security.h> #include <linux/seqlock.h> #include <linux/swap.h> #include <linux/bootmem.h> #include <linux/fs_struct.h> #include <linux/hardirq.h> #include <linux/bit_spinlock.h> #include <linux/rculist_bl.h> #include <linux/prefetch.h> #include <linux/ratelimit.h> #include <linux/list_lru.h> #include <linux/kasan.h> #include "internal.h" #include "mount.h" /* * Usage: * dcache->d_inode->i_lock protects: * - i_dentry, d_u.d_alias, d_inode of aliases * dcache_hash_bucket lock protects: * - the dcache hash table * s_anon bl list spinlock protects: * - the s_anon list (see __d_drop) * dentry->d_sb->s_dentry_lru_lock protects: * - the dcache lru lists and counters * d_lock protects: * - d_flags * - d_name * - d_lru * - d_count * - d_unhashed() * - d_parent and d_subdirs * - childrens' d_child and d_parent * - d_u.d_alias, d_inode * * Ordering: * dentry->d_inode->i_lock * dentry->d_lock * dentry->d_sb->s_dentry_lru_lock * dcache_hash_bucket lock * s_anon lock * * If there is an ancestor relationship: * dentry->d_parent->...->d_parent->d_lock * ... * dentry->d_parent->d_lock * dentry->d_lock * * If no ancestor relationship: * if (dentry1 < dentry2) * dentry1->d_lock * dentry2->d_lock */ int sysctl_vfs_cache_pressure __read_mostly = 100; EXPORT_SYMBOL_GPL(sysctl_vfs_cache_pressure); __cacheline_aligned_in_smp DEFINE_SEQLOCK(rename_lock); EXPORT_SYMBOL(rename_lock); static struct kmem_cache *dentry_cache __read_mostly; /* * This is the single most critical data structure when it comes * to the dcache: the hashtable for lookups. Somebody should try * to make this good - I've just made it work. * * This hash-function tries to avoid losing too many bits of hash * information, yet avoid using a prime hash-size or similar. */ static unsigned int d_hash_mask __read_mostly; static unsigned int d_hash_shift __read_mostly; static struct hlist_bl_head *dentry_hashtable __read_mostly; static inline struct hlist_bl_head *d_hash(const struct dentry *parent, unsigned int hash) { hash += (unsigned long) parent / L1_CACHE_BYTES; return dentry_hashtable + hash_32(hash, d_hash_shift); } /* Statistics gathering. */ struct dentry_stat_t dentry_stat = { .age_limit = 45, }; static DEFINE_PER_CPU(long, nr_dentry); static DEFINE_PER_CPU(long, nr_dentry_unused); #if defined(CONFIG_SYSCTL) && defined(CONFIG_PROC_FS) /* * Here we resort to our own counters instead of using generic per-cpu counters * for consistency with what the vfs inode code does. We are expected to harvest * better code and performance by having our own specialized counters. * * Please note that the loop is done over all possible CPUs, not over all online * CPUs. The reason for this is that we don't want to play games with CPUs going * on and off. If one of them goes off, we will just keep their counters. * * glommer: See cffbc8a for details, and if you ever intend to change this, * please update all vfs counters to match. */ static long get_nr_dentry(void) { int i; long sum = 0; for_each_possible_cpu(i) sum += per_cpu(nr_dentry, i); return sum < 0 ? 0 : sum; } static long get_nr_dentry_unused(void) { int i; long sum = 0; for_each_possible_cpu(i) sum += per_cpu(nr_dentry_unused, i); return sum < 0 ? 0 : sum; } int proc_nr_dentry(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { dentry_stat.nr_dentry = get_nr_dentry(); dentry_stat.nr_unused = get_nr_dentry_unused(); return proc_doulongvec_minmax(table, write, buffer, lenp, ppos); } #endif /* * Compare 2 name strings, return 0 if they match, otherwise non-zero. * The strings are both count bytes long, and count is non-zero. */ #ifdef CONFIG_DCACHE_WORD_ACCESS #include <asm/word-at-a-time.h> /* * NOTE! 'cs' and 'scount' come from a dentry, so it has a * aligned allocation for this particular component. We don't * strictly need the load_unaligned_zeropad() safety, but it * doesn't hurt either. * * In contrast, 'ct' and 'tcount' can be from a pathname, and do * need the careful unaligned handling. */ static inline int dentry_string_cmp(const unsigned char *cs, const unsigned char *ct, unsigned tcount) { unsigned long a,b,mask; for (;;) { a = *(unsigned long *)cs; b = load_unaligned_zeropad(ct); if (tcount < sizeof(unsigned long)) break; if (unlikely(a != b)) return 1; cs += sizeof(unsigned long); ct += sizeof(unsigned long); tcount -= sizeof(unsigned long); if (!tcount) return 0; } mask = bytemask_from_count(tcount); return unlikely(!!((a ^ b) & mask)); } #else static inline int dentry_string_cmp(const unsigned char *cs, const unsigned char *ct, unsigned tcount) { do { if (*cs != *ct) return 1; cs++; ct++; tcount--; } while (tcount); return 0; } #endif static inline int dentry_cmp(const struct dentry *dentry, const unsigned char *ct, unsigned tcount) { const unsigned char *cs; /* * Be careful about RCU walk racing with rename: * use ACCESS_ONCE to fetch the name pointer. * * NOTE! Even if a rename will mean that the length * was not loaded atomically, we don't care. The * RCU walk will check the sequence count eventually, * and catch it. And we won't overrun the buffer, * because we're reading the name pointer atomically, * and a dentry name is guaranteed to be properly * terminated with a NUL byte. * * End result: even if 'len' is wrong, we'll exit * early because the data cannot match (there can * be no NUL in the ct/tcount data) */ cs = ACCESS_ONCE(dentry->d_name.name); smp_read_barrier_depends(); return dentry_string_cmp(cs, ct, tcount); } struct external_name { union { atomic_t count; struct rcu_head head; } u; unsigned char name[]; }; static inline struct external_name *external_name(struct dentry *dentry) { return container_of(dentry->d_name.name, struct external_name, name[0]); } static void __d_free(struct rcu_head *head) { struct dentry *dentry = container_of(head, struct dentry, d_u.d_rcu); kmem_cache_free(dentry_cache, dentry); } static void __d_free_external(struct rcu_head *head) { struct dentry *dentry = container_of(head, struct dentry, d_u.d_rcu); kfree(external_name(dentry)); kmem_cache_free(dentry_cache, dentry); } static inline int dname_external(const struct dentry *dentry) { return dentry->d_name.name != dentry->d_iname; } /* * Make sure other CPUs see the inode attached before the type is set. */ static inline void __d_set_inode_and_type(struct dentry *dentry, struct inode *inode, unsigned type_flags) { unsigned flags; dentry->d_inode = inode; smp_wmb(); flags = READ_ONCE(dentry->d_flags); flags &= ~(DCACHE_ENTRY_TYPE | DCACHE_FALLTHRU); flags |= type_flags; WRITE_ONCE(dentry->d_flags, flags); } /* * Ideally, we want to make sure that other CPUs see the flags cleared before * the inode is detached, but this is really a violation of RCU principles * since the ordering suggests we should always set inode before flags. * * We should instead replace or discard the entire dentry - but that sucks * performancewise on mass deletion/rename. */ static inline void __d_clear_type_and_inode(struct dentry *dentry) { unsigned flags = READ_ONCE(dentry->d_flags); flags &= ~(DCACHE_ENTRY_TYPE | DCACHE_FALLTHRU); WRITE_ONCE(dentry->d_flags, flags); smp_wmb(); dentry->d_inode = NULL; } static void dentry_free(struct dentry *dentry) { WARN_ON(!hlist_unhashed(&dentry->d_u.d_alias)); if (unlikely(dname_external(dentry))) { struct external_name *p = external_name(dentry); if (likely(atomic_dec_and_test(&p->u.count))) { call_rcu(&dentry->d_u.d_rcu, __d_free_external); return; } } /* if dentry was never visible to RCU, immediate free is OK */ if (!(dentry->d_flags & DCACHE_RCUACCESS)) __d_free(&dentry->d_u.d_rcu); else call_rcu(&dentry->d_u.d_rcu, __d_free); } /** * dentry_rcuwalk_invalidate - invalidate in-progress rcu-walk lookups * @dentry: the target dentry * After this call, in-progress rcu-walk path lookup will fail. This * should be called after unhashing, and after changing d_inode (if * the dentry has not already been unhashed). */ static inline void dentry_rcuwalk_invalidate(struct dentry *dentry) { lockdep_assert_held(&dentry->d_lock); /* Go through am invalidation barrier */ write_seqcount_invalidate(&dentry->d_seq); } /* * Release the dentry's inode, using the filesystem * d_iput() operation if defined. Dentry has no refcount * and is unhashed. */ static void dentry_iput(struct dentry * dentry) __releases(dentry->d_lock) __releases(dentry->d_inode->i_lock) { struct inode *inode = dentry->d_inode; if (inode) { __d_clear_type_and_inode(dentry); hlist_del_init(&dentry->d_u.d_alias); spin_unlock(&dentry->d_lock); spin_unlock(&inode->i_lock); if (!inode->i_nlink) fsnotify_inoderemove(inode); if (dentry->d_op && dentry->d_op->d_iput) dentry->d_op->d_iput(dentry, inode); else iput(inode); } else { spin_unlock(&dentry->d_lock); } } /* * Release the dentry's inode, using the filesystem * d_iput() operation if defined. dentry remains in-use. */ static void dentry_unlink_inode(struct dentry * dentry) __releases(dentry->d_lock) __releases(dentry->d_inode->i_lock) { struct inode *inode = dentry->d_inode; __d_clear_type_and_inode(dentry); hlist_del_init(&dentry->d_u.d_alias); dentry_rcuwalk_invalidate(dentry); spin_unlock(&dentry->d_lock); spin_unlock(&inode->i_lock); if (!inode->i_nlink) fsnotify_inoderemove(inode); if (dentry->d_op && dentry->d_op->d_iput) dentry->d_op->d_iput(dentry, inode); else iput(inode); } /* * The DCACHE_LRU_LIST bit is set whenever the 'd_lru' entry * is in use - which includes both the "real" per-superblock * LRU list _and_ the DCACHE_SHRINK_LIST use. * * The DCACHE_SHRINK_LIST bit is set whenever the dentry is * on the shrink list (ie not on the superblock LRU list). * * The per-cpu "nr_dentry_unused" counters are updated with * the DCACHE_LRU_LIST bit. * * These helper functions make sure we always follow the * rules. d_lock must be held by the caller. */ #define D_FLAG_VERIFY(dentry,x) WARN_ON_ONCE(((dentry)->d_flags & (DCACHE_LRU_LIST | DCACHE_SHRINK_LIST)) != (x)) static void d_lru_add(struct dentry *dentry) { D_FLAG_VERIFY(dentry, 0); dentry->d_flags |= DCACHE_LRU_LIST; this_cpu_inc(nr_dentry_unused); WARN_ON_ONCE(!list_lru_add(&dentry->d_sb->s_dentry_lru, &dentry->d_lru)); } static void d_lru_del(struct dentry *dentry) { D_FLAG_VERIFY(dentry, DCACHE_LRU_LIST); dentry->d_flags &= ~DCACHE_LRU_LIST; this_cpu_dec(nr_dentry_unused); WARN_ON_ONCE(!list_lru_del(&dentry->d_sb->s_dentry_lru, &dentry->d_lru)); } static void d_shrink_del(struct dentry *dentry) { D_FLAG_VERIFY(dentry, DCACHE_SHRINK_LIST | DCACHE_LRU_LIST); list_del_init(&dentry->d_lru); dentry->d_flags &= ~(DCACHE_SHRINK_LIST | DCACHE_LRU_LIST); this_cpu_dec(nr_dentry_unused); } static void d_shrink_add(struct dentry *dentry, struct list_head *list) { D_FLAG_VERIFY(dentry, 0); list_add(&dentry->d_lru, list); dentry->d_flags |= DCACHE_SHRINK_LIST | DCACHE_LRU_LIST; this_cpu_inc(nr_dentry_unused); } /* * These can only be called under the global LRU lock, ie during the * callback for freeing the LRU list. "isolate" removes it from the * LRU lists entirely, while shrink_move moves it to the indicated * private list. */ static void d_lru_isolate(struct list_lru_one *lru, struct dentry *dentry) { D_FLAG_VERIFY(dentry, DCACHE_LRU_LIST); dentry->d_flags &= ~DCACHE_LRU_LIST; this_cpu_dec(nr_dentry_unused); list_lru_isolate(lru, &dentry->d_lru); } static void d_lru_shrink_move(struct list_lru_one *lru, struct dentry *dentry, struct list_head *list) { D_FLAG_VERIFY(dentry, DCACHE_LRU_LIST); dentry->d_flags |= DCACHE_SHRINK_LIST; list_lru_isolate_move(lru, &dentry->d_lru, list); } /* * dentry_lru_(add|del)_list) must be called with d_lock held. */ static void dentry_lru_add(struct dentry *dentry) { if (unlikely(!(dentry->d_flags & DCACHE_LRU_LIST))) d_lru_add(dentry); } /** * d_drop - drop a dentry * @dentry: dentry to drop * * d_drop() unhashes the entry from the parent dentry hashes, so that it won't * be found through a VFS lookup any more. Note that this is different from * deleting the dentry - d_delete will try to mark the dentry negative if * possible, giving a successful _negative_ lookup, while d_drop will * just make the cache lookup fail. * * d_drop() is used mainly for stuff that wants to invalidate a dentry for some * reason (NFS timeouts or autofs deletes). * * __d_drop requires dentry->d_lock. */ void __d_drop(struct dentry *dentry) { if (!d_unhashed(dentry)) { struct hlist_bl_head *b; /* * Hashed dentries are normally on the dentry hashtable, * with the exception of those newly allocated by * d_obtain_alias, which are always IS_ROOT: */ if (unlikely(IS_ROOT(dentry))) b = &dentry->d_sb->s_anon; else b = d_hash(dentry->d_parent, dentry->d_name.hash); hlist_bl_lock(b); __hlist_bl_del(&dentry->d_hash); dentry->d_hash.pprev = NULL; hlist_bl_unlock(b); dentry_rcuwalk_invalidate(dentry); } } EXPORT_SYMBOL(__d_drop); void d_drop(struct dentry *dentry) { spin_lock(&dentry->d_lock); __d_drop(dentry); spin_unlock(&dentry->d_lock); } EXPORT_SYMBOL(d_drop); static void __dentry_kill(struct dentry *dentry) { struct dentry *parent = NULL; bool can_free = true; if (!IS_ROOT(dentry)) parent = dentry->d_parent; /* * The dentry is now unrecoverably dead to the world. */ lockref_mark_dead(&dentry->d_lockref); /* * inform the fs via d_prune that this dentry is about to be * unhashed and destroyed. */ if (dentry->d_flags & DCACHE_OP_PRUNE) dentry->d_op->d_prune(dentry); if (dentry->d_flags & DCACHE_LRU_LIST) { if (!(dentry->d_flags & DCACHE_SHRINK_LIST)) d_lru_del(dentry); } /* if it was on the hash then remove it */ __d_drop(dentry); __list_del_entry(&dentry->d_child); /* * Inform d_walk() that we are no longer attached to the * dentry tree */ dentry->d_flags |= DCACHE_DENTRY_KILLED; if (parent) spin_unlock(&parent->d_lock); dentry_iput(dentry); /* * dentry_iput drops the locks, at which point nobody (except * transient RCU lookups) can reach this dentry. */ BUG_ON(dentry->d_lockref.count > 0); this_cpu_dec(nr_dentry); if (dentry->d_op && dentry->d_op->d_release) dentry->d_op->d_release(dentry); spin_lock(&dentry->d_lock); if (dentry->d_flags & DCACHE_SHRINK_LIST) { dentry->d_flags |= DCACHE_MAY_FREE; can_free = false; } spin_unlock(&dentry->d_lock); if (likely(can_free)) dentry_free(dentry); } /* * Finish off a dentry we've decided to kill. * dentry->d_lock must be held, returns with it unlocked. * If ref is non-zero, then decrement the refcount too. * Returns dentry requiring refcount drop, or NULL if we're done. */ static struct dentry *dentry_kill(struct dentry *dentry) __releases(dentry->d_lock) { struct inode *inode = dentry->d_inode; struct dentry *parent = NULL; if (inode && unlikely(!spin_trylock(&inode->i_lock))) goto failed; if (!IS_ROOT(dentry)) { parent = dentry->d_parent; if (unlikely(!spin_trylock(&parent->d_lock))) { if (inode) spin_unlock(&inode->i_lock); goto failed; } } __dentry_kill(dentry); return parent; failed: spin_unlock(&dentry->d_lock); cpu_relax(); return dentry; /* try again with same dentry */ } static inline struct dentry *lock_parent(struct dentry *dentry) { struct dentry *parent = dentry->d_parent; if (IS_ROOT(dentry)) return NULL; if (unlikely(dentry->d_lockref.count < 0)) return NULL; if (likely(spin_trylock(&parent->d_lock))) return parent; rcu_read_lock(); spin_unlock(&dentry->d_lock); again: parent = ACCESS_ONCE(dentry->d_parent); spin_lock(&parent->d_lock); /* * We can't blindly lock dentry until we are sure * that we won't violate the locking order. * Any changes of dentry->d_parent must have * been done with parent->d_lock held, so * spin_lock() above is enough of a barrier * for checking if it's still our child. */ if (unlikely(parent != dentry->d_parent)) { spin_unlock(&parent->d_lock); goto again; } rcu_read_unlock(); if (parent != dentry) spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED); else parent = NULL; return parent; } /* * Try to do a lockless dput(), and return whether that was successful. * * If unsuccessful, we return false, having already taken the dentry lock. * * The caller needs to hold the RCU read lock, so that the dentry is * guaranteed to stay around even if the refcount goes down to zero! */ static inline bool fast_dput(struct dentry *dentry) { int ret; unsigned int d_flags; /* * If we have a d_op->d_delete() operation, we sould not * let the dentry count go to zero, so use "put_or_lock". */ if (unlikely(dentry->d_flags & DCACHE_OP_DELETE)) return lockref_put_or_lock(&dentry->d_lockref); /* * .. otherwise, we can try to just decrement the * lockref optimistically. */ ret = lockref_put_return(&dentry->d_lockref); /* * If the lockref_put_return() failed due to the lock being held * by somebody else, the fast path has failed. We will need to * get the lock, and then check the count again. */ if (unlikely(ret < 0)) { spin_lock(&dentry->d_lock); if (dentry->d_lockref.count > 1) { dentry->d_lockref.count--; spin_unlock(&dentry->d_lock); return 1; } return 0; } /* * If we weren't the last ref, we're done. */ if (ret) return 1; /* * Careful, careful. The reference count went down * to zero, but we don't hold the dentry lock, so * somebody else could get it again, and do another * dput(), and we need to not race with that. * * However, there is a very special and common case * where we don't care, because there is nothing to * do: the dentry is still hashed, it does not have * a 'delete' op, and it's referenced and already on * the LRU list. * * NOTE! Since we aren't locked, these values are * not "stable". However, it is sufficient that at * some point after we dropped the reference the * dentry was hashed and the flags had the proper * value. Other dentry users may have re-gotten * a reference to the dentry and change that, but * our work is done - we can leave the dentry * around with a zero refcount. */ smp_rmb(); d_flags = ACCESS_ONCE(dentry->d_flags); d_flags &= DCACHE_REFERENCED | DCACHE_LRU_LIST | DCACHE_DISCONNECTED; /* Nothing to do? Dropping the reference was all we needed? */ if (d_flags == (DCACHE_REFERENCED | DCACHE_LRU_LIST) && !d_unhashed(dentry)) return 1; /* * Not the fast normal case? Get the lock. We've already decremented * the refcount, but we'll need to re-check the situation after * getting the lock. */ spin_lock(&dentry->d_lock); /* * Did somebody else grab a reference to it in the meantime, and * we're no longer the last user after all? Alternatively, somebody * else could have killed it and marked it dead. Either way, we * don't need to do anything else. */ if (dentry->d_lockref.count) { spin_unlock(&dentry->d_lock); return 1; } /* * Re-get the reference we optimistically dropped. We hold the * lock, and we just tested that it was zero, so we can just * set it to 1. */ dentry->d_lockref.count = 1; return 0; } /* * This is dput * * This is complicated by the fact that we do not want to put * dentries that are no longer on any hash chain on the unused * list: we'd much rather just get rid of them immediately. * * However, that implies that we have to traverse the dentry * tree upwards to the parents which might _also_ now be * scheduled for deletion (it may have been only waiting for * its last child to go away). * * This tail recursion is done by hand as we don't want to depend * on the compiler to always get this right (gcc generally doesn't). * Real recursion would eat up our stack space. */ /* * dput - release a dentry * @dentry: dentry to release * * Release a dentry. This will drop the usage count and if appropriate * call the dentry unlink method as well as removing it from the queues and * releasing its resources. If the parent dentries were scheduled for release * they too may now get deleted. */ void dput(struct dentry *dentry) { if (unlikely(!dentry)) return; repeat: rcu_read_lock(); if (likely(fast_dput(dentry))) { rcu_read_unlock(); return; } /* Slow case: now with the dentry lock held */ rcu_read_unlock(); /* Unreachable? Get rid of it */ if (unlikely(d_unhashed(dentry))) goto kill_it; if (unlikely(dentry->d_flags & DCACHE_DISCONNECTED)) goto kill_it; if (unlikely(dentry->d_flags & DCACHE_OP_DELETE)) { if (dentry->d_op->d_delete(dentry)) goto kill_it; } if (!(dentry->d_flags & DCACHE_REFERENCED)) dentry->d_flags |= DCACHE_REFERENCED; dentry_lru_add(dentry); dentry->d_lockref.count--; spin_unlock(&dentry->d_lock); return; kill_it: dentry = dentry_kill(dentry); if (dentry) goto repeat; } EXPORT_SYMBOL(dput); /* This must be called with d_lock held */ static inline void __dget_dlock(struct dentry *dentry) { dentry->d_lockref.count++; } static inline void __dget(struct dentry *dentry) { lockref_get(&dentry->d_lockref); } struct dentry *dget_parent(struct dentry *dentry) { int gotref; struct dentry *ret; /* * Do optimistic parent lookup without any * locking. */ rcu_read_lock(); ret = ACCESS_ONCE(dentry->d_parent); gotref = lockref_get_not_zero(&ret->d_lockref); rcu_read_unlock(); if (likely(gotref)) { if (likely(ret == ACCESS_ONCE(dentry->d_parent))) return ret; dput(ret); } repeat: /* * Don't need rcu_dereference because we re-check it was correct under * the lock. */ rcu_read_lock(); ret = dentry->d_parent; spin_lock(&ret->d_lock); if (unlikely(ret != dentry->d_parent)) { spin_unlock(&ret->d_lock); rcu_read_unlock(); goto repeat; } rcu_read_unlock(); BUG_ON(!ret->d_lockref.count); ret->d_lockref.count++; spin_unlock(&ret->d_lock); return ret; } EXPORT_SYMBOL(dget_parent); /** * d_find_alias - grab a hashed alias of inode * @inode: inode in question * * If inode has a hashed alias, or is a directory and has any alias, * acquire the reference to alias and return it. Otherwise return NULL. * Notice that if inode is a directory there can be only one alias and * it can be unhashed only if it has no children, or if it is the root * of a filesystem, or if the directory was renamed and d_revalidate * was the first vfs operation to notice. * * If the inode has an IS_ROOT, DCACHE_DISCONNECTED alias, then prefer * any other hashed alias over that one. */ static struct dentry *__d_find_alias(struct inode *inode) { struct dentry *alias, *discon_alias; again: discon_alias = NULL; hlist_for_each_entry(alias, &inode->i_dentry, d_u.d_alias) { spin_lock(&alias->d_lock); if (S_ISDIR(inode->i_mode) || !d_unhashed(alias)) { if (IS_ROOT(alias) && (alias->d_flags & DCACHE_DISCONNECTED)) { discon_alias = alias; } else { __dget_dlock(alias); spin_unlock(&alias->d_lock); return alias; } } spin_unlock(&alias->d_lock); } if (discon_alias) { alias = discon_alias; spin_lock(&alias->d_lock); if (S_ISDIR(inode->i_mode) || !d_unhashed(alias)) { __dget_dlock(alias); spin_unlock(&alias->d_lock); return alias; } spin_unlock(&alias->d_lock); goto again; } return NULL; } struct dentry *d_find_alias(struct inode *inode) { struct dentry *de = NULL; if (!hlist_empty(&inode->i_dentry)) { spin_lock(&inode->i_lock); de = __d_find_alias(inode); spin_unlock(&inode->i_lock); } return de; } EXPORT_SYMBOL(d_find_alias); /* * Try to kill dentries associated with this inode. * WARNING: you must own a reference to inode. */ void d_prune_aliases(struct inode *inode) { struct dentry *dentry; restart: spin_lock(&inode->i_lock); hlist_for_each_entry(dentry, &inode->i_dentry, d_u.d_alias) { spin_lock(&dentry->d_lock); if (!dentry->d_lockref.count) { struct dentry *parent = lock_parent(dentry); if (likely(!dentry->d_lockref.count)) { __dentry_kill(dentry); dput(parent); goto restart; } if (parent) spin_unlock(&parent->d_lock); } spin_unlock(&dentry->d_lock); } spin_unlock(&inode->i_lock); } EXPORT_SYMBOL(d_prune_aliases); static void shrink_dentry_list(struct list_head *list) { struct dentry *dentry, *parent; while (!list_empty(list)) { struct inode *inode; dentry = list_entry(list->prev, struct dentry, d_lru); spin_lock(&dentry->d_lock); parent = lock_parent(dentry); /* * The dispose list is isolated and dentries are not accounted * to the LRU here, so we can simply remove it from the list * here regardless of whether it is referenced or not. */ d_shrink_del(dentry); /* * We found an inuse dentry which was not removed from * the LRU because of laziness during lookup. Do not free it. */ if (dentry->d_lockref.count > 0) { spin_unlock(&dentry->d_lock); if (parent) spin_unlock(&parent->d_lock); continue; } if (unlikely(dentry->d_flags & DCACHE_DENTRY_KILLED)) { bool can_free = dentry->d_flags & DCACHE_MAY_FREE; spin_unlock(&dentry->d_lock); if (parent) spin_unlock(&parent->d_lock); if (can_free) dentry_free(dentry); continue; } inode = dentry->d_inode; if (inode && unlikely(!spin_trylock(&inode->i_lock))) { d_shrink_add(dentry, list); spin_unlock(&dentry->d_lock); if (parent) spin_unlock(&parent->d_lock); continue; } __dentry_kill(dentry); /* * We need to prune ancestors too. This is necessary to prevent * quadratic behavior of shrink_dcache_parent(), but is also * expected to be beneficial in reducing dentry cache * fragmentation. */ dentry = parent; while (dentry && !lockref_put_or_lock(&dentry->d_lockref)) { parent = lock_parent(dentry); if (dentry->d_lockref.count != 1) { dentry->d_lockref.count--; spin_unlock(&dentry->d_lock); if (parent) spin_unlock(&parent->d_lock); break; } inode = dentry->d_inode; /* can't be NULL */ if (unlikely(!spin_trylock(&inode->i_lock))) { spin_unlock(&dentry->d_lock); if (parent) spin_unlock(&parent->d_lock); cpu_relax(); continue; } __dentry_kill(dentry); dentry = parent; } } } static enum lru_status dentry_lru_isolate(struct list_head *item, struct list_lru_one *lru, spinlock_t *lru_lock, void *arg) { struct list_head *freeable = arg; struct dentry *dentry = container_of(item, struct dentry, d_lru); /* * we are inverting the lru lock/dentry->d_lock here, * so use a trylock. If we fail to get the lock, just skip * it */ if (!spin_trylock(&dentry->d_lock)) return LRU_SKIP; /* * Referenced dentries are still in use. If they have active * counts, just remove them from the LRU. Otherwise give them * another pass through the LRU. */ if (dentry->d_lockref.count) { d_lru_isolate(lru, dentry); spin_unlock(&dentry->d_lock); return LRU_REMOVED; } if (dentry->d_flags & DCACHE_REFERENCED) { dentry->d_flags &= ~DCACHE_REFERENCED; spin_unlock(&dentry->d_lock); /* * The list move itself will be made by the common LRU code. At * this point, we've dropped the dentry->d_lock but keep the * lru lock. This is safe to do, since every list movement is * protected by the lru lock even if both locks are held. * * This is guaranteed by the fact that all LRU management * functions are intermediated by the LRU API calls like * list_lru_add and list_lru_del. List movement in this file * only ever occur through this functions or through callbacks * like this one, that are called from the LRU API. * * The only exceptions to this are functions like * shrink_dentry_list, and code that first checks for the * DCACHE_SHRINK_LIST flag. Those are guaranteed to be * operating only with stack provided lists after they are * properly isolated from the main list. It is thus, always a * local access. */ return LRU_ROTATE; } d_lru_shrink_move(lru, dentry, freeable); spin_unlock(&dentry->d_lock); return LRU_REMOVED; } /** * prune_dcache_sb - shrink the dcache * @sb: superblock * @sc: shrink control, passed to list_lru_shrink_walk() * * Attempt to shrink the superblock dcache LRU by @sc->nr_to_scan entries. This * is done when we need more memory and called from the superblock shrinker * function. * * This function may fail to free any resources if all the dentries are in * use. */ long prune_dcache_sb(struct super_block *sb, struct shrink_control *sc) { LIST_HEAD(dispose); long freed; freed = list_lru_shrink_walk(&sb->s_dentry_lru, sc, dentry_lru_isolate, &dispose); shrink_dentry_list(&dispose); return freed; } static enum lru_status dentry_lru_isolate_shrink(struct list_head *item, struct list_lru_one *lru, spinlock_t *lru_lock, void *arg) { struct list_head *freeable = arg; struct dentry *dentry = container_of(item, struct dentry, d_lru); /* * we are inverting the lru lock/dentry->d_lock here, * so use a trylock. If we fail to get the lock, just skip * it */ if (!spin_trylock(&dentry->d_lock)) return LRU_SKIP; d_lru_shrink_move(lru, dentry, freeable); spin_unlock(&dentry->d_lock); return LRU_REMOVED; } /** * shrink_dcache_sb - shrink dcache for a superblock * @sb: superblock * * Shrink the dcache for the specified super block. This is used to free * the dcache before unmounting a file system. */ void shrink_dcache_sb(struct super_block *sb) { long freed; do { LIST_HEAD(dispose); freed = list_lru_walk(&sb->s_dentry_lru, dentry_lru_isolate_shrink, &dispose, UINT_MAX); this_cpu_sub(nr_dentry_unused, freed); shrink_dentry_list(&dispose); } while (freed > 0); } EXPORT_SYMBOL(shrink_dcache_sb); /** * enum d_walk_ret - action to talke during tree walk * @D_WALK_CONTINUE: contrinue walk * @D_WALK_QUIT: quit walk * @D_WALK_NORETRY: quit when retry is needed * @D_WALK_SKIP: skip this dentry and its children */ enum d_walk_ret { D_WALK_CONTINUE, D_WALK_QUIT, D_WALK_NORETRY, D_WALK_SKIP, }; /** * d_walk - walk the dentry tree * @parent: start of walk * @data: data passed to @enter() and @finish() * @enter: callback when first entering the dentry * @finish: callback when successfully finished the walk * * The @enter() and @finish() callbacks are called with d_lock held. */ static void d_walk(struct dentry *parent, void *data, enum d_walk_ret (*enter)(void *, struct dentry *), void (*finish)(void *)) { struct dentry *this_parent; struct list_head *next; unsigned seq = 0; enum d_walk_ret ret; bool retry = true; again: read_seqbegin_or_lock(&rename_lock, &seq); this_parent = parent; spin_lock(&this_parent->d_lock); ret = enter(data, this_parent); switch (ret) { case D_WALK_CONTINUE: break; case D_WALK_QUIT: case D_WALK_SKIP: goto out_unlock; case D_WALK_NORETRY: retry = false; break; } repeat: next = this_parent->d_subdirs.next; resume: while (next != &this_parent->d_subdirs) { struct list_head *tmp = next; struct dentry *dentry = list_entry(tmp, struct dentry, d_child); next = tmp->next; spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED); ret = enter(data, dentry); switch (ret) { case D_WALK_CONTINUE: break; case D_WALK_QUIT: spin_unlock(&dentry->d_lock); goto out_unlock; case D_WALK_NORETRY: retry = false; break; case D_WALK_SKIP: spin_unlock(&dentry->d_lock); continue; } if (!list_empty(&dentry->d_subdirs)) { spin_unlock(&this_parent->d_lock); spin_release(&dentry->d_lock.dep_map, 1, _RET_IP_); this_parent = dentry; spin_acquire(&this_parent->d_lock.dep_map, 0, 1, _RET_IP_); goto repeat; } spin_unlock(&dentry->d_lock); } /* * All done at this level ... ascend and resume the search. */ rcu_read_lock(); ascend: if (this_parent != parent) { struct dentry *child = this_parent; this_parent = child->d_parent; spin_unlock(&child->d_lock); spin_lock(&this_parent->d_lock); /* might go back up the wrong parent if we have had a rename. */ if (need_seqretry(&rename_lock, seq)) goto rename_retry; /* go into the first sibling still alive */ do { next = child->d_child.next; if (next == &this_parent->d_subdirs) goto ascend; child = list_entry(next, struct dentry, d_child); } while (unlikely(child->d_flags & DCACHE_DENTRY_KILLED)); rcu_read_unlock(); goto resume; } if (need_seqretry(&rename_lock, seq)) goto rename_retry; rcu_read_unlock(); if (finish) finish(data); out_unlock: spin_unlock(&this_parent->d_lock); done_seqretry(&rename_lock, seq); return; rename_retry: spin_unlock(&this_parent->d_lock); rcu_read_unlock(); BUG_ON(seq & 1); if (!retry) return; seq = 1; goto again; } /* * Search for at least 1 mount point in the dentry's subdirs. * We descend to the next level whenever the d_subdirs * list is non-empty and continue searching. */ static enum d_walk_ret check_mount(void *data, struct dentry *dentry) { int *ret = data; if (d_mountpoint(dentry)) { *ret = 1; return D_WALK_QUIT; } return D_WALK_CONTINUE; } /** * have_submounts - check for mounts over a dentry * @parent: dentry to check. * * Return true if the parent or its subdirectories contain * a mount point */ int have_submounts(struct dentry *parent) { int ret = 0; d_walk(parent, &ret, check_mount, NULL); return ret; } EXPORT_SYMBOL(have_submounts); /* * Called by mount code to set a mountpoint and check if the mountpoint is * reachable (e.g. NFS can unhash a directory dentry and then the complete * subtree can become unreachable). * * Only one of d_invalidate() and d_set_mounted() must succeed. For * this reason take rename_lock and d_lock on dentry and ancestors. */ int d_set_mounted(struct dentry *dentry) { struct dentry *p; int ret = -ENOENT; write_seqlock(&rename_lock); for (p = dentry->d_parent; !IS_ROOT(p); p = p->d_parent) { /* Need exclusion wrt. d_invalidate() */ spin_lock(&p->d_lock); if (unlikely(d_unhashed(p))) { spin_unlock(&p->d_lock); goto out; } spin_unlock(&p->d_lock); } spin_lock(&dentry->d_lock); if (!d_unlinked(dentry)) { dentry->d_flags |= DCACHE_MOUNTED; ret = 0; } spin_unlock(&dentry->d_lock); out: write_sequnlock(&rename_lock); return ret; } /* * Search the dentry child list of the specified parent, * and move any unused dentries to the end of the unused * list for prune_dcache(). We descend to the next level * whenever the d_subdirs list is non-empty and continue * searching. * * It returns zero iff there are no unused children, * otherwise it returns the number of children moved to * the end of the unused list. This may not be the total * number of unused children, because select_parent can * drop the lock and return early due to latency * constraints. */ struct select_data { struct dentry *start; struct list_head dispose; int found; }; static enum d_walk_ret select_collect(void *_data, struct dentry *dentry) { struct select_data *data = _data; enum d_walk_ret ret = D_WALK_CONTINUE; if (data->start == dentry) goto out; if (dentry->d_flags & DCACHE_SHRINK_LIST) { data->found++; } else { if (dentry->d_flags & DCACHE_LRU_LIST) d_lru_del(dentry); if (!dentry->d_lockref.count) { d_shrink_add(dentry, &data->dispose); data->found++; } } /* * We can return to the caller if we have found some (this * ensures forward progress). We'll be coming back to find * the rest. */ if (!list_empty(&data->dispose)) ret = need_resched() ? D_WALK_QUIT : D_WALK_NORETRY; out: return ret; } /** * shrink_dcache_parent - prune dcache * @parent: parent of entries to prune * * Prune the dcache to remove unused children of the parent dentry. */ void shrink_dcache_parent(struct dentry *parent) { for (;;) { struct select_data data; INIT_LIST_HEAD(&data.dispose); data.start = parent; data.found = 0; d_walk(parent, &data, select_collect, NULL); if (!data.found) break; shrink_dentry_list(&data.dispose); cond_resched(); } } EXPORT_SYMBOL(shrink_dcache_parent); static enum d_walk_ret umount_check(void *_data, struct dentry *dentry) { /* it has busy descendents; complain about those instead */ if (!list_empty(&dentry->d_subdirs)) return D_WALK_CONTINUE; /* root with refcount 1 is fine */ if (dentry == _data && dentry->d_lockref.count == 1) return D_WALK_CONTINUE; printk(KERN_ERR "BUG: Dentry %p{i=%lx,n=%pd} " " still in use (%d) [unmount of %s %s]\n", dentry, dentry->d_inode ? dentry->d_inode->i_ino : 0UL, dentry, dentry->d_lockref.count, dentry->d_sb->s_type->name, dentry->d_sb->s_id); WARN_ON(1); return D_WALK_CONTINUE; } static void do_one_tree(struct dentry *dentry) { shrink_dcache_parent(dentry); d_walk(dentry, dentry, umount_check, NULL); d_drop(dentry); dput(dentry); } /* * destroy the dentries attached to a superblock on unmounting */ void shrink_dcache_for_umount(struct super_block *sb) { struct dentry *dentry; WARN(down_read_trylock(&sb->s_umount), "s_umount should've been locked"); dentry = sb->s_root; sb->s_root = NULL; do_one_tree(dentry); while (!hlist_bl_empty(&sb->s_anon)) { dentry = dget(hlist_bl_entry(hlist_bl_first(&sb->s_anon), struct dentry, d_hash)); do_one_tree(dentry); } } struct detach_data { struct select_data select; struct dentry *mountpoint; }; static enum d_walk_ret detach_and_collect(void *_data, struct dentry *dentry) { struct detach_data *data = _data; if (d_mountpoint(dentry)) { __dget_dlock(dentry); data->mountpoint = dentry; return D_WALK_QUIT; } return select_collect(&data->select, dentry); } static void check_and_drop(void *_data) { struct detach_data *data = _data; if (!data->mountpoint && !data->select.found) __d_drop(data->select.start); } /** * d_invalidate - detach submounts, prune dcache, and drop * @dentry: dentry to invalidate (aka detach, prune and drop) * * no dcache lock. * * The final d_drop is done as an atomic operation relative to * rename_lock ensuring there are no races with d_set_mounted. This * ensures there are no unhashed dentries on the path to a mountpoint. */ void d_invalidate(struct dentry *dentry) { /* * If it's already been dropped, return OK. */ spin_lock(&dentry->d_lock); if (d_unhashed(dentry)) { spin_unlock(&dentry->d_lock); return; } spin_unlock(&dentry->d_lock); /* Negative dentries can be dropped without further checks */ if (!dentry->d_inode) { d_drop(dentry); return; } for (;;) { struct detach_data data; data.mountpoint = NULL; INIT_LIST_HEAD(&data.select.dispose); data.select.start = dentry; data.select.found = 0; d_walk(dentry, &data, detach_and_collect, check_and_drop); if (data.select.found) shrink_dentry_list(&data.select.dispose); if (data.mountpoint) { detach_mounts(data.mountpoint); dput(data.mountpoint); } if (!data.mountpoint && !data.select.found) break; cond_resched(); } } EXPORT_SYMBOL(d_invalidate); /** * __d_alloc - allocate a dcache entry * @sb: filesystem it will belong to * @name: qstr of the name * * Allocates a dentry. It returns %NULL if there is insufficient memory * available. On a success the dentry is returned. The name passed in is * copied and the copy passed in may be reused after this call. */ struct dentry *__d_alloc(struct super_block *sb, const struct qstr *name) { struct dentry *dentry; char *dname; dentry = kmem_cache_alloc(dentry_cache, GFP_KERNEL); if (!dentry) return NULL; /* * We guarantee that the inline name is always NUL-terminated. * This way the memcpy() done by the name switching in rename * will still always have a NUL at the end, even if we might * be overwriting an internal NUL character */ dentry->d_iname[DNAME_INLINE_LEN-1] = 0; if (name->len > DNAME_INLINE_LEN-1) { size_t size = offsetof(struct external_name, name[1]); struct external_name *p = kmalloc(size + name->len, GFP_KERNEL); if (!p) { kmem_cache_free(dentry_cache, dentry); return NULL; } atomic_set(&p->u.count, 1); dname = p->name; if (IS_ENABLED(CONFIG_DCACHE_WORD_ACCESS)) kasan_unpoison_shadow(dname, round_up(name->len + 1, sizeof(unsigned long))); } else { dname = dentry->d_iname; } dentry->d_name.len = name->len; dentry->d_name.hash = name->hash; memcpy(dname, name->name, name->len); dname[name->len] = 0; /* Make sure we always see the terminating NUL character */ smp_wmb(); dentry->d_name.name = dname; dentry->d_lockref.count = 1; dentry->d_flags = 0; spin_lock_init(&dentry->d_lock); seqcount_init(&dentry->d_seq); dentry->d_inode = NULL; dentry->d_parent = dentry; dentry->d_sb = sb; dentry->d_op = NULL; dentry->d_fsdata = NULL; INIT_HLIST_BL_NODE(&dentry->d_hash); INIT_LIST_HEAD(&dentry->d_lru); INIT_LIST_HEAD(&dentry->d_subdirs); INIT_HLIST_NODE(&dentry->d_u.d_alias); INIT_LIST_HEAD(&dentry->d_child); d_set_d_op(dentry, dentry->d_sb->s_d_op); this_cpu_inc(nr_dentry); return dentry; } /** * d_alloc - allocate a dcache entry * @parent: parent of entry to allocate * @name: qstr of the name * * Allocates a dentry. It returns %NULL if there is insufficient memory * available. On a success the dentry is returned. The name passed in is * copied and the copy passed in may be reused after this call. */ struct dentry *d_alloc(struct dentry * parent, const struct qstr *name) { struct dentry *dentry = __d_alloc(parent->d_sb, name); if (!dentry) return NULL; spin_lock(&parent->d_lock); /* * don't need child lock because it is not subject * to concurrency here */ __dget_dlock(parent); dentry->d_parent = parent; list_add(&dentry->d_child, &parent->d_subdirs); spin_unlock(&parent->d_lock); return dentry; } EXPORT_SYMBOL(d_alloc); /** * d_alloc_pseudo - allocate a dentry (for lookup-less filesystems) * @sb: the superblock * @name: qstr of the name * * For a filesystem that just pins its dentries in memory and never * performs lookups at all, return an unhashed IS_ROOT dentry. */ struct dentry *d_alloc_pseudo(struct super_block *sb, const struct qstr *name) { return __d_alloc(sb, name); } EXPORT_SYMBOL(d_alloc_pseudo); struct dentry *d_alloc_name(struct dentry *parent, const char *name) { struct qstr q; q.name = name; q.len = strlen(name); q.hash = full_name_hash(q.name, q.len); return d_alloc(parent, &q); } EXPORT_SYMBOL(d_alloc_name); void d_set_d_op(struct dentry *dentry, const struct dentry_operations *op) { WARN_ON_ONCE(dentry->d_op); WARN_ON_ONCE(dentry->d_flags & (DCACHE_OP_HASH | DCACHE_OP_COMPARE | DCACHE_OP_REVALIDATE | DCACHE_OP_WEAK_REVALIDATE | DCACHE_OP_DELETE | DCACHE_OP_SELECT_INODE)); dentry->d_op = op; if (!op) return; if (op->d_hash) dentry->d_flags |= DCACHE_OP_HASH; if (op->d_compare) dentry->d_flags |= DCACHE_OP_COMPARE; if (op->d_revalidate) dentry->d_flags |= DCACHE_OP_REVALIDATE; if (op->d_weak_revalidate) dentry->d_flags |= DCACHE_OP_WEAK_REVALIDATE; if (op->d_delete) dentry->d_flags |= DCACHE_OP_DELETE; if (op->d_prune) dentry->d_flags |= DCACHE_OP_PRUNE; if (op->d_select_inode) dentry->d_flags |= DCACHE_OP_SELECT_INODE; } EXPORT_SYMBOL(d_set_d_op); /* * d_set_fallthru - Mark a dentry as falling through to a lower layer * @dentry - The dentry to mark * * Mark a dentry as falling through to the lower layer (as set with * d_pin_lower()). This flag may be recorded on the medium. */ void d_set_fallthru(struct dentry *dentry) { spin_lock(&dentry->d_lock); dentry->d_flags |= DCACHE_FALLTHRU; spin_unlock(&dentry->d_lock); } EXPORT_SYMBOL(d_set_fallthru); static unsigned d_flags_for_inode(struct inode *inode) { unsigned add_flags = DCACHE_REGULAR_TYPE; if (!inode) return DCACHE_MISS_TYPE; if (S_ISDIR(inode->i_mode)) { add_flags = DCACHE_DIRECTORY_TYPE; if (unlikely(!(inode->i_opflags & IOP_LOOKUP))) { if (unlikely(!inode->i_op->lookup)) add_flags = DCACHE_AUTODIR_TYPE; else inode->i_opflags |= IOP_LOOKUP; } goto type_determined; } if (unlikely(!(inode->i_opflags & IOP_NOFOLLOW))) { if (unlikely(inode->i_op->follow_link)) { add_flags = DCACHE_SYMLINK_TYPE; goto type_determined; } inode->i_opflags |= IOP_NOFOLLOW; } if (unlikely(!S_ISREG(inode->i_mode))) add_flags = DCACHE_SPECIAL_TYPE; type_determined: if (unlikely(IS_AUTOMOUNT(inode))) add_flags |= DCACHE_NEED_AUTOMOUNT; return add_flags; } static void __d_instantiate(struct dentry *dentry, struct inode *inode) { unsigned add_flags = d_flags_for_inode(inode); spin_lock(&dentry->d_lock); if (inode) hlist_add_head(&dentry->d_u.d_alias, &inode->i_dentry); __d_set_inode_and_type(dentry, inode, add_flags); dentry_rcuwalk_invalidate(dentry); spin_unlock(&dentry->d_lock); fsnotify_d_instantiate(dentry, inode); } /** * d_instantiate - fill in inode information for a dentry * @entry: dentry to complete * @inode: inode to attach to this dentry * * Fill in inode information in the entry. * * This turns negative dentries into productive full members * of society. * * NOTE! This assumes that the inode count has been incremented * (or otherwise set) by the caller to indicate that it is now * in use by the dcache. */ void d_instantiate(struct dentry *entry, struct inode * inode) { BUG_ON(!hlist_unhashed(&entry->d_u.d_alias)); if (inode) spin_lock(&inode->i_lock); __d_instantiate(entry, inode); if (inode) spin_unlock(&inode->i_lock); security_d_instantiate(entry, inode); } EXPORT_SYMBOL(d_instantiate); /** * d_instantiate_unique - instantiate a non-aliased dentry * @entry: dentry to instantiate * @inode: inode to attach to this dentry * * Fill in inode information in the entry. On success, it returns NULL. * If an unhashed alias of "entry" already exists, then we return the * aliased dentry instead and drop one reference to inode. * * Note that in order to avoid conflicts with rename() etc, the caller * had better be holding the parent directory semaphore. * * This also assumes that the inode count has been incremented * (or otherwise set) by the caller to indicate that it is now * in use by the dcache. */ static struct dentry *__d_instantiate_unique(struct dentry *entry, struct inode *inode) { struct dentry *alias; int len = entry->d_name.len; const char *name = entry->d_name.name; unsigned int hash = entry->d_name.hash; if (!inode) { __d_instantiate(entry, NULL); return NULL; } hlist_for_each_entry(alias, &inode->i_dentry, d_u.d_alias) { /* * Don't need alias->d_lock here, because aliases with * d_parent == entry->d_parent are not subject to name or * parent changes, because the parent inode i_mutex is held. */ if (alias->d_name.hash != hash) continue; if (alias->d_parent != entry->d_parent) continue; if (alias->d_name.len != len) continue; if (dentry_cmp(alias, name, len)) continue; __dget(alias); return alias; } __d_instantiate(entry, inode); return NULL; } struct dentry *d_instantiate_unique(struct dentry *entry, struct inode *inode) { struct dentry *result; BUG_ON(!hlist_unhashed(&entry->d_u.d_alias)); if (inode) spin_lock(&inode->i_lock); result = __d_instantiate_unique(entry, inode); if (inode) spin_unlock(&inode->i_lock); if (!result) { security_d_instantiate(entry, inode); return NULL; } BUG_ON(!d_unhashed(result)); iput(inode); return result; } EXPORT_SYMBOL(d_instantiate_unique); /** * d_instantiate_no_diralias - instantiate a non-aliased dentry * @entry: dentry to complete * @inode: inode to attach to this dentry * * Fill in inode information in the entry. If a directory alias is found, then * return an error (and drop inode). Together with d_materialise_unique() this * guarantees that a directory inode may never have more than one alias. */ int d_instantiate_no_diralias(struct dentry *entry, struct inode *inode) { BUG_ON(!hlist_unhashed(&entry->d_u.d_alias)); spin_lock(&inode->i_lock); if (S_ISDIR(inode->i_mode) && !hlist_empty(&inode->i_dentry)) { spin_unlock(&inode->i_lock); iput(inode); return -EBUSY; } __d_instantiate(entry, inode); spin_unlock(&inode->i_lock); security_d_instantiate(entry, inode); return 0; } EXPORT_SYMBOL(d_instantiate_no_diralias); struct dentry *d_make_root(struct inode *root_inode) { struct dentry *res = NULL; if (root_inode) { static const struct qstr name = QSTR_INIT("/", 1); res = __d_alloc(root_inode->i_sb, &name); if (res) d_instantiate(res, root_inode); else iput(root_inode); } return res; } EXPORT_SYMBOL(d_make_root); static struct dentry * __d_find_any_alias(struct inode *inode) { struct dentry *alias; if (hlist_empty(&inode->i_dentry)) return NULL; alias = hlist_entry(inode->i_dentry.first, struct dentry, d_u.d_alias); __dget(alias); return alias; } /** * d_find_any_alias - find any alias for a given inode * @inode: inode to find an alias for * * If any aliases exist for the given inode, take and return a * reference for one of them. If no aliases exist, return %NULL. */ struct dentry *d_find_any_alias(struct inode *inode) { struct dentry *de; spin_lock(&inode->i_lock); de = __d_find_any_alias(inode); spin_unlock(&inode->i_lock); return de; } EXPORT_SYMBOL(d_find_any_alias); static struct dentry *__d_obtain_alias(struct inode *inode, int disconnected) { static const struct qstr anonstring = QSTR_INIT("/", 1); struct dentry *tmp; struct dentry *res; unsigned add_flags; if (!inode) return ERR_PTR(-ESTALE); if (IS_ERR(inode)) return ERR_CAST(inode); res = d_find_any_alias(inode); if (res) goto out_iput; tmp = __d_alloc(inode->i_sb, &anonstring); if (!tmp) { res = ERR_PTR(-ENOMEM); goto out_iput; } spin_lock(&inode->i_lock); res = __d_find_any_alias(inode); if (res) { spin_unlock(&inode->i_lock); dput(tmp); goto out_iput; } /* attach a disconnected dentry */ add_flags = d_flags_for_inode(inode); if (disconnected) add_flags |= DCACHE_DISCONNECTED; spin_lock(&tmp->d_lock); __d_set_inode_and_type(tmp, inode, add_flags); hlist_add_head(&tmp->d_u.d_alias, &inode->i_dentry); hlist_bl_lock(&tmp->d_sb->s_anon); hlist_bl_add_head(&tmp->d_hash, &tmp->d_sb->s_anon); hlist_bl_unlock(&tmp->d_sb->s_anon); spin_unlock(&tmp->d_lock); spin_unlock(&inode->i_lock); security_d_instantiate(tmp, inode); return tmp; out_iput: if (res && !IS_ERR(res)) security_d_instantiate(res, inode); iput(inode); return res; } /** * d_obtain_alias - find or allocate a DISCONNECTED dentry for a given inode * @inode: inode to allocate the dentry for * * Obtain a dentry for an inode resulting from NFS filehandle conversion or * similar open by handle operations. The returned dentry may be anonymous, * or may have a full name (if the inode was already in the cache). * * When called on a directory inode, we must ensure that the inode only ever * has one dentry. If a dentry is found, that is returned instead of * allocating a new one. * * On successful return, the reference to the inode has been transferred * to the dentry. In case of an error the reference on the inode is released. * To make it easier to use in export operations a %NULL or IS_ERR inode may * be passed in and the error will be propagated to the return value, * with a %NULL @inode replaced by ERR_PTR(-ESTALE). */ struct dentry *d_obtain_alias(struct inode *inode) { return __d_obtain_alias(inode, 1); } EXPORT_SYMBOL(d_obtain_alias); /** * d_obtain_root - find or allocate a dentry for a given inode * @inode: inode to allocate the dentry for * * Obtain an IS_ROOT dentry for the root of a filesystem. * * We must ensure that directory inodes only ever have one dentry. If a * dentry is found, that is returned instead of allocating a new one. * * On successful return, the reference to the inode has been transferred * to the dentry. In case of an error the reference on the inode is * released. A %NULL or IS_ERR inode may be passed in and will be the * error will be propagate to the return value, with a %NULL @inode * replaced by ERR_PTR(-ESTALE). */ struct dentry *d_obtain_root(struct inode *inode) { return __d_obtain_alias(inode, 0); } EXPORT_SYMBOL(d_obtain_root); /** * d_add_ci - lookup or allocate new dentry with case-exact name * @inode: the inode case-insensitive lookup has found * @dentry: the negative dentry that was passed to the parent's lookup func * @name: the case-exact name to be associated with the returned dentry * * This is to avoid filling the dcache with case-insensitive names to the * same inode, only the actual correct case is stored in the dcache for * case-insensitive filesystems. * * For a case-insensitive lookup match and if the the case-exact dentry * already exists in in the dcache, use it and return it. * * If no entry exists with the exact case name, allocate new dentry with * the exact case, and return the spliced entry. */ struct dentry *d_add_ci(struct dentry *dentry, struct inode *inode, struct qstr *name) { struct dentry *found; struct dentry *new; /* * First check if a dentry matching the name already exists, * if not go ahead and create it now. */ found = d_hash_and_lookup(dentry->d_parent, name); if (!found) { new = d_alloc(dentry->d_parent, name); if (!new) { found = ERR_PTR(-ENOMEM); } else { found = d_splice_alias(inode, new); if (found) { dput(new); return found; } return new; } } iput(inode); return found; } EXPORT_SYMBOL(d_add_ci); /* * Do the slow-case of the dentry name compare. * * Unlike the dentry_cmp() function, we need to atomically * load the name and length information, so that the * filesystem can rely on them, and can use the 'name' and * 'len' information without worrying about walking off the * end of memory etc. * * Thus the read_seqcount_retry() and the "duplicate" info * in arguments (the low-level filesystem should not look * at the dentry inode or name contents directly, since * rename can change them while we're in RCU mode). */ enum slow_d_compare { D_COMP_OK, D_COMP_NOMATCH, D_COMP_SEQRETRY, }; static noinline enum slow_d_compare slow_dentry_cmp( const struct dentry *parent, struct dentry *dentry, unsigned int seq, const struct qstr *name) { int tlen = dentry->d_name.len; const char *tname = dentry->d_name.name; if (read_seqcount_retry(&dentry->d_seq, seq)) { cpu_relax(); return D_COMP_SEQRETRY; } if (parent->d_op->d_compare(parent, dentry, tlen, tname, name)) return D_COMP_NOMATCH; return D_COMP_OK; } /** * __d_lookup_rcu - search for a dentry (racy, store-free) * @parent: parent dentry * @name: qstr of name we wish to find * @seqp: returns d_seq value at the point where the dentry was found * Returns: dentry, or NULL * * __d_lookup_rcu is the dcache lookup function for rcu-walk name * resolution (store-free path walking) design described in * Documentation/filesystems/path-lookup.txt. * * This is not to be used outside core vfs. * * __d_lookup_rcu must only be used in rcu-walk mode, ie. with vfsmount lock * held, and rcu_read_lock held. The returned dentry must not be stored into * without taking d_lock and checking d_seq sequence count against @seq * returned here. * * A refcount may be taken on the found dentry with the d_rcu_to_refcount * function. * * Alternatively, __d_lookup_rcu may be called again to look up the child of * the returned dentry, so long as its parent's seqlock is checked after the * child is looked up. Thus, an interlocking stepping of sequence lock checks * is formed, giving integrity down the path walk. * * NOTE! The caller *has* to check the resulting dentry against the sequence * number we've returned before using any of the resulting dentry state! */ struct dentry *__d_lookup_rcu(const struct dentry *parent, const struct qstr *name, unsigned *seqp) { u64 hashlen = name->hash_len; const unsigned char *str = name->name; struct hlist_bl_head *b = d_hash(parent, hashlen_hash(hashlen)); struct hlist_bl_node *node; struct dentry *dentry; /* * Note: There is significant duplication with __d_lookup_rcu which is * required to prevent single threaded performance regressions * especially on architectures where smp_rmb (in seqcounts) are costly. * Keep the two functions in sync. */ /* * The hash list is protected using RCU. * * Carefully use d_seq when comparing a candidate dentry, to avoid * races with d_move(). * * It is possible that concurrent renames can mess up our list * walk here and result in missing our dentry, resulting in the * false-negative result. d_lookup() protects against concurrent * renames using rename_lock seqlock. * * See Documentation/filesystems/path-lookup.txt for more details. */ hlist_bl_for_each_entry_rcu(dentry, node, b, d_hash) { unsigned seq; seqretry: /* * The dentry sequence count protects us from concurrent * renames, and thus protects parent and name fields. * * The caller must perform a seqcount check in order * to do anything useful with the returned dentry. * * NOTE! We do a "raw" seqcount_begin here. That means that * we don't wait for the sequence count to stabilize if it * is in the middle of a sequence change. If we do the slow * dentry compare, we will do seqretries until it is stable, * and if we end up with a successful lookup, we actually * want to exit RCU lookup anyway. */ seq = raw_seqcount_begin(&dentry->d_seq); if (dentry->d_parent != parent) continue; if (d_unhashed(dentry)) continue; if (unlikely(parent->d_flags & DCACHE_OP_COMPARE)) { if (dentry->d_name.hash != hashlen_hash(hashlen)) continue; *seqp = seq; switch (slow_dentry_cmp(parent, dentry, seq, name)) { case D_COMP_OK: return dentry; case D_COMP_NOMATCH: continue; default: goto seqretry; } } if (dentry->d_name.hash_len != hashlen) continue; *seqp = seq; if (!dentry_cmp(dentry, str, hashlen_len(hashlen))) return dentry; } return NULL; } /** * d_lookup - search for a dentry * @parent: parent dentry * @name: qstr of name we wish to find * Returns: dentry, or NULL * * d_lookup searches the children of the parent dentry for the name in * question. If the dentry is found its reference count is incremented and the * dentry is returned. The caller must use dput to free the entry when it has * finished using it. %NULL is returned if the dentry does not exist. */ struct dentry *d_lookup(const struct dentry *parent, const struct qstr *name) { struct dentry *dentry; unsigned seq; do { seq = read_seqbegin(&rename_lock); dentry = __d_lookup(parent, name); if (dentry) break; } while (read_seqretry(&rename_lock, seq)); return dentry; } EXPORT_SYMBOL(d_lookup); /** * __d_lookup - search for a dentry (racy) * @parent: parent dentry * @name: qstr of name we wish to find * Returns: dentry, or NULL * * __d_lookup is like d_lookup, however it may (rarely) return a * false-negative result due to unrelated rename activity. * * __d_lookup is slightly faster by avoiding rename_lock read seqlock, * however it must be used carefully, eg. with a following d_lookup in * the case of failure. * * __d_lookup callers must be commented. */ struct dentry *__d_lookup(const struct dentry *parent, const struct qstr *name) { unsigned int len = name->len; unsigned int hash = name->hash; const unsigned char *str = name->name; struct hlist_bl_head *b = d_hash(parent, hash); struct hlist_bl_node *node; struct dentry *found = NULL; struct dentry *dentry; /* * Note: There is significant duplication with __d_lookup_rcu which is * required to prevent single threaded performance regressions * especially on architectures where smp_rmb (in seqcounts) are costly. * Keep the two functions in sync. */ /* * The hash list is protected using RCU. * * Take d_lock when comparing a candidate dentry, to avoid races * with d_move(). * * It is possible that concurrent renames can mess up our list * walk here and result in missing our dentry, resulting in the * false-negative result. d_lookup() protects against concurrent * renames using rename_lock seqlock. * * See Documentation/filesystems/path-lookup.txt for more details. */ rcu_read_lock(); hlist_bl_for_each_entry_rcu(dentry, node, b, d_hash) { if (dentry->d_name.hash != hash) continue; spin_lock(&dentry->d_lock); if (dentry->d_parent != parent) goto next; if (d_unhashed(dentry)) goto next; /* * It is safe to compare names since d_move() cannot * change the qstr (protected by d_lock). */ if (parent->d_flags & DCACHE_OP_COMPARE) { int tlen = dentry->d_name.len; const char *tname = dentry->d_name.name; if (parent->d_op->d_compare(parent, dentry, tlen, tname, name)) goto next; } else { if (dentry->d_name.len != len) goto next; if (dentry_cmp(dentry, str, len)) goto next; } dentry->d_lockref.count++; found = dentry; spin_unlock(&dentry->d_lock); break; next: spin_unlock(&dentry->d_lock); } rcu_read_unlock(); return found; } /** * d_hash_and_lookup - hash the qstr then search for a dentry * @dir: Directory to search in * @name: qstr of name we wish to find * * On lookup failure NULL is returned; on bad name - ERR_PTR(-error) */ struct dentry *d_hash_and_lookup(struct dentry *dir, struct qstr *name) { /* * Check for a fs-specific hash function. Note that we must * calculate the standard hash first, as the d_op->d_hash() * routine may choose to leave the hash value unchanged. */ name->hash = full_name_hash(name->name, name->len); if (dir->d_flags & DCACHE_OP_HASH) { int err = dir->d_op->d_hash(dir, name); if (unlikely(err < 0)) return ERR_PTR(err); } return d_lookup(dir, name); } EXPORT_SYMBOL(d_hash_and_lookup); /* * When a file is deleted, we have two options: * - turn this dentry into a negative dentry * - unhash this dentry and free it. * * Usually, we want to just turn this into * a negative dentry, but if anybody else is * currently using the dentry or the inode * we can't do that and we fall back on removing * it from the hash queues and waiting for * it to be deleted later when it has no users */ /** * d_delete - delete a dentry * @dentry: The dentry to delete * * Turn the dentry into a negative dentry if possible, otherwise * remove it from the hash queues so it can be deleted later */ void d_delete(struct dentry * dentry) { struct inode *inode; int isdir = 0; /* * Are we the only user? */ again: spin_lock(&dentry->d_lock); inode = dentry->d_inode; isdir = S_ISDIR(inode->i_mode); if (dentry->d_lockref.count == 1) { if (!spin_trylock(&inode->i_lock)) { spin_unlock(&dentry->d_lock); cpu_relax(); goto again; } dentry->d_flags &= ~DCACHE_CANT_MOUNT; dentry_unlink_inode(dentry); fsnotify_nameremove(dentry, isdir); return; } if (!d_unhashed(dentry)) __d_drop(dentry); spin_unlock(&dentry->d_lock); fsnotify_nameremove(dentry, isdir); } EXPORT_SYMBOL(d_delete); static void __d_rehash(struct dentry * entry, struct hlist_bl_head *b) { BUG_ON(!d_unhashed(entry)); hlist_bl_lock(b); entry->d_flags |= DCACHE_RCUACCESS; hlist_bl_add_head_rcu(&entry->d_hash, b); hlist_bl_unlock(b); } static void _d_rehash(struct dentry * entry) { __d_rehash(entry, d_hash(entry->d_parent, entry->d_name.hash)); } /** * d_rehash - add an entry back to the hash * @entry: dentry to add to the hash * * Adds a dentry to the hash according to its name. */ void d_rehash(struct dentry * entry) { spin_lock(&entry->d_lock); _d_rehash(entry); spin_unlock(&entry->d_lock); } EXPORT_SYMBOL(d_rehash); /** * dentry_update_name_case - update case insensitive dentry with a new name * @dentry: dentry to be updated * @name: new name * * Update a case insensitive dentry with new case of name. * * dentry must have been returned by d_lookup with name @name. Old and new * name lengths must match (ie. no d_compare which allows mismatched name * lengths). * * Parent inode i_mutex must be held over d_lookup and into this call (to * keep renames and concurrent inserts, and readdir(2) away). */ void dentry_update_name_case(struct dentry *dentry, struct qstr *name) { BUG_ON(!mutex_is_locked(&dentry->d_parent->d_inode->i_mutex)); BUG_ON(dentry->d_name.len != name->len); /* d_lookup gives this */ spin_lock(&dentry->d_lock); write_seqcount_begin(&dentry->d_seq); memcpy((unsigned char *)dentry->d_name.name, name->name, name->len); write_seqcount_end(&dentry->d_seq); spin_unlock(&dentry->d_lock); } EXPORT_SYMBOL(dentry_update_name_case); static void swap_names(struct dentry *dentry, struct dentry *target) { if (unlikely(dname_external(target))) { if (unlikely(dname_external(dentry))) { /* * Both external: swap the pointers */ swap(target->d_name.name, dentry->d_name.name); } else { /* * dentry:internal, target:external. Steal target's * storage and make target internal. */ memcpy(target->d_iname, dentry->d_name.name, dentry->d_name.len + 1); dentry->d_name.name = target->d_name.name; target->d_name.name = target->d_iname; } } else { if (unlikely(dname_external(dentry))) { /* * dentry:external, target:internal. Give dentry's * storage to target and make dentry internal */ memcpy(dentry->d_iname, target->d_name.name, target->d_name.len + 1); target->d_name.name = dentry->d_name.name; dentry->d_name.name = dentry->d_iname; } else { /* * Both are internal. */ unsigned int i; BUILD_BUG_ON(!IS_ALIGNED(DNAME_INLINE_LEN, sizeof(long))); kmemcheck_mark_initialized(dentry->d_iname, DNAME_INLINE_LEN); kmemcheck_mark_initialized(target->d_iname, DNAME_INLINE_LEN); for (i = 0; i < DNAME_INLINE_LEN / sizeof(long); i++) { swap(((long *) &dentry->d_iname)[i], ((long *) &target->d_iname)[i]); } } } swap(dentry->d_name.hash_len, target->d_name.hash_len); } static void copy_name(struct dentry *dentry, struct dentry *target) { struct external_name *old_name = NULL; if (unlikely(dname_external(dentry))) old_name = external_name(dentry); if (unlikely(dname_external(target))) { atomic_inc(&external_name(target)->u.count); dentry->d_name = target->d_name; } else { memcpy(dentry->d_iname, target->d_name.name, target->d_name.len + 1); dentry->d_name.name = dentry->d_iname; dentry->d_name.hash_len = target->d_name.hash_len; } if (old_name && likely(atomic_dec_and_test(&old_name->u.count))) kfree_rcu(old_name, u.head); } static void dentry_lock_for_move(struct dentry *dentry, struct dentry *target) { /* * XXXX: do we really need to take target->d_lock? */ if (IS_ROOT(dentry) || dentry->d_parent == target->d_parent) spin_lock(&target->d_parent->d_lock); else { if (d_ancestor(dentry->d_parent, target->d_parent)) { spin_lock(&dentry->d_parent->d_lock); spin_lock_nested(&target->d_parent->d_lock, DENTRY_D_LOCK_NESTED); } else { spin_lock(&target->d_parent->d_lock); spin_lock_nested(&dentry->d_parent->d_lock, DENTRY_D_LOCK_NESTED); } } if (target < dentry) { spin_lock_nested(&target->d_lock, 2); spin_lock_nested(&dentry->d_lock, 3); } else { spin_lock_nested(&dentry->d_lock, 2); spin_lock_nested(&target->d_lock, 3); } } static void dentry_unlock_for_move(struct dentry *dentry, struct dentry *target) { if (target->d_parent != dentry->d_parent) spin_unlock(&dentry->d_parent->d_lock); if (target->d_parent != target) spin_unlock(&target->d_parent->d_lock); spin_unlock(&target->d_lock); spin_unlock(&dentry->d_lock); } /* * When switching names, the actual string doesn't strictly have to * be preserved in the target - because we're dropping the target * anyway. As such, we can just do a simple memcpy() to copy over * the new name before we switch, unless we are going to rehash * it. Note that if we *do* unhash the target, we are not allowed * to rehash it without giving it a new name/hash key - whether * we swap or overwrite the names here, resulting name won't match * the reality in filesystem; it's only there for d_path() purposes. * Note that all of this is happening under rename_lock, so the * any hash lookup seeing it in the middle of manipulations will * be discarded anyway. So we do not care what happens to the hash * key in that case. */ /* * __d_move - move a dentry * @dentry: entry to move * @target: new dentry * @exchange: exchange the two dentries * * Update the dcache to reflect the move of a file name. Negative * dcache entries should not be moved in this way. Caller must hold * rename_lock, the i_mutex of the source and target directories, * and the sb->s_vfs_rename_mutex if they differ. See lock_rename(). */ static void __d_move(struct dentry *dentry, struct dentry *target, bool exchange) { if (!dentry->d_inode) printk(KERN_WARNING "VFS: moving negative dcache entry\n"); BUG_ON(d_ancestor(dentry, target)); BUG_ON(d_ancestor(target, dentry)); dentry_lock_for_move(dentry, target); write_seqcount_begin(&dentry->d_seq); write_seqcount_begin_nested(&target->d_seq, DENTRY_D_LOCK_NESTED); /* __d_drop does write_seqcount_barrier, but they're OK to nest. */ /* * Move the dentry to the target hash queue. Don't bother checking * for the same hash queue because of how unlikely it is. */ __d_drop(dentry); __d_rehash(dentry, d_hash(target->d_parent, target->d_name.hash)); /* * Unhash the target (d_delete() is not usable here). If exchanging * the two dentries, then rehash onto the other's hash queue. */ __d_drop(target); if (exchange) { __d_rehash(target, d_hash(dentry->d_parent, dentry->d_name.hash)); } /* Switch the names.. */ if (exchange) swap_names(dentry, target); else copy_name(dentry, target); /* ... and switch them in the tree */ if (IS_ROOT(dentry)) { /* splicing a tree */ dentry->d_parent = target->d_parent; target->d_parent = target; list_del_init(&target->d_child); list_move(&dentry->d_child, &dentry->d_parent->d_subdirs); } else { /* swapping two dentries */ swap(dentry->d_parent, target->d_parent); list_move(&target->d_child, &target->d_parent->d_subdirs); list_move(&dentry->d_child, &dentry->d_parent->d_subdirs); if (exchange) fsnotify_d_move(target); fsnotify_d_move(dentry); } write_seqcount_end(&target->d_seq); write_seqcount_end(&dentry->d_seq); dentry_unlock_for_move(dentry, target); } /* * d_move - move a dentry * @dentry: entry to move * @target: new dentry * * Update the dcache to reflect the move of a file name. Negative * dcache entries should not be moved in this way. See the locking * requirements for __d_move. */ void d_move(struct dentry *dentry, struct dentry *target) { write_seqlock(&rename_lock); __d_move(dentry, target, false); write_sequnlock(&rename_lock); } EXPORT_SYMBOL(d_move); /* * d_exchange - exchange two dentries * @dentry1: first dentry * @dentry2: second dentry */ void d_exchange(struct dentry *dentry1, struct dentry *dentry2) { write_seqlock(&rename_lock); WARN_ON(!dentry1->d_inode); WARN_ON(!dentry2->d_inode); WARN_ON(IS_ROOT(dentry1)); WARN_ON(IS_ROOT(dentry2)); __d_move(dentry1, dentry2, true); write_sequnlock(&rename_lock); } /** * d_ancestor - search for an ancestor * @p1: ancestor dentry * @p2: child dentry * * Returns the ancestor dentry of p2 which is a child of p1, if p1 is * an ancestor of p2, else NULL. */ struct dentry *d_ancestor(struct dentry *p1, struct dentry *p2) { struct dentry *p; for (p = p2; !IS_ROOT(p); p = p->d_parent) { if (p->d_parent == p1) return p; } return NULL; } /* * This helper attempts to cope with remotely renamed directories * * It assumes that the caller is already holding * dentry->d_parent->d_inode->i_mutex, inode->i_lock and rename_lock * * Note: If ever the locking in lock_rename() changes, then please * remember to update this too... */ static int __d_unalias(struct inode *inode, struct dentry *dentry, struct dentry *alias) { struct mutex *m1 = NULL, *m2 = NULL; int ret = -ESTALE; /* If alias and dentry share a parent, then no extra locks required */ if (alias->d_parent == dentry->d_parent) goto out_unalias; /* See lock_rename() */ if (!mutex_trylock(&dentry->d_sb->s_vfs_rename_mutex)) goto out_err; m1 = &dentry->d_sb->s_vfs_rename_mutex; if (!mutex_trylock(&alias->d_parent->d_inode->i_mutex)) goto out_err; m2 = &alias->d_parent->d_inode->i_mutex; out_unalias: __d_move(alias, dentry, false); ret = 0; out_err: spin_unlock(&inode->i_lock); if (m2) mutex_unlock(m2); if (m1) mutex_unlock(m1); return ret; } /** * d_splice_alias - splice a disconnected dentry into the tree if one exists * @inode: the inode which may have a disconnected dentry * @dentry: a negative dentry which we want to point to the inode. * * If inode is a directory and has an IS_ROOT alias, then d_move that in * place of the given dentry and return it, else simply d_add the inode * to the dentry and return NULL. * * If a non-IS_ROOT directory is found, the filesystem is corrupt, and * we should error out: directories can't have multiple aliases. * * This is needed in the lookup routine of any filesystem that is exportable * (via knfsd) so that we can build dcache paths to directories effectively. * * If a dentry was found and moved, then it is returned. Otherwise NULL * is returned. This matches the expected return value of ->lookup. * * Cluster filesystems may call this function with a negative, hashed dentry. * In that case, we know that the inode will be a regular file, and also this * will only occur during atomic_open. So we need to check for the dentry * being already hashed only in the final case. */ struct dentry *d_splice_alias(struct inode *inode, struct dentry *dentry) { if (IS_ERR(inode)) return ERR_CAST(inode); BUG_ON(!d_unhashed(dentry)); if (!inode) { __d_instantiate(dentry, NULL); goto out; } spin_lock(&inode->i_lock); if (S_ISDIR(inode->i_mode)) { struct dentry *new = __d_find_any_alias(inode); if (unlikely(new)) { write_seqlock(&rename_lock); if (unlikely(d_ancestor(new, dentry))) { write_sequnlock(&rename_lock); spin_unlock(&inode->i_lock); dput(new); new = ERR_PTR(-ELOOP); pr_warn_ratelimited( "VFS: Lookup of '%s' in %s %s" " would have caused loop\n", dentry->d_name.name, inode->i_sb->s_type->name, inode->i_sb->s_id); } else if (!IS_ROOT(new)) { int err = __d_unalias(inode, dentry, new); write_sequnlock(&rename_lock); if (err) { dput(new); new = ERR_PTR(err); } } else { __d_move(new, dentry, false); write_sequnlock(&rename_lock); spin_unlock(&inode->i_lock); security_d_instantiate(new, inode); } iput(inode); return new; } } /* already taking inode->i_lock, so d_add() by hand */ __d_instantiate(dentry, inode); spin_unlock(&inode->i_lock); out: security_d_instantiate(dentry, inode); d_rehash(dentry); return NULL; } EXPORT_SYMBOL(d_splice_alias); static int prepend(char **buffer, int *buflen, const char *str, int namelen) { *buflen -= namelen; if (*buflen < 0) return -ENAMETOOLONG; *buffer -= namelen; memcpy(*buffer, str, namelen); return 0; } /** * prepend_name - prepend a pathname in front of current buffer pointer * @buffer: buffer pointer * @buflen: allocated length of the buffer * @name: name string and length qstr structure * * With RCU path tracing, it may race with d_move(). Use ACCESS_ONCE() to * make sure that either the old or the new name pointer and length are * fetched. However, there may be mismatch between length and pointer. * The length cannot be trusted, we need to copy it byte-by-byte until * the length is reached or a null byte is found. It also prepends "/" at * the beginning of the name. The sequence number check at the caller will * retry it again when a d_move() does happen. So any garbage in the buffer * due to mismatched pointer and length will be discarded. * * Data dependency barrier is needed to make sure that we see that terminating * NUL. Alpha strikes again, film at 11... */ static int prepend_name(char **buffer, int *buflen, struct qstr *name) { const char *dname = ACCESS_ONCE(name->name); u32 dlen = ACCESS_ONCE(name->len); char *p; smp_read_barrier_depends(); *buflen -= dlen + 1; if (*buflen < 0) return -ENAMETOOLONG; p = *buffer -= dlen + 1; *p++ = '/'; while (dlen--) { char c = *dname++; if (!c) break; *p++ = c; } return 0; } /** * prepend_path - Prepend path string to a buffer * @path: the dentry/vfsmount to report * @root: root vfsmnt/dentry * @buffer: pointer to the end of the buffer * @buflen: pointer to buffer length * * The function will first try to write out the pathname without taking any * lock other than the RCU read lock to make sure that dentries won't go away. * It only checks the sequence number of the global rename_lock as any change * in the dentry's d_seq will be preceded by changes in the rename_lock * sequence number. If the sequence number had been changed, it will restart * the whole pathname back-tracing sequence again by taking the rename_lock. * In this case, there is no need to take the RCU read lock as the recursive * parent pointer references will keep the dentry chain alive as long as no * rename operation is performed. */ static int prepend_path(const struct path *path, const struct path *root, char **buffer, int *buflen) { struct dentry *dentry; struct vfsmount *vfsmnt; struct mount *mnt; int error = 0; unsigned seq, m_seq = 0; char *bptr; int blen; rcu_read_lock(); restart_mnt: read_seqbegin_or_lock(&mount_lock, &m_seq); seq = 0; rcu_read_lock(); restart: bptr = *buffer; blen = *buflen; error = 0; dentry = path->dentry; vfsmnt = path->mnt; mnt = real_mount(vfsmnt); read_seqbegin_or_lock(&rename_lock, &seq); while (dentry != root->dentry || vfsmnt != root->mnt) { struct dentry * parent; if (dentry == vfsmnt->mnt_root || IS_ROOT(dentry)) { struct mount *parent = ACCESS_ONCE(mnt->mnt_parent); /* Escaped? */ if (dentry != vfsmnt->mnt_root) { bptr = *buffer; blen = *buflen; error = 3; break; } /* Global root? */ if (mnt != parent) { dentry = ACCESS_ONCE(mnt->mnt_mountpoint); mnt = parent; vfsmnt = &mnt->mnt; continue; } if (!error) error = is_mounted(vfsmnt) ? 1 : 2; break; } parent = dentry->d_parent; prefetch(parent); error = prepend_name(&bptr, &blen, &dentry->d_name); if (error) break; dentry = parent; } if (!(seq & 1)) rcu_read_unlock(); if (need_seqretry(&rename_lock, seq)) { seq = 1; goto restart; } done_seqretry(&rename_lock, seq); if (!(m_seq & 1)) rcu_read_unlock(); if (need_seqretry(&mount_lock, m_seq)) { m_seq = 1; goto restart_mnt; } done_seqretry(&mount_lock, m_seq); if (error >= 0 && bptr == *buffer) { if (--blen < 0) error = -ENAMETOOLONG; else *--bptr = '/'; } *buffer = bptr; *buflen = blen; return error; } /** * __d_path - return the path of a dentry * @path: the dentry/vfsmount to report * @root: root vfsmnt/dentry * @buf: buffer to return value in * @buflen: buffer length * * Convert a dentry into an ASCII path name. * * Returns a pointer into the buffer or an error code if the * path was too long. * * "buflen" should be positive. * * If the path is not reachable from the supplied root, return %NULL. */ char *__d_path(const struct path *path, const struct path *root, char *buf, int buflen) { char *res = buf + buflen; int error; prepend(&res, &buflen, "\0", 1); error = prepend_path(path, root, &res, &buflen); if (error < 0) return ERR_PTR(error); if (error > 0) return NULL; return res; } char *d_absolute_path(const struct path *path, char *buf, int buflen) { struct path root = {}; char *res = buf + buflen; int error; prepend(&res, &buflen, "\0", 1); error = prepend_path(path, &root, &res, &buflen); if (error > 1) error = -EINVAL; if (error < 0) return ERR_PTR(error); return res; } /* * same as __d_path but appends "(deleted)" for unlinked files. */ static int path_with_deleted(const struct path *path, const struct path *root, char **buf, int *buflen) { prepend(buf, buflen, "\0", 1); if (d_unlinked(path->dentry)) { int error = prepend(buf, buflen, " (deleted)", 10); if (error) return error; } return prepend_path(path, root, buf, buflen); } static int prepend_unreachable(char **buffer, int *buflen) { return prepend(buffer, buflen, "(unreachable)", 13); } static void get_fs_root_rcu(struct fs_struct *fs, struct path *root) { unsigned seq; do { seq = read_seqcount_begin(&fs->seq); *root = fs->root; } while (read_seqcount_retry(&fs->seq, seq)); } /** * d_path - return the path of a dentry * @path: path to report * @buf: buffer to return value in * @buflen: buffer length * * Convert a dentry into an ASCII path name. If the entry has been deleted * the string " (deleted)" is appended. Note that this is ambiguous. * * Returns a pointer into the buffer or an error code if the path was * too long. Note: Callers should use the returned pointer, not the passed * in buffer, to use the name! The implementation often starts at an offset * into the buffer, and may leave 0 bytes at the start. * * "buflen" should be positive. */ char *d_path(const struct path *path, char *buf, int buflen) { char *res = buf + buflen; struct path root; int error; /* * We have various synthetic filesystems that never get mounted. On * these filesystems dentries are never used for lookup purposes, and * thus don't need to be hashed. They also don't need a name until a * user wants to identify the object in /proc/pid/fd/. The little hack * below allows us to generate a name for these objects on demand: * * Some pseudo inodes are mountable. When they are mounted * path->dentry == path->mnt->mnt_root. In that case don't call d_dname * and instead have d_path return the mounted path. */ if (path->dentry->d_op && path->dentry->d_op->d_dname && (!IS_ROOT(path->dentry) || path->dentry != path->mnt->mnt_root)) return path->dentry->d_op->d_dname(path->dentry, buf, buflen); rcu_read_lock(); get_fs_root_rcu(current->fs, &root); error = path_with_deleted(path, &root, &res, &buflen); rcu_read_unlock(); if (error < 0) res = ERR_PTR(error); return res; } EXPORT_SYMBOL(d_path); /* * Helper function for dentry_operations.d_dname() members */ char *dynamic_dname(struct dentry *dentry, char *buffer, int buflen, const char *fmt, ...) { va_list args; char temp[64]; int sz; va_start(args, fmt); sz = vsnprintf(temp, sizeof(temp), fmt, args) + 1; va_end(args); if (sz > sizeof(temp) || sz > buflen) return ERR_PTR(-ENAMETOOLONG); buffer += buflen - sz; return memcpy(buffer, temp, sz); } char *simple_dname(struct dentry *dentry, char *buffer, int buflen) { char *end = buffer + buflen; /* these dentries are never renamed, so d_lock is not needed */ if (prepend(&end, &buflen, " (deleted)", 11) || prepend(&end, &buflen, dentry->d_name.name, dentry->d_name.len) || prepend(&end, &buflen, "/", 1)) end = ERR_PTR(-ENAMETOOLONG); return end; } EXPORT_SYMBOL(simple_dname); /* * Write full pathname from the root of the filesystem into the buffer. */ static char *__dentry_path(struct dentry *d, char *buf, int buflen) { struct dentry *dentry; char *end, *retval; int len, seq = 0; int error = 0; if (buflen < 2) goto Elong; rcu_read_lock(); restart: dentry = d; end = buf + buflen; len = buflen; prepend(&end, &len, "\0", 1); /* Get '/' right */ retval = end-1; *retval = '/'; read_seqbegin_or_lock(&rename_lock, &seq); while (!IS_ROOT(dentry)) { struct dentry *parent = dentry->d_parent; prefetch(parent); error = prepend_name(&end, &len, &dentry->d_name); if (error) break; retval = end; dentry = parent; } if (!(seq & 1)) rcu_read_unlock(); if (need_seqretry(&rename_lock, seq)) { seq = 1; goto restart; } done_seqretry(&rename_lock, seq); if (error) goto Elong; return retval; Elong: return ERR_PTR(-ENAMETOOLONG); } char *dentry_path_raw(struct dentry *dentry, char *buf, int buflen) { return __dentry_path(dentry, buf, buflen); } EXPORT_SYMBOL(dentry_path_raw); char *dentry_path(struct dentry *dentry, char *buf, int buflen) { char *p = NULL; char *retval; if (d_unlinked(dentry)) { p = buf + buflen; if (prepend(&p, &buflen, "//deleted", 10) != 0) goto Elong; buflen++; } retval = __dentry_path(dentry, buf, buflen); if (!IS_ERR(retval) && p) *p = '/'; /* restore '/' overriden with '\0' */ return retval; Elong: return ERR_PTR(-ENAMETOOLONG); } static void get_fs_root_and_pwd_rcu(struct fs_struct *fs, struct path *root, struct path *pwd) { unsigned seq; do { seq = read_seqcount_begin(&fs->seq); *root = fs->root; *pwd = fs->pwd; } while (read_seqcount_retry(&fs->seq, seq)); } /* * NOTE! The user-level library version returns a * character pointer. The kernel system call just * returns the length of the buffer filled (which * includes the ending '\0' character), or a negative * error value. So libc would do something like * * char *getcwd(char * buf, size_t size) * { * int retval; * * retval = sys_getcwd(buf, size); * if (retval >= 0) * return buf; * errno = -retval; * return NULL; * } */ SYSCALL_DEFINE2(getcwd, char __user *, buf, unsigned long, size) { int error; struct path pwd, root; char *page = __getname(); if (!page) return -ENOMEM; rcu_read_lock(); get_fs_root_and_pwd_rcu(current->fs, &root, &pwd); error = -ENOENT; if (!d_unlinked(pwd.dentry)) { unsigned long len; char *cwd = page + PATH_MAX; int buflen = PATH_MAX; prepend(&cwd, &buflen, "\0", 1); error = prepend_path(&pwd, &root, &cwd, &buflen); rcu_read_unlock(); if (error < 0) goto out; /* Unreachable from current root */ if (error > 0) { error = prepend_unreachable(&cwd, &buflen); if (error) goto out; } error = -ERANGE; len = PATH_MAX + page - cwd; if (len <= size) { error = len; if (copy_to_user(buf, cwd, len)) error = -EFAULT; } } else { rcu_read_unlock(); } out: __putname(page); return error; } /* * Test whether new_dentry is a subdirectory of old_dentry. * * Trivially implemented using the dcache structure */ /** * is_subdir - is new dentry a subdirectory of old_dentry * @new_dentry: new dentry * @old_dentry: old dentry * * Returns 1 if new_dentry is a subdirectory of the parent (at any depth). * Returns 0 otherwise. * Caller must ensure that "new_dentry" is pinned before calling is_subdir() */ int is_subdir(struct dentry *new_dentry, struct dentry *old_dentry) { int result; unsigned seq; if (new_dentry == old_dentry) return 1; do { /* for restarting inner loop in case of seq retry */ seq = read_seqbegin(&rename_lock); /* * Need rcu_readlock to protect against the d_parent trashing * due to d_move */ rcu_read_lock(); if (d_ancestor(old_dentry, new_dentry)) result = 1; else result = 0; rcu_read_unlock(); } while (read_seqretry(&rename_lock, seq)); return result; } static enum d_walk_ret d_genocide_kill(void *data, struct dentry *dentry) { struct dentry *root = data; if (dentry != root) { if (d_unhashed(dentry) || !dentry->d_inode) return D_WALK_SKIP; if (!(dentry->d_flags & DCACHE_GENOCIDE)) { dentry->d_flags |= DCACHE_GENOCIDE; dentry->d_lockref.count--; } } return D_WALK_CONTINUE; } void d_genocide(struct dentry *parent) { d_walk(parent, parent, d_genocide_kill, NULL); } void d_tmpfile(struct dentry *dentry, struct inode *inode) { inode_dec_link_count(inode); BUG_ON(dentry->d_name.name != dentry->d_iname || !hlist_unhashed(&dentry->d_u.d_alias) || !d_unlinked(dentry)); spin_lock(&dentry->d_parent->d_lock); spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED); dentry->d_name.len = sprintf(dentry->d_iname, "#%llu", (unsigned long long)inode->i_ino); spin_unlock(&dentry->d_lock); spin_unlock(&dentry->d_parent->d_lock); d_instantiate(dentry, inode); } EXPORT_SYMBOL(d_tmpfile); static __initdata unsigned long dhash_entries; static int __init set_dhash_entries(char *str) { if (!str) return 0; dhash_entries = simple_strtoul(str, &str, 0); return 1; } __setup("dhash_entries=", set_dhash_entries); static void __init dcache_init_early(void) { unsigned int loop; /* If hashes are distributed across NUMA nodes, defer * hash allocation until vmalloc space is available. */ if (hashdist) return; dentry_hashtable = alloc_large_system_hash("Dentry cache", sizeof(struct hlist_bl_head), dhash_entries, 13, HASH_EARLY, &d_hash_shift, &d_hash_mask, 0, 0); for (loop = 0; loop < (1U << d_hash_shift); loop++) INIT_HLIST_BL_HEAD(dentry_hashtable + loop); } static void __init dcache_init(void) { unsigned int loop; /* * A constructor could be added for stable state like the lists, * but it is probably not worth it because of the cache nature * of the dcache. */ dentry_cache = KMEM_CACHE(dentry, SLAB_RECLAIM_ACCOUNT|SLAB_PANIC|SLAB_MEM_SPREAD); /* Hash may have been set up in dcache_init_early */ if (!hashdist) return; dentry_hashtable = alloc_large_system_hash("Dentry cache", sizeof(struct hlist_bl_head), dhash_entries, 13, 0, &d_hash_shift, &d_hash_mask, 0, 0); for (loop = 0; loop < (1U << d_hash_shift); loop++) INIT_HLIST_BL_HEAD(dentry_hashtable + loop); } /* SLAB cache for __getname() consumers */ struct kmem_cache *names_cachep __read_mostly; EXPORT_SYMBOL(names_cachep); EXPORT_SYMBOL(d_genocide); void __init vfs_caches_init_early(void) { dcache_init_early(); inode_init_early(); } void __init vfs_caches_init(void) { names_cachep = kmem_cache_create("names_cache", PATH_MAX, 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); dcache_init(); inode_init(); files_init(); files_maxfiles_init(); mnt_init(); bdev_cache_init(); chrdev_init(); }
./CrossVul/dataset_final_sorted/CWE-254/c/good_1548_0
crossvul-cpp_data_bad_3331_1
// imagew-util.c // Part of ImageWorsener, Copyright (c) 2011 by Jason Summers. // For more information, see the readme.txt file. // This file is mainly for portability wrappers, and any code that // may require unusual header files (malloc.h, strsafe.h). #include "imagew-config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef IW_WINDOWS #include <malloc.h> #endif #include <stdarg.h> #include <time.h> #include "imagew-internals.h" #ifdef IW_WINDOWS #include <strsafe.h> #endif void* iwpvt_default_malloc(void *userdata, unsigned int flags, size_t n) { if(flags & IW_MALLOCFLAG_ZEROMEM) { return calloc(n,1); } return malloc(n); } void iwpvt_default_free(void *userdata, void *mem) { free(mem); } IW_IMPL(void*) iw_malloc_ex(struct iw_context *ctx, unsigned int flags, size_t n) { void *mem; if(n>ctx->max_malloc) { if(!(flags&IW_MALLOCFLAG_NOERRORS)) iw_set_error(ctx,"Out of memory"); return NULL; } mem = (*ctx->mallocfn)(ctx->userdata,flags,n); if(!mem) { if(!(flags&IW_MALLOCFLAG_NOERRORS)) iw_set_error(ctx,"Out of memory"); return NULL; } return mem; } IW_IMPL(void*) iw_malloc(struct iw_context *ctx, size_t n) { return iw_malloc_ex(ctx,0,n); } IW_IMPL(void*) iw_mallocz(struct iw_context *ctx, size_t n) { return iw_malloc_ex(ctx,IW_MALLOCFLAG_ZEROMEM,n); } // Allocate a large block of memory, presumably for image data. // Use this if integer overflow is a possibility when multiplying // two factors together. IW_IMPL(void*) iw_malloc_large(struct iw_context *ctx, size_t n1, size_t n2) { if(n1 > ctx->max_malloc/n2) { iw_set_error(ctx,"Image too large to process"); return NULL; } return iw_malloc_ex(ctx,0,n1*n2); } // Emulate realloc using malloc, by always allocating a new memory block. static void* emulated_realloc(struct iw_context *ctx, unsigned int flags, void *oldmem, size_t oldmem_size, size_t newmem_size) { void *newmem; newmem = (*ctx->mallocfn)(ctx->userdata,flags,newmem_size); if(oldmem && newmem) { if(oldmem_size<newmem_size) memcpy(newmem,oldmem,oldmem_size); else memcpy(newmem,oldmem,newmem_size); } if(oldmem) { // Our realloc functions always free the old memory, even on failure. (*ctx->freefn)(ctx->userdata,oldmem); } return newmem; } IW_IMPL(void*) iw_realloc_ex(struct iw_context *ctx, unsigned int flags, void *oldmem, size_t oldmem_size, size_t newmem_size) { void *mem; if(!oldmem) { return iw_malloc_ex(ctx,flags,newmem_size); } if(newmem_size>ctx->max_malloc) { if(!(flags&IW_MALLOCFLAG_NOERRORS)) iw_set_error(ctx,"Out of memory"); return NULL; } mem = emulated_realloc(ctx,flags,oldmem,oldmem_size,newmem_size); if(!mem) { if(!(flags&IW_MALLOCFLAG_NOERRORS)) iw_set_error(ctx,"Out of memory"); return NULL; } return mem; } IW_IMPL(void*) iw_realloc(struct iw_context *ctx, void *oldmem, size_t oldmem_size, size_t newmem_size) { return iw_realloc_ex(ctx,0,oldmem,oldmem_size,newmem_size); } IW_IMPL(void) iw_free(struct iw_context *ctx, void *mem) { if(!mem) return; // Note that this function can be used to free the ctx struct itself, // so we're not allowed to use ctx after freeing the memory. (*ctx->freefn)(ctx->userdata,mem); } IW_IMPL(char*) iw_strdup(struct iw_context *ctx, const char *s) { size_t len; char *s2; if(!s) return NULL; len = strlen(s); s2 = iw_malloc(ctx, len+1); if(!s2) return NULL; memcpy(s2, s, len+1); return s2; } char* iwpvt_strdup_dbl(struct iw_context *ctx, double n) { char buf[100]; iw_snprintf(buf, sizeof(buf), "%.20f", n); return iw_strdup(ctx, buf); } IW_IMPL(void) iw_strlcpy(char *dst, const char *src, size_t dstlen) { size_t n; n = strlen(src); if(n>dstlen-1) n=dstlen-1; memcpy(dst,src,n); dst[n]='\0'; } IW_IMPL(void) iw_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) { #ifdef IW_WINDOWS StringCchVPrintfA(buf,buflen,fmt,ap); #else vsnprintf(buf,buflen,fmt,ap); buf[buflen-1]='\0'; #endif } IW_IMPL(void) iw_snprintf(char *buf, size_t buflen, const char *fmt, ...) { va_list ap; va_start(ap, fmt); iw_vsnprintf(buf,buflen,fmt,ap); va_end(ap); } IW_IMPL(int) iw_stricmp(const char *s1, const char *s2) { #ifdef IW_WINDOWS return _stricmp(s1,s2); #else return strcasecmp(s1,s2); #endif } IW_IMPL(void) iw_zeromem(void *mem, size_t n) { memset(mem,0,n); } //////////////////////////////////////////// // A simple carry-with-multiply pseudorandom number generator (PRNG). struct iw_prng { iw_uint32 multiply; iw_uint32 carry; }; struct iw_prng *iwpvt_prng_create(struct iw_context *ctx) { struct iw_prng *prng; prng = (struct iw_prng*)iw_mallocz(ctx,sizeof(struct iw_prng)); if(!prng) return NULL; return prng; } void iwpvt_prng_destroy(struct iw_context *ctx, struct iw_prng *prng) { if(prng) iw_free(ctx,(void*)prng); } void iwpvt_prng_set_random_seed(struct iw_prng *prng, int s) { prng->multiply = ((iw_uint32)0x03333333) + s; prng->carry = ((iw_uint32)0x05555555) + s; } iw_uint32 iwpvt_prng_rand(struct iw_prng *prng) { iw_uint64 x; x = ((iw_uint64)0xfff0bf23) * prng->multiply + prng->carry; prng->carry = (iw_uint32)(x>>32); prng->multiply = 0xffffffff - (0xffffffff & x); return prng->multiply; } //////////////////////////////////////////// int iwpvt_util_randomize(struct iw_prng *prng) { int s; s = (int)time(NULL); iwpvt_prng_set_random_seed(prng, s); return s; } IW_IMPL(int) iw_file_to_memory(struct iw_context *ctx, struct iw_iodescr *iodescr, void **pmem, iw_int64 *psize) { int ret; size_t bytesread; *pmem=NULL; *psize=0; if(!iodescr->getfilesize_fn) return 0; ret = (*iodescr->getfilesize_fn)(ctx,iodescr,psize); // TODO: Don't require a getfilesize function. if(!ret) return 0; *pmem = iw_malloc(ctx,(size_t)*psize); ret = (*iodescr->read_fn)(ctx,iodescr,*pmem,(size_t)*psize,&bytesread); if(!ret) return 0; if((iw_int64)bytesread != *psize) return 0; return 1; } struct iw_utf8cvt_struct { char *dst; int dstlen; int dp; }; static void utf8cvt_emitoctet(struct iw_utf8cvt_struct *s, unsigned char c) { if(s->dp > s->dstlen-2) return; s->dst[s->dp] = (char)c; s->dp++; } // Map Unicode characters to ASCII substitutions. // Not used for codepoints <=127. static void utf8cvt_emitunichar(struct iw_utf8cvt_struct *s, unsigned int c) { int i; int pos; struct charmap_struct { unsigned int code; const char *s; }; static const struct charmap_struct chartable[] = { {0, "?" }, // Default character {0x00a9, "(c)" }, {0x00d7, "x" }, // multiplication sign {0x2013, "-" }, // en dash {0x2018, "'" }, // left single quote {0x2019, "'" }, // right single quote {0x201c, "\"" }, // left double quote {0x201d, "\"" }, // right double quote {0x2192, "->" }, {0xfeff, "" }, // zero-width no-break space {0, NULL} }; // Try to find the codepoint in the table. pos = 0; for(i=1;chartable[i].code;i++) { if(c==chartable[i].code) { pos=i; break; } } // Write out the ASCII translation of this code. for(i=0;chartable[pos].s[i];i++) { utf8cvt_emitoctet(s,(unsigned char)chartable[pos].s[i]); } } // This UTF-8 converter is intended to be safe to use with malformed data, but // it may not handle it in the best possible way. It mostly just skips over it. IW_IMPL(void) iw_utf8_to_ascii(const char *src, char *dst, int dstlen) { struct iw_utf8cvt_struct s; int sp; unsigned char c; unsigned int pending_char; int bytes_expected; s.dst = dst; s.dstlen = dstlen; s.dp = 0; pending_char=0; bytes_expected=0; for(sp=0;src[sp];sp++) { c = (unsigned char)src[sp]; if(c<128) { // Only byte of a 1-byte sequence utf8cvt_emitoctet(&s,c); bytes_expected=0; } else if(c<0xc0) { // Continuation byte if(bytes_expected>0) { pending_char = (pending_char<<6)|(c&0x3f); bytes_expected--; if(bytes_expected<1) { utf8cvt_emitunichar(&s,pending_char); } } } else if(c<0xe0) { // 1st byte of a 2-byte sequence pending_char = c&0x1f; bytes_expected=1; } else if(c<0xf0) { // 1st byte of a 3-byte sequence pending_char = c&0x0f; bytes_expected=2; } else if(c<0xf8) { // 1st byte of a 4-byte sequence pending_char = c&0x07; bytes_expected=3; } } dst[s.dp] = '\0'; } IW_IMPL(int) iw_get_host_endianness(void) { iw_byte b; unsigned int x = 1; memcpy(&b,&x,1); return b==0 ? IW_ENDIAN_BIG : IW_ENDIAN_LITTLE; } IW_IMPL(void) iw_set_ui16le(iw_byte *b, unsigned int n) { b[0] = n&0xff; b[1] = (n>>8)&0xff; } IW_IMPL(void) iw_set_ui32le(iw_byte *b, unsigned int n) { b[0] = n&0xff; b[1] = (n>>8)&0xff; b[2] = (n>>16)&0xff; b[3] = (n>>24)&0xff; } IW_IMPL(void) iw_set_ui16be(iw_byte *b, unsigned int n) { b[0] = (n>>8)&0xff; b[1] = n&0xff; } IW_IMPL(void) iw_set_ui32be(iw_byte *b, unsigned int n) { b[0] = (n>>24)&0xff; b[1] = (n>>16)&0xff; b[2] = (n>>8)&0xff; b[3] = n&0xff; } IW_IMPL(unsigned int) iw_get_ui16le(const iw_byte *b) { return b[0] | (b[1]<<8); } IW_IMPL(unsigned int) iw_get_ui32le(const iw_byte *b) { return b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24); } IW_IMPL(int) iw_get_i32le(const iw_byte *b) { return (iw_int32)(iw_uint32)(b[0] | (b[1]<<8) | (b[2]<<16) | (b[3]<<24)); } IW_IMPL(unsigned int) iw_get_ui16be(const iw_byte *b) { return (b[0]<<8) | b[1]; } IW_IMPL(unsigned int) iw_get_ui32be(const iw_byte *b) { return (b[0]<<24) | (b[1]<<16) | (b[2]<<8) | b[3]; } // Accepts a flag indicating the endianness. IW_IMPL(unsigned int) iw_get_ui16_e(const iw_byte *b, int endian) { if(endian==IW_ENDIAN_LITTLE) return iw_get_ui16le(b); return iw_get_ui16be(b); } IW_IMPL(unsigned int) iw_get_ui32_e(const iw_byte *b, int endian) { if(endian==IW_ENDIAN_LITTLE) return iw_get_ui32le(b); return iw_get_ui32be(b); } IW_IMPL(int) iw_max_color_to_bitdepth(unsigned int mc) { unsigned int bd; for(bd=1;bd<=15;bd++) { if(mc < (1U<<bd)) return bd; } return 16; } IW_IMPL(int) iw_detect_fmt_from_filename(const char *fn) { char *s; int i; struct fmttable_struct { const char *ext; int fmt; }; static const struct fmttable_struct fmttable[] = { {"png", IW_FORMAT_PNG}, {"jpg", IW_FORMAT_JPEG}, {"jpeg", IW_FORMAT_JPEG}, {"bmp", IW_FORMAT_BMP}, {"tif", IW_FORMAT_TIFF}, {"tiff", IW_FORMAT_TIFF}, {"miff", IW_FORMAT_MIFF}, {"webp", IW_FORMAT_WEBP}, {"gif", IW_FORMAT_GIF}, {"pnm", IW_FORMAT_PNM}, {"pbm", IW_FORMAT_PBM}, {"pgm", IW_FORMAT_PGM}, {"ppm", IW_FORMAT_PPM}, {"pam", IW_FORMAT_PAM}, {NULL, 0} }; s=strrchr(fn,'.'); if(!s) return IW_FORMAT_UNKNOWN; s++; for(i=0;fmttable[i].ext;i++) { if(!iw_stricmp(s,fmttable[i].ext)) return fmttable[i].fmt; } return IW_FORMAT_UNKNOWN; } IW_IMPL(const char*) iw_get_fmt_name(int fmt) { static const char *n; n=NULL; switch(fmt) { case IW_FORMAT_PNG: n="PNG"; break; case IW_FORMAT_JPEG: n="JPEG"; break; case IW_FORMAT_BMP: n="BMP"; break; case IW_FORMAT_TIFF: n="TIFF"; break; case IW_FORMAT_MIFF: n="MIFF"; break; case IW_FORMAT_WEBP: n="WebP"; break; case IW_FORMAT_GIF: n="GIF"; break; case IW_FORMAT_PNM: n="PNM"; break; case IW_FORMAT_PBM: n="PBM"; break; case IW_FORMAT_PGM: n="PGM"; break; case IW_FORMAT_PPM: n="PPM"; break; case IW_FORMAT_PAM: n="PAM"; break; } return n; } IW_IMPL(int) iw_detect_fmt_of_file(const iw_byte *buf, size_t n) { int fmt = IW_FORMAT_UNKNOWN; if(n<2) return fmt; if(buf[0]==0x89 && buf[1]==0x50) { fmt=IW_FORMAT_PNG; } else if(n>=3 && buf[0]=='G' && buf[1]=='I' && buf[2]=='F') { fmt=IW_FORMAT_GIF; } else if(buf[0]==0xff && buf[1]==0xd8) { fmt=IW_FORMAT_JPEG; } else if(buf[0]=='B' && buf[1]=='M') { fmt=IW_FORMAT_BMP; } else if(buf[0]=='B' && buf[1]=='A') { fmt=IW_FORMAT_BMP; } else if((buf[0]==0x49 || buf[0]==0x4d) && buf[1]==buf[0]) { fmt=IW_FORMAT_TIFF; } else if(buf[0]==0x69 && buf[1]==0x64) { fmt=IW_FORMAT_MIFF; } else if(n>=12 && buf[0]==0x52 && buf[1]==0x49 && buf[2]==0x46 && buf[3]==0x46 && buf[8]==0x57 && buf[9]==0x45 && buf[10]==0x42 && buf[11]==0x50) { fmt=IW_FORMAT_WEBP; } else if(buf[0]=='P' && (buf[1]>='1' && buf[1]<='6')) { return IW_FORMAT_PNM; } else if(buf[0]=='P' && (buf[1]=='7' && buf[2]==0x0a)) { return IW_FORMAT_PAM; } return fmt; } IW_IMPL(unsigned int) iw_get_profile_by_fmt(int fmt) { unsigned int p; switch(fmt) { case IW_FORMAT_PNG: p = IW_PROFILE_TRANSPARENCY | IW_PROFILE_GRAYSCALE | IW_PROFILE_PALETTETRNS | IW_PROFILE_GRAY1 | IW_PROFILE_GRAY2 | IW_PROFILE_GRAY4 | IW_PROFILE_16BPS | IW_PROFILE_BINARYTRNS | IW_PROFILE_PAL1 | IW_PROFILE_PAL2 | IW_PROFILE_PAL4 | IW_PROFILE_PAL8 | IW_PROFILE_REDUCEDBITDEPTHS | IW_PROFILE_PNG_BKGD; break; case IW_FORMAT_BMP: p = IW_PROFILE_PAL1 | IW_PROFILE_PAL4 | IW_PROFILE_PAL8 | IW_PROFILE_REDUCEDBITDEPTHS; break; case IW_FORMAT_JPEG: p = IW_PROFILE_GRAYSCALE; break; case IW_FORMAT_TIFF: p = IW_PROFILE_TRANSPARENCY | IW_PROFILE_GRAYSCALE | IW_PROFILE_GRAY1 | IW_PROFILE_GRAY4 | IW_PROFILE_16BPS | IW_PROFILE_PAL4 | IW_PROFILE_PAL8; break; case IW_FORMAT_MIFF: p = IW_PROFILE_TRANSPARENCY | IW_PROFILE_GRAYSCALE | IW_PROFILE_ALWAYSLINEAR | IW_PROFILE_HDRI | IW_PROFILE_RGB16_BKGD; break; case IW_FORMAT_WEBP: p = 0; #if IW_WEBP_SUPPORT_TRANSPARENCY p |= IW_PROFILE_TRANSPARENCY; #endif break; case IW_FORMAT_PAM: p = IW_PROFILE_16BPS | IW_PROFILE_REDUCEDBITDEPTHS | IW_PROFILE_GRAYSCALE | IW_PROFILE_GRAY1 | IW_PROFILE_TRANSPARENCY; break; case IW_FORMAT_PNM: p = IW_PROFILE_16BPS | IW_PROFILE_REDUCEDBITDEPTHS | IW_PROFILE_GRAYSCALE | IW_PROFILE_GRAY1; break; case IW_FORMAT_PPM: p = IW_PROFILE_16BPS | IW_PROFILE_REDUCEDBITDEPTHS; break; case IW_FORMAT_PGM: // No reason to set GRAY[124], because we can't optimize for them. Each pixel // uses a minimum of one byte. p = IW_PROFILE_16BPS | IW_PROFILE_REDUCEDBITDEPTHS | IW_PROFILE_GRAYSCALE; break; case IW_FORMAT_PBM: p = IW_PROFILE_GRAY1; break; default: p = 0; } return p; } // The imagew-allfmts.c file is probably a more logical place for the // iw_is_*_fmt_supported() functions, but putting them there could create // unnecessary dependencies on third-party libraries. IW_IMPL(int) iw_is_input_fmt_supported(int fmt) { switch(fmt) { #if IW_SUPPORT_PNG == 1 case IW_FORMAT_PNG: #endif #if IW_SUPPORT_JPEG == 1 case IW_FORMAT_JPEG: #endif #if IW_SUPPORT_WEBP == 1 case IW_FORMAT_WEBP: #endif case IW_FORMAT_MIFF: case IW_FORMAT_GIF: case IW_FORMAT_BMP: case IW_FORMAT_PNM: case IW_FORMAT_PAM: return 1; } return 0; } IW_IMPL(int) iw_is_output_fmt_supported(int fmt) { switch(fmt) { #if IW_SUPPORT_PNG == 1 case IW_FORMAT_PNG: #endif #if IW_SUPPORT_JPEG == 1 case IW_FORMAT_JPEG: #endif #if IW_SUPPORT_WEBP == 1 case IW_FORMAT_WEBP: #endif case IW_FORMAT_BMP: case IW_FORMAT_TIFF: case IW_FORMAT_MIFF: case IW_FORMAT_PNM: case IW_FORMAT_PPM: case IW_FORMAT_PGM: case IW_FORMAT_PBM: case IW_FORMAT_PAM: return 1; } return 0; } // Find where a number ends (at a comma, or the end of string), // and record if it contained a slash. static int iw_get_number_len(const char *s, int *pslash_pos) { int i; for(i=0;s[i];i++) { if(s[i]=='/') { *pslash_pos = i; } if(s[i]!=',') continue; return i; } return i; } // Returns 0 if no valid number found. static int iw_parse_number_internal(const char *s, double *presult, int *pcharsread) { int len; int slash_pos = -1; *presult = 0.0; *pcharsread = 0; len = iw_get_number_len(s,&slash_pos); if(len<1) return 0; *pcharsread = len; if(slash_pos>=0) { // a rational number double numer, denom; numer = atof(s); denom = atof(s+slash_pos+1); if(denom==0.0) *presult = 0.0; else *presult = numer/denom; } else { *presult = atof(s); } return 1; } // Returns number of numbers parsed. // If there are not enough numbers, leaves some contents of 'results' unchanged. IW_IMPL(int) iw_parse_number_list(const char *s, int max_numbers, // max number of numbers to parse double *results) // array of doubles to hold the results { int n; int charsread; int curpos=0; int ret; int numresults = 0; for(n=0;n<max_numbers;n++) { ret=iw_parse_number_internal(&s[curpos], &results[n], &charsread); if(!ret) break; numresults++; curpos+=charsread; if(s[curpos]==',') { curpos++; } else { break; } } return numresults; } IW_IMPL(double) iw_parse_number(const char *s) { double result; int charsread; iw_parse_number_internal(s, &result, &charsread); return result; } IW_IMPL(int) iw_round_to_int(double x) { if(x<0.0) return -(int)(0.5-x); return (int)(0.5+x); } IW_IMPL(int) iw_parse_int(const char *s) { double result; int charsread; iw_parse_number_internal(s, &result, &charsread); return iw_round_to_int(result); }
./CrossVul/dataset_final_sorted/CWE-682/c/bad_3331_1
crossvul-cpp_data_good_3331_1
// imagew-util.c // Part of ImageWorsener, Copyright (c) 2011 by Jason Summers. // For more information, see the readme.txt file. // This file is mainly for portability wrappers, and any code that // may require unusual header files (malloc.h, strsafe.h). #include "imagew-config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef IW_WINDOWS #include <malloc.h> #endif #include <stdarg.h> #include <time.h> #include "imagew-internals.h" #ifdef IW_WINDOWS #include <strsafe.h> #endif void* iwpvt_default_malloc(void *userdata, unsigned int flags, size_t n) { if(flags & IW_MALLOCFLAG_ZEROMEM) { return calloc(n,1); } return malloc(n); } void iwpvt_default_free(void *userdata, void *mem) { free(mem); } IW_IMPL(void*) iw_malloc_ex(struct iw_context *ctx, unsigned int flags, size_t n) { void *mem; if(n>ctx->max_malloc) { if(!(flags&IW_MALLOCFLAG_NOERRORS)) iw_set_error(ctx,"Out of memory"); return NULL; } mem = (*ctx->mallocfn)(ctx->userdata,flags,n); if(!mem) { if(!(flags&IW_MALLOCFLAG_NOERRORS)) iw_set_error(ctx,"Out of memory"); return NULL; } return mem; } IW_IMPL(void*) iw_malloc(struct iw_context *ctx, size_t n) { return iw_malloc_ex(ctx,0,n); } IW_IMPL(void*) iw_mallocz(struct iw_context *ctx, size_t n) { return iw_malloc_ex(ctx,IW_MALLOCFLAG_ZEROMEM,n); } // Allocate a large block of memory, presumably for image data. // Use this if integer overflow is a possibility when multiplying // two factors together. IW_IMPL(void*) iw_malloc_large(struct iw_context *ctx, size_t n1, size_t n2) { if(n1 > ctx->max_malloc/n2) { iw_set_error(ctx,"Image too large to process"); return NULL; } return iw_malloc_ex(ctx,0,n1*n2); } // Emulate realloc using malloc, by always allocating a new memory block. static void* emulated_realloc(struct iw_context *ctx, unsigned int flags, void *oldmem, size_t oldmem_size, size_t newmem_size) { void *newmem; newmem = (*ctx->mallocfn)(ctx->userdata,flags,newmem_size); if(oldmem && newmem) { if(oldmem_size<newmem_size) memcpy(newmem,oldmem,oldmem_size); else memcpy(newmem,oldmem,newmem_size); } if(oldmem) { // Our realloc functions always free the old memory, even on failure. (*ctx->freefn)(ctx->userdata,oldmem); } return newmem; } IW_IMPL(void*) iw_realloc_ex(struct iw_context *ctx, unsigned int flags, void *oldmem, size_t oldmem_size, size_t newmem_size) { void *mem; if(!oldmem) { return iw_malloc_ex(ctx,flags,newmem_size); } if(newmem_size>ctx->max_malloc) { if(!(flags&IW_MALLOCFLAG_NOERRORS)) iw_set_error(ctx,"Out of memory"); return NULL; } mem = emulated_realloc(ctx,flags,oldmem,oldmem_size,newmem_size); if(!mem) { if(!(flags&IW_MALLOCFLAG_NOERRORS)) iw_set_error(ctx,"Out of memory"); return NULL; } return mem; } IW_IMPL(void*) iw_realloc(struct iw_context *ctx, void *oldmem, size_t oldmem_size, size_t newmem_size) { return iw_realloc_ex(ctx,0,oldmem,oldmem_size,newmem_size); } IW_IMPL(void) iw_free(struct iw_context *ctx, void *mem) { if(!mem) return; // Note that this function can be used to free the ctx struct itself, // so we're not allowed to use ctx after freeing the memory. (*ctx->freefn)(ctx->userdata,mem); } IW_IMPL(char*) iw_strdup(struct iw_context *ctx, const char *s) { size_t len; char *s2; if(!s) return NULL; len = strlen(s); s2 = iw_malloc(ctx, len+1); if(!s2) return NULL; memcpy(s2, s, len+1); return s2; } char* iwpvt_strdup_dbl(struct iw_context *ctx, double n) { char buf[100]; iw_snprintf(buf, sizeof(buf), "%.20f", n); return iw_strdup(ctx, buf); } IW_IMPL(void) iw_strlcpy(char *dst, const char *src, size_t dstlen) { size_t n; n = strlen(src); if(n>dstlen-1) n=dstlen-1; memcpy(dst,src,n); dst[n]='\0'; } IW_IMPL(void) iw_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) { #ifdef IW_WINDOWS StringCchVPrintfA(buf,buflen,fmt,ap); #else vsnprintf(buf,buflen,fmt,ap); buf[buflen-1]='\0'; #endif } IW_IMPL(void) iw_snprintf(char *buf, size_t buflen, const char *fmt, ...) { va_list ap; va_start(ap, fmt); iw_vsnprintf(buf,buflen,fmt,ap); va_end(ap); } IW_IMPL(int) iw_stricmp(const char *s1, const char *s2) { #ifdef IW_WINDOWS return _stricmp(s1,s2); #else return strcasecmp(s1,s2); #endif } IW_IMPL(void) iw_zeromem(void *mem, size_t n) { memset(mem,0,n); } //////////////////////////////////////////// // A simple carry-with-multiply pseudorandom number generator (PRNG). struct iw_prng { iw_uint32 multiply; iw_uint32 carry; }; struct iw_prng *iwpvt_prng_create(struct iw_context *ctx) { struct iw_prng *prng; prng = (struct iw_prng*)iw_mallocz(ctx,sizeof(struct iw_prng)); if(!prng) return NULL; return prng; } void iwpvt_prng_destroy(struct iw_context *ctx, struct iw_prng *prng) { if(prng) iw_free(ctx,(void*)prng); } void iwpvt_prng_set_random_seed(struct iw_prng *prng, int s) { prng->multiply = ((iw_uint32)0x03333333) + s; prng->carry = ((iw_uint32)0x05555555) + s; } iw_uint32 iwpvt_prng_rand(struct iw_prng *prng) { iw_uint64 x; x = ((iw_uint64)0xfff0bf23) * prng->multiply + prng->carry; prng->carry = (iw_uint32)(x>>32); prng->multiply = 0xffffffff - (0xffffffff & x); return prng->multiply; } //////////////////////////////////////////// int iwpvt_util_randomize(struct iw_prng *prng) { int s; s = (int)time(NULL); iwpvt_prng_set_random_seed(prng, s); return s; } IW_IMPL(int) iw_file_to_memory(struct iw_context *ctx, struct iw_iodescr *iodescr, void **pmem, iw_int64 *psize) { int ret; size_t bytesread; *pmem=NULL; *psize=0; if(!iodescr->getfilesize_fn) return 0; ret = (*iodescr->getfilesize_fn)(ctx,iodescr,psize); // TODO: Don't require a getfilesize function. if(!ret) return 0; *pmem = iw_malloc(ctx,(size_t)*psize); ret = (*iodescr->read_fn)(ctx,iodescr,*pmem,(size_t)*psize,&bytesread); if(!ret) return 0; if((iw_int64)bytesread != *psize) return 0; return 1; } struct iw_utf8cvt_struct { char *dst; int dstlen; int dp; }; static void utf8cvt_emitoctet(struct iw_utf8cvt_struct *s, unsigned char c) { if(s->dp > s->dstlen-2) return; s->dst[s->dp] = (char)c; s->dp++; } // Map Unicode characters to ASCII substitutions. // Not used for codepoints <=127. static void utf8cvt_emitunichar(struct iw_utf8cvt_struct *s, unsigned int c) { int i; int pos; struct charmap_struct { unsigned int code; const char *s; }; static const struct charmap_struct chartable[] = { {0, "?" }, // Default character {0x00a9, "(c)" }, {0x00d7, "x" }, // multiplication sign {0x2013, "-" }, // en dash {0x2018, "'" }, // left single quote {0x2019, "'" }, // right single quote {0x201c, "\"" }, // left double quote {0x201d, "\"" }, // right double quote {0x2192, "->" }, {0xfeff, "" }, // zero-width no-break space {0, NULL} }; // Try to find the codepoint in the table. pos = 0; for(i=1;chartable[i].code;i++) { if(c==chartable[i].code) { pos=i; break; } } // Write out the ASCII translation of this code. for(i=0;chartable[pos].s[i];i++) { utf8cvt_emitoctet(s,(unsigned char)chartable[pos].s[i]); } } // This UTF-8 converter is intended to be safe to use with malformed data, but // it may not handle it in the best possible way. It mostly just skips over it. IW_IMPL(void) iw_utf8_to_ascii(const char *src, char *dst, int dstlen) { struct iw_utf8cvt_struct s; int sp; unsigned char c; unsigned int pending_char; int bytes_expected; s.dst = dst; s.dstlen = dstlen; s.dp = 0; pending_char=0; bytes_expected=0; for(sp=0;src[sp];sp++) { c = (unsigned char)src[sp]; if(c<128) { // Only byte of a 1-byte sequence utf8cvt_emitoctet(&s,c); bytes_expected=0; } else if(c<0xc0) { // Continuation byte if(bytes_expected>0) { pending_char = (pending_char<<6)|(c&0x3f); bytes_expected--; if(bytes_expected<1) { utf8cvt_emitunichar(&s,pending_char); } } } else if(c<0xe0) { // 1st byte of a 2-byte sequence pending_char = c&0x1f; bytes_expected=1; } else if(c<0xf0) { // 1st byte of a 3-byte sequence pending_char = c&0x0f; bytes_expected=2; } else if(c<0xf8) { // 1st byte of a 4-byte sequence pending_char = c&0x07; bytes_expected=3; } } dst[s.dp] = '\0'; } IW_IMPL(int) iw_get_host_endianness(void) { iw_byte b; unsigned int x = 1; memcpy(&b,&x,1); return b==0 ? IW_ENDIAN_BIG : IW_ENDIAN_LITTLE; } IW_IMPL(void) iw_set_ui16le(iw_byte *b, unsigned int n) { b[0] = n&0xff; b[1] = (n>>8)&0xff; } IW_IMPL(void) iw_set_ui32le(iw_byte *b, unsigned int n) { b[0] = n&0xff; b[1] = (n>>8)&0xff; b[2] = (n>>16)&0xff; b[3] = (n>>24)&0xff; } IW_IMPL(void) iw_set_ui16be(iw_byte *b, unsigned int n) { b[0] = (n>>8)&0xff; b[1] = n&0xff; } IW_IMPL(void) iw_set_ui32be(iw_byte *b, unsigned int n) { b[0] = (n>>24)&0xff; b[1] = (n>>16)&0xff; b[2] = (n>>8)&0xff; b[3] = n&0xff; } IW_IMPL(unsigned int) iw_get_ui16le(const iw_byte *b) { return (unsigned int)b[0] | ((unsigned int)b[1]<<8); } IW_IMPL(unsigned int) iw_get_ui32le(const iw_byte *b) { return (unsigned int)b[0] | ((unsigned int)b[1]<<8) | ((unsigned int)b[2]<<16) | ((unsigned int)b[3]<<24); } IW_IMPL(int) iw_get_i32le(const iw_byte *b) { return (iw_int32)(iw_uint32)((unsigned int)b[0] | ((unsigned int)b[1]<<8) | ((unsigned int)b[2]<<16) | ((unsigned int)b[3]<<24)); } IW_IMPL(unsigned int) iw_get_ui16be(const iw_byte *b) { return ((unsigned int)b[0]<<8) | (unsigned int)b[1]; } IW_IMPL(unsigned int) iw_get_ui32be(const iw_byte *b) { return ((unsigned int)b[0]<<24) | ((unsigned int)b[1]<<16) | ((unsigned int)b[2]<<8) | (unsigned int)b[3]; } // Accepts a flag indicating the endianness. IW_IMPL(unsigned int) iw_get_ui16_e(const iw_byte *b, int endian) { if(endian==IW_ENDIAN_LITTLE) return iw_get_ui16le(b); return iw_get_ui16be(b); } IW_IMPL(unsigned int) iw_get_ui32_e(const iw_byte *b, int endian) { if(endian==IW_ENDIAN_LITTLE) return iw_get_ui32le(b); return iw_get_ui32be(b); } IW_IMPL(int) iw_max_color_to_bitdepth(unsigned int mc) { unsigned int bd; for(bd=1;bd<=15;bd++) { if(mc < (1U<<bd)) return bd; } return 16; } IW_IMPL(int) iw_detect_fmt_from_filename(const char *fn) { char *s; int i; struct fmttable_struct { const char *ext; int fmt; }; static const struct fmttable_struct fmttable[] = { {"png", IW_FORMAT_PNG}, {"jpg", IW_FORMAT_JPEG}, {"jpeg", IW_FORMAT_JPEG}, {"bmp", IW_FORMAT_BMP}, {"tif", IW_FORMAT_TIFF}, {"tiff", IW_FORMAT_TIFF}, {"miff", IW_FORMAT_MIFF}, {"webp", IW_FORMAT_WEBP}, {"gif", IW_FORMAT_GIF}, {"pnm", IW_FORMAT_PNM}, {"pbm", IW_FORMAT_PBM}, {"pgm", IW_FORMAT_PGM}, {"ppm", IW_FORMAT_PPM}, {"pam", IW_FORMAT_PAM}, {NULL, 0} }; s=strrchr(fn,'.'); if(!s) return IW_FORMAT_UNKNOWN; s++; for(i=0;fmttable[i].ext;i++) { if(!iw_stricmp(s,fmttable[i].ext)) return fmttable[i].fmt; } return IW_FORMAT_UNKNOWN; } IW_IMPL(const char*) iw_get_fmt_name(int fmt) { static const char *n; n=NULL; switch(fmt) { case IW_FORMAT_PNG: n="PNG"; break; case IW_FORMAT_JPEG: n="JPEG"; break; case IW_FORMAT_BMP: n="BMP"; break; case IW_FORMAT_TIFF: n="TIFF"; break; case IW_FORMAT_MIFF: n="MIFF"; break; case IW_FORMAT_WEBP: n="WebP"; break; case IW_FORMAT_GIF: n="GIF"; break; case IW_FORMAT_PNM: n="PNM"; break; case IW_FORMAT_PBM: n="PBM"; break; case IW_FORMAT_PGM: n="PGM"; break; case IW_FORMAT_PPM: n="PPM"; break; case IW_FORMAT_PAM: n="PAM"; break; } return n; } IW_IMPL(int) iw_detect_fmt_of_file(const iw_byte *buf, size_t n) { int fmt = IW_FORMAT_UNKNOWN; if(n<2) return fmt; if(buf[0]==0x89 && buf[1]==0x50) { fmt=IW_FORMAT_PNG; } else if(n>=3 && buf[0]=='G' && buf[1]=='I' && buf[2]=='F') { fmt=IW_FORMAT_GIF; } else if(buf[0]==0xff && buf[1]==0xd8) { fmt=IW_FORMAT_JPEG; } else if(buf[0]=='B' && buf[1]=='M') { fmt=IW_FORMAT_BMP; } else if(buf[0]=='B' && buf[1]=='A') { fmt=IW_FORMAT_BMP; } else if((buf[0]==0x49 || buf[0]==0x4d) && buf[1]==buf[0]) { fmt=IW_FORMAT_TIFF; } else if(buf[0]==0x69 && buf[1]==0x64) { fmt=IW_FORMAT_MIFF; } else if(n>=12 && buf[0]==0x52 && buf[1]==0x49 && buf[2]==0x46 && buf[3]==0x46 && buf[8]==0x57 && buf[9]==0x45 && buf[10]==0x42 && buf[11]==0x50) { fmt=IW_FORMAT_WEBP; } else if(buf[0]=='P' && (buf[1]>='1' && buf[1]<='6')) { return IW_FORMAT_PNM; } else if(buf[0]=='P' && (buf[1]=='7' && buf[2]==0x0a)) { return IW_FORMAT_PAM; } return fmt; } IW_IMPL(unsigned int) iw_get_profile_by_fmt(int fmt) { unsigned int p; switch(fmt) { case IW_FORMAT_PNG: p = IW_PROFILE_TRANSPARENCY | IW_PROFILE_GRAYSCALE | IW_PROFILE_PALETTETRNS | IW_PROFILE_GRAY1 | IW_PROFILE_GRAY2 | IW_PROFILE_GRAY4 | IW_PROFILE_16BPS | IW_PROFILE_BINARYTRNS | IW_PROFILE_PAL1 | IW_PROFILE_PAL2 | IW_PROFILE_PAL4 | IW_PROFILE_PAL8 | IW_PROFILE_REDUCEDBITDEPTHS | IW_PROFILE_PNG_BKGD; break; case IW_FORMAT_BMP: p = IW_PROFILE_PAL1 | IW_PROFILE_PAL4 | IW_PROFILE_PAL8 | IW_PROFILE_REDUCEDBITDEPTHS; break; case IW_FORMAT_JPEG: p = IW_PROFILE_GRAYSCALE; break; case IW_FORMAT_TIFF: p = IW_PROFILE_TRANSPARENCY | IW_PROFILE_GRAYSCALE | IW_PROFILE_GRAY1 | IW_PROFILE_GRAY4 | IW_PROFILE_16BPS | IW_PROFILE_PAL4 | IW_PROFILE_PAL8; break; case IW_FORMAT_MIFF: p = IW_PROFILE_TRANSPARENCY | IW_PROFILE_GRAYSCALE | IW_PROFILE_ALWAYSLINEAR | IW_PROFILE_HDRI | IW_PROFILE_RGB16_BKGD; break; case IW_FORMAT_WEBP: p = 0; #if IW_WEBP_SUPPORT_TRANSPARENCY p |= IW_PROFILE_TRANSPARENCY; #endif break; case IW_FORMAT_PAM: p = IW_PROFILE_16BPS | IW_PROFILE_REDUCEDBITDEPTHS | IW_PROFILE_GRAYSCALE | IW_PROFILE_GRAY1 | IW_PROFILE_TRANSPARENCY; break; case IW_FORMAT_PNM: p = IW_PROFILE_16BPS | IW_PROFILE_REDUCEDBITDEPTHS | IW_PROFILE_GRAYSCALE | IW_PROFILE_GRAY1; break; case IW_FORMAT_PPM: p = IW_PROFILE_16BPS | IW_PROFILE_REDUCEDBITDEPTHS; break; case IW_FORMAT_PGM: // No reason to set GRAY[124], because we can't optimize for them. Each pixel // uses a minimum of one byte. p = IW_PROFILE_16BPS | IW_PROFILE_REDUCEDBITDEPTHS | IW_PROFILE_GRAYSCALE; break; case IW_FORMAT_PBM: p = IW_PROFILE_GRAY1; break; default: p = 0; } return p; } // The imagew-allfmts.c file is probably a more logical place for the // iw_is_*_fmt_supported() functions, but putting them there could create // unnecessary dependencies on third-party libraries. IW_IMPL(int) iw_is_input_fmt_supported(int fmt) { switch(fmt) { #if IW_SUPPORT_PNG == 1 case IW_FORMAT_PNG: #endif #if IW_SUPPORT_JPEG == 1 case IW_FORMAT_JPEG: #endif #if IW_SUPPORT_WEBP == 1 case IW_FORMAT_WEBP: #endif case IW_FORMAT_MIFF: case IW_FORMAT_GIF: case IW_FORMAT_BMP: case IW_FORMAT_PNM: case IW_FORMAT_PAM: return 1; } return 0; } IW_IMPL(int) iw_is_output_fmt_supported(int fmt) { switch(fmt) { #if IW_SUPPORT_PNG == 1 case IW_FORMAT_PNG: #endif #if IW_SUPPORT_JPEG == 1 case IW_FORMAT_JPEG: #endif #if IW_SUPPORT_WEBP == 1 case IW_FORMAT_WEBP: #endif case IW_FORMAT_BMP: case IW_FORMAT_TIFF: case IW_FORMAT_MIFF: case IW_FORMAT_PNM: case IW_FORMAT_PPM: case IW_FORMAT_PGM: case IW_FORMAT_PBM: case IW_FORMAT_PAM: return 1; } return 0; } // Find where a number ends (at a comma, or the end of string), // and record if it contained a slash. static int iw_get_number_len(const char *s, int *pslash_pos) { int i; for(i=0;s[i];i++) { if(s[i]=='/') { *pslash_pos = i; } if(s[i]!=',') continue; return i; } return i; } // Returns 0 if no valid number found. static int iw_parse_number_internal(const char *s, double *presult, int *pcharsread) { int len; int slash_pos = -1; *presult = 0.0; *pcharsread = 0; len = iw_get_number_len(s,&slash_pos); if(len<1) return 0; *pcharsread = len; if(slash_pos>=0) { // a rational number double numer, denom; numer = atof(s); denom = atof(s+slash_pos+1); if(denom==0.0) *presult = 0.0; else *presult = numer/denom; } else { *presult = atof(s); } return 1; } // Returns number of numbers parsed. // If there are not enough numbers, leaves some contents of 'results' unchanged. IW_IMPL(int) iw_parse_number_list(const char *s, int max_numbers, // max number of numbers to parse double *results) // array of doubles to hold the results { int n; int charsread; int curpos=0; int ret; int numresults = 0; for(n=0;n<max_numbers;n++) { ret=iw_parse_number_internal(&s[curpos], &results[n], &charsread); if(!ret) break; numresults++; curpos+=charsread; if(s[curpos]==',') { curpos++; } else { break; } } return numresults; } IW_IMPL(double) iw_parse_number(const char *s) { double result; int charsread; iw_parse_number_internal(s, &result, &charsread); return result; } IW_IMPL(int) iw_round_to_int(double x) { if(x<0.0) return -(int)(0.5-x); return (int)(0.5+x); } IW_IMPL(int) iw_parse_int(const char *s) { double result; int charsread; iw_parse_number_internal(s, &result, &charsread); return iw_round_to_int(result); }
./CrossVul/dataset_final_sorted/CWE-682/c/good_3331_1
crossvul-cpp_data_good_278_1
/* This file is part of libmspack. * (C) 2003-2011 Stuart Caie. * * libmspack is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License (LGPL) version 2.1 * * For further details, see the file COPYING.LIB distributed with libmspack */ /* CHM decompression implementation */ #include <system.h> #include <chm.h> /* prototypes */ static struct mschmd_header * chmd_open( struct mschm_decompressor *base, const char *filename); static struct mschmd_header * chmd_fast_open( struct mschm_decompressor *base, const char *filename); static struct mschmd_header *chmd_real_open( struct mschm_decompressor *base, const char *filename, int entire); static void chmd_close( struct mschm_decompressor *base, struct mschmd_header *chm); static int chmd_read_headers( struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire); static int chmd_fast_find( struct mschm_decompressor *base, struct mschmd_header *chm, const char *filename, struct mschmd_file *f_ptr, int f_size); static unsigned char *read_chunk( struct mschm_decompressor_p *self, struct mschmd_header *chm, struct mspack_file *fh, unsigned int chunk); static int search_chunk( struct mschmd_header *chm, const unsigned char *chunk, const char *filename, const unsigned char **result, const unsigned char **result_end); static inline int compare( const char *s1, const char *s2, int l1, int l2); static int chmd_extract( struct mschm_decompressor *base, struct mschmd_file *file, const char *filename); static int chmd_sys_write( struct mspack_file *file, void *buffer, int bytes); static int chmd_init_decomp( struct mschm_decompressor_p *self, struct mschmd_file *file); static int read_reset_table( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, int entry, off_t *length_ptr, off_t *offset_ptr); static int read_spaninfo( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, off_t *length_ptr); static int find_sys_file( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, struct mschmd_file **f_ptr, const char *name); static unsigned char *read_sys_file( struct mschm_decompressor_p *self, struct mschmd_file *file); static int chmd_error( struct mschm_decompressor *base); static int read_off64( off_t *var, unsigned char *mem, struct mspack_system *sys, struct mspack_file *fh); /* filenames of the system files used for decompression. * Content and ControlData are essential. * ResetTable is preferred, but SpanInfo can be used if not available */ static const char *content_name = "::DataSpace/Storage/MSCompressed/Content"; static const char *control_name = "::DataSpace/Storage/MSCompressed/ControlData"; static const char *spaninfo_name = "::DataSpace/Storage/MSCompressed/SpanInfo"; static const char *rtable_name = "::DataSpace/Storage/MSCompressed/Transform/" "{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable"; /*************************************** * MSPACK_CREATE_CHM_DECOMPRESSOR *************************************** * constructor */ struct mschm_decompressor * mspack_create_chm_decompressor(struct mspack_system *sys) { struct mschm_decompressor_p *self = NULL; if (!sys) sys = mspack_default_system; if (!mspack_valid_system(sys)) return NULL; if ((self = (struct mschm_decompressor_p *) sys->alloc(sys, sizeof(struct mschm_decompressor_p)))) { self->base.open = &chmd_open; self->base.close = &chmd_close; self->base.extract = &chmd_extract; self->base.last_error = &chmd_error; self->base.fast_open = &chmd_fast_open; self->base.fast_find = &chmd_fast_find; self->system = sys; self->error = MSPACK_ERR_OK; self->d = NULL; } return (struct mschm_decompressor *) self; } /*************************************** * MSPACK_DESTROY_CAB_DECOMPRESSOR *************************************** * destructor */ void mspack_destroy_chm_decompressor(struct mschm_decompressor *base) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; if (self) { struct mspack_system *sys = self->system; if (self->d) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); sys->free(self->d); } sys->free(self); } } /*************************************** * CHMD_OPEN *************************************** * opens a file and tries to read it as a CHM file. * Calls chmd_real_open() with entire=1. */ static struct mschmd_header *chmd_open(struct mschm_decompressor *base, const char *filename) { return chmd_real_open(base, filename, 1); } /*************************************** * CHMD_FAST_OPEN *************************************** * opens a file and tries to read it as a CHM file, but does not read * the file headers. Calls chmd_real_open() with entire=0 */ static struct mschmd_header *chmd_fast_open(struct mschm_decompressor *base, const char *filename) { return chmd_real_open(base, filename, 0); } /*************************************** * CHMD_REAL_OPEN *************************************** * the real implementation of chmd_open() and chmd_fast_open(). It simply * passes the "entire" parameter to chmd_read_headers(), which will then * either read all headers, or a bare mininum. */ static struct mschmd_header *chmd_real_open(struct mschm_decompressor *base, const char *filename, int entire) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mschmd_header *chm = NULL; struct mspack_system *sys; struct mspack_file *fh; int error; if (!base) return NULL; sys = self->system; if ((fh = sys->open(sys, filename, MSPACK_SYS_OPEN_READ))) { if ((chm = (struct mschmd_header *) sys->alloc(sys, sizeof(struct mschmd_header)))) { chm->filename = filename; error = chmd_read_headers(sys, fh, chm, entire); if (error) { /* if the error is DATAFORMAT, and there are some results, return * partial results with a warning, rather than nothing */ if (error == MSPACK_ERR_DATAFORMAT && (chm->files || chm->sysfiles)) { sys->message(fh, "WARNING; contents are corrupt"); error = MSPACK_ERR_OK; } else { chmd_close(base, chm); chm = NULL; } } self->error = error; } else { self->error = MSPACK_ERR_NOMEMORY; } sys->close(fh); } else { self->error = MSPACK_ERR_OPEN; } return chm; } /*************************************** * CHMD_CLOSE *************************************** * frees all memory associated with a given mschmd_header */ static void chmd_close(struct mschm_decompressor *base, struct mschmd_header *chm) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mschmd_file *fi, *nfi; struct mspack_system *sys; unsigned int i; if (!base) return; sys = self->system; self->error = MSPACK_ERR_OK; /* free files */ for (fi = chm->files; fi; fi = nfi) { nfi = fi->next; sys->free(fi); } for (fi = chm->sysfiles; fi; fi = nfi) { nfi = fi->next; sys->free(fi); } /* if this CHM was being decompressed, free decompression state */ if (self->d && (self->d->chm == chm)) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); sys->free(self->d); self->d = NULL; } /* if this CHM had a chunk cache, free it and contents */ if (chm->chunk_cache) { for (i = 0; i < chm->num_chunks; i++) sys->free(chm->chunk_cache[i]); sys->free(chm->chunk_cache); } sys->free(chm); } /*************************************** * CHMD_READ_HEADERS *************************************** * reads the basic CHM file headers. If the "entire" parameter is * non-zero, all file entries will also be read. fills out a pre-existing * mschmd_header structure, allocates memory for files as necessary */ /* The GUIDs found in CHM headers */ static const unsigned char guids[32] = { /* {7C01FD10-7BAA-11D0-9E0C-00A0-C922-E6EC} */ 0x10, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11, 0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC, /* {7C01FD11-7BAA-11D0-9E0C-00A0-C922-E6EC} */ 0x11, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11, 0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC }; /* reads an encoded integer into a variable; 7 bits of data per byte, * the high bit is used to indicate that there is another byte */ #define READ_ENCINT(var) do { \ (var) = 0; \ do { \ if (p >= end) goto chunk_end; \ (var) = ((var) << 7) | (*p & 0x7F); \ } while (*p++ & 0x80); \ } while (0) static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire) { unsigned int section, name_len, x, errors, num_chunks; unsigned char buf[0x54], *chunk = NULL, *name, *p, *end; struct mschmd_file *fi, *link = NULL; off_t offset, length; int num_entries; /* initialise pointers */ chm->files = NULL; chm->sysfiles = NULL; chm->chunk_cache = NULL; chm->sec0.base.chm = chm; chm->sec0.base.id = 0; chm->sec1.base.chm = chm; chm->sec1.base.id = 1; chm->sec1.content = NULL; chm->sec1.control = NULL; chm->sec1.spaninfo = NULL; chm->sec1.rtable = NULL; /* read the first header */ if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) { return MSPACK_ERR_READ; } /* check ITSF signature */ if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) { return MSPACK_ERR_SIGNATURE; } /* check both header GUIDs */ if (mspack_memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) { D(("incorrect GUIDs")) return MSPACK_ERR_SIGNATURE; } chm->version = EndGetI32(&buf[chmhead_Version]); chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]); chm->language = EndGetI32(&buf[chmhead_LanguageID]); if (chm->version > 3) { sys->message(fh, "WARNING; CHM version > 3"); } /* read the header section table */ if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) { return MSPACK_ERR_READ; } /* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files. * The offset will be corrected later, once HS1 is read. */ if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) || read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) || read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 0 */ if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 0 */ if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) { return MSPACK_ERR_READ; } if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 1 */ if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 1 */ if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) { return MSPACK_ERR_READ; } chm->dir_offset = sys->tell(fh); chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]); chm->density = EndGetI32(&buf[chmhs1_Density]); chm->depth = EndGetI32(&buf[chmhs1_Depth]); chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]); chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]); chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]); chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]); if (chm->version < 3) { /* versions before 3 don't have chmhst3_OffsetCS0 */ chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks); } /* check if content offset or file size is wrong */ if (chm->sec0.offset > chm->length) { D(("content section begins after file has ended")) return MSPACK_ERR_DATAFORMAT; } /* ensure there are chunks and that chunk size is * large enough for signature and num_entries */ if (chm->chunk_size < (pmgl_Entries + 2)) { D(("chunk size not large enough")) return MSPACK_ERR_DATAFORMAT; } if (chm->num_chunks == 0) { D(("no chunks")) return MSPACK_ERR_DATAFORMAT; } /* The chunk_cache data structure is not great; large values for num_chunks * or num_chunks*chunk_size can exhaust all memory. Until a better chunk * cache is implemented, put arbitrary limits on num_chunks and chunk size. */ if (chm->num_chunks > 100000) { D(("more than 100,000 chunks")) return MSPACK_ERR_DATAFORMAT; } if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) { D(("chunks larger than entire file")) return MSPACK_ERR_DATAFORMAT; } /* common sense checks on header section 1 fields */ if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) { sys->message(fh, "WARNING; chunk size is not a power of two"); } if (chm->first_pmgl != 0) { sys->message(fh, "WARNING; first PMGL chunk is not zero"); } if (chm->first_pmgl > chm->last_pmgl) { D(("first pmgl chunk is after last pmgl chunk")) return MSPACK_ERR_DATAFORMAT; } if (chm->index_root != 0xFFFFFFFF && chm->index_root > chm->num_chunks) { D(("index_root outside valid range")) return MSPACK_ERR_DATAFORMAT; } /* if we are doing a quick read, stop here! */ if (!entire) { return MSPACK_ERR_OK; } /* seek to the first PMGL chunk, and reduce the number of chunks to read */ if ((x = chm->first_pmgl) != 0) { if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) { return MSPACK_ERR_SEEK; } } num_chunks = chm->last_pmgl - x + 1; if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) { return MSPACK_ERR_NOMEMORY; } /* read and process all chunks from FirstPMGL to LastPMGL */ errors = 0; while (num_chunks--) { /* read next chunk */ if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) { sys->free(chunk); return MSPACK_ERR_READ; } /* process only directory (PMGL) chunks */ if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue; if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) { sys->message(fh, "WARNING; PMGL quickref area is too small"); } if (EndGetI32(&chunk[pmgl_QuickRefSize]) > ((int)chm->chunk_size - pmgl_Entries)) { sys->message(fh, "WARNING; PMGL quickref area is too large"); } p = &chunk[pmgl_Entries]; end = &chunk[chm->chunk_size - 2]; num_entries = EndGetI16(end); while (num_entries--) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; name = p; p += name_len; READ_ENCINT(section); READ_ENCINT(offset); READ_ENCINT(length); /* empty files and directory names are stored as a file entry at * offset 0 with length 0. We want to keep empty files, but not * directory names, which end with a "/" */ if ((offset == 0) && (length == 0)) { if ((name_len > 0) && (name[name_len-1] == '/')) continue; } if (section > 1) { sys->message(fh, "invalid section number '%u'.", section); continue; } if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) { sys->free(chunk); return MSPACK_ERR_NOMEMORY; } fi->next = NULL; fi->filename = (char *) &fi[1]; fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0) : (struct mschmd_section *) (&chm->sec1)); fi->offset = offset; fi->length = length; sys->copy(name, fi->filename, (size_t) name_len); fi->filename[name_len] = '\0'; if (name[0] == ':' && name[1] == ':') { /* system file */ if (mspack_memcmp(&name[2], &content_name[2], 31L) == 0) { if (mspack_memcmp(&name[33], &content_name[33], 8L) == 0) { chm->sec1.content = fi; } else if (mspack_memcmp(&name[33], &control_name[33], 11L) == 0) { chm->sec1.control = fi; } else if (mspack_memcmp(&name[33], &spaninfo_name[33], 8L) == 0) { chm->sec1.spaninfo = fi; } else if (mspack_memcmp(&name[33], &rtable_name[33], 72L) == 0) { chm->sec1.rtable = fi; } } fi->next = chm->sysfiles; chm->sysfiles = fi; } else { /* normal file */ if (link) link->next = fi; else chm->files = fi; link = fi; } } /* this is reached either when num_entries runs out, or if * reading data from the chunk reached a premature end of chunk */ chunk_end: if (num_entries >= 0) { D(("chunk ended before all entries could be read")) errors++; } } sys->free(chunk); return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK; } /*************************************** * CHMD_FAST_FIND *************************************** * uses PMGI index chunks and quickref data to quickly locate a file * directly from the on-disk index. * * TODO: protect against infinite loops in chunks (where pgml_NextChunk * or a PGMI index entry point to an already visited chunk) */ static int chmd_fast_find(struct mschm_decompressor *base, struct mschmd_header *chm, const char *filename, struct mschmd_file *f_ptr, int f_size) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mspack_system *sys; struct mspack_file *fh; const unsigned char *chunk, *p, *end; int err = MSPACK_ERR_OK, result = -1; unsigned int n, sec; if (!self || !chm || !f_ptr || (f_size != sizeof(struct mschmd_file))) { return MSPACK_ERR_ARGS; } sys = self->system; /* clear the results structure */ memset(f_ptr, 0, f_size); if (!(fh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ))) { return MSPACK_ERR_OPEN; } /* go through PMGI chunk hierarchy to reach PMGL chunk */ if (chm->index_root < chm->num_chunks) { n = chm->index_root; for (;;) { if (!(chunk = read_chunk(self, chm, fh, n))) { sys->close(fh); return self->error; } /* search PMGI/PMGL chunk. exit early if no entry found */ if ((result = search_chunk(chm, chunk, filename, &p, &end)) <= 0) { break; } /* found result. loop around for next chunk if this is PMGI */ if (chunk[3] == 0x4C) break; else READ_ENCINT(n); } } else { /* PMGL chunks only, search from first_pmgl to last_pmgl */ for (n = chm->first_pmgl; n <= chm->last_pmgl; n = EndGetI32(&chunk[pmgl_NextChunk])) { if (!(chunk = read_chunk(self, chm, fh, n))) { err = self->error; break; } /* search PMGL chunk. exit if file found */ if ((result = search_chunk(chm, chunk, filename, &p, &end)) > 0) { break; } /* stop simple infinite loops: can't visit the same chunk twice */ if ((int)n == EndGetI32(&chunk[pmgl_NextChunk])) { break; } } } /* if we found a file, read it */ if (result > 0) { READ_ENCINT(sec); f_ptr->section = (sec == 0) ? (struct mschmd_section *) &chm->sec0 : (struct mschmd_section *) &chm->sec1; READ_ENCINT(f_ptr->offset); READ_ENCINT(f_ptr->length); } else if (result < 0) { err = MSPACK_ERR_DATAFORMAT; } sys->close(fh); return self->error = err; chunk_end: D(("read beyond end of chunk entries")) sys->close(fh); return self->error = MSPACK_ERR_DATAFORMAT; } /* reads the given chunk into memory, storing it in a chunk cache * so it doesn't need to be read from disk more than once */ static unsigned char *read_chunk(struct mschm_decompressor_p *self, struct mschmd_header *chm, struct mspack_file *fh, unsigned int chunk_num) { struct mspack_system *sys = self->system; unsigned char *buf; /* check arguments - most are already checked by chmd_fast_find */ if (chunk_num > chm->num_chunks) return NULL; /* ensure chunk cache is available */ if (!chm->chunk_cache) { size_t size = sizeof(unsigned char *) * chm->num_chunks; if (!(chm->chunk_cache = (unsigned char **) sys->alloc(sys, size))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } memset(chm->chunk_cache, 0, size); } /* try to answer out of chunk cache */ if (chm->chunk_cache[chunk_num]) return chm->chunk_cache[chunk_num]; /* need to read chunk - allocate memory for it */ if (!(buf = (unsigned char *) sys->alloc(sys, chm->chunk_size))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } /* seek to block and read it */ if (sys->seek(fh, (off_t) (chm->dir_offset + (chunk_num * chm->chunk_size)), MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; sys->free(buf); return NULL; } if (sys->read(fh, buf, (int)chm->chunk_size) != (int)chm->chunk_size) { self->error = MSPACK_ERR_READ; sys->free(buf); return NULL; } /* check the signature. Is is PMGL or PMGI? */ if (!((buf[0] == 0x50) && (buf[1] == 0x4D) && (buf[2] == 0x47) && ((buf[3] == 0x4C) || (buf[3] == 0x49)))) { self->error = MSPACK_ERR_SEEK; sys->free(buf); return NULL; } /* all OK. Store chunk in cache and return it */ return chm->chunk_cache[chunk_num] = buf; } /* searches a PMGI/PMGL chunk for a given filename entry. Returns -1 on * data format error, 0 if entry definitely not found, 1 if entry * found. In the latter case, *result and *result_end are set pointing * to that entry's data (either the "next chunk" ENCINT for a PMGI or * the section, offset and length ENCINTs for a PMGL). * * In the case of PMGL chunks, the entry has definitely been * found. In the case of PMGI chunks, the entry which points to the * chunk that may eventually contain that entry has been found. */ static int search_chunk(struct mschmd_header *chm, const unsigned char *chunk, const char *filename, const unsigned char **result, const unsigned char **result_end) { const unsigned char *start, *end, *p; unsigned int qr_size, num_entries, qr_entries, qr_density, name_len; unsigned int L, R, M, fname_len, entries_off, is_pmgl; int cmp; fname_len = strlen(filename); /* PMGL chunk or PMGI chunk? (note: read_chunk() has already * checked the rest of the characters in the chunk signature) */ if (chunk[3] == 0x4C) { is_pmgl = 1; entries_off = pmgl_Entries; } else { is_pmgl = 0; entries_off = pmgi_Entries; } /* Step 1: binary search first filename of each QR entry * - target filename == entry * found file * - target filename < all entries * file not found * - target filename > all entries * proceed to step 2 using final entry * - target filename between two searched entries * proceed to step 2 */ qr_size = EndGetI32(&chunk[pmgl_QuickRefSize]); start = &chunk[chm->chunk_size - 2]; end = &chunk[chm->chunk_size - qr_size]; num_entries = EndGetI16(start); qr_density = 1 + (1 << chm->density); qr_entries = (num_entries + qr_density-1) / qr_density; if (num_entries == 0) { D(("chunk has no entries")) return -1; } if (qr_size > chm->chunk_size) { D(("quickref size > chunk size")) return -1; } *result_end = end; if (((int)qr_entries * 2) > (start - end)) { D(("WARNING; more quickrefs than quickref space")) qr_entries = 0; /* but we can live with it */ } if (qr_entries > 0) { L = 0; R = qr_entries - 1; do { /* pick new midpoint */ M = (L + R) >> 1; /* compare filename with entry QR points to */ p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)]; READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; cmp = compare(filename, (char *)p, fname_len, name_len); if (cmp == 0) break; else if (cmp < 0) { if (M) R = M - 1; else return 0; } else if (cmp > 0) L = M + 1; } while (L <= R); M = (L + R) >> 1; if (cmp == 0) { /* exact match! */ p += name_len; *result = p; return 1; } /* otherwise, read the group of entries for QR entry M */ p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)]; num_entries -= (M * qr_density); if (num_entries > qr_density) num_entries = qr_density; } else { p = &chunk[entries_off]; } /* Step 2: linear search through the set of entries reached in step 1. * - filename == any entry * found entry * - filename < all entries (PMGI) or any entry (PMGL) * entry not found, stop now * - filename > all entries * entry not found (PMGL) / maybe found (PMGI) * - */ *result = NULL; while (num_entries-- > 0) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; cmp = compare(filename, (char *)p, fname_len, name_len); p += name_len; if (cmp == 0) { /* entry found */ *result = p; return 1; } if (cmp < 0) { /* entry not found (PMGL) / maybe found (PMGI) */ break; } /* read and ignore the rest of this entry */ if (is_pmgl) { READ_ENCINT(R); /* skip section */ READ_ENCINT(R); /* skip offset */ READ_ENCINT(R); /* skip length */ } else { *result = p; /* store potential final result */ READ_ENCINT(R); /* skip chunk number */ } } /* PMGL? not found. PMGI? maybe found */ return (is_pmgl) ? 0 : (*result ? 1 : 0); chunk_end: D(("reached end of chunk data while searching")) return -1; } #if HAVE_TOWLOWER # if HAVE_WCTYPE_H # include <wctype.h> # endif # define TOLOWER(x) towlower(x) #elif HAVE_TOLOWER # if HAVE_CTYPE_H # include <ctype.h> # endif # define TOLOWER(x) tolower(x) #else # define TOLOWER(x) (((x)<0||(x)>255)?(x):mspack_tolower_map[(x)]) /* Map of char -> lowercase char for the first 256 chars. Generated with: * LC_CTYPE=en_GB.utf-8 perl -Mlocale -le 'print map{ord(lc chr).","} 0..255' */ static const unsigned char mspack_tolower_map[256] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, 28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52, 53,54,55,56,57,58,59,60,61,62,63,64,97,98,99,100,101,102,103,104,105,106, 107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,91,92,93,94, 95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114, 115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133, 134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152, 153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171, 172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190, 191,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241, 242,243,244,245,246,215,248,249,250,251,252,253,254,223,224,225,226,227,228, 229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247, 248,249,250,251,252,253,254,255 }; #endif /* decodes a UTF-8 character from s[] into c. Will not read past e. * doesn't test that extension bytes are %10xxxxxx. * allows some overlong encodings. */ #define GET_UTF8_CHAR(s, e, c) do { \ unsigned char x = *s++; \ if (x < 0x80) c = x; \ else if (x >= 0xC2 && x < 0xE0 && s < e) { \ c = (x & 0x1F) << 6 | (*s++ & 0x3F); \ } \ else if (x >= 0xE0 && x < 0xF0 && s+1 < e) { \ c = (x & 0x0F) << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F); \ s += 2; \ } \ else if (x >= 0xF0 && x <= 0xF5 && s+2 < e) { \ c = (x & 0x07) << 18 | (s[0] & 0x3F) << 12 | \ (s[1] & 0x3F) << 6 | (s[2] & 0x3F); \ if (c > 0x10FFFF) c = 0xFFFD; \ s += 3; \ } \ else c = 0xFFFD; \ } while (0) /* case-insensitively compares two UTF8 encoded strings. String length for * both strings must be provided, null bytes are not terminators */ static inline int compare(const char *s1, const char *s2, int l1, int l2) { register const unsigned char *p1 = (const unsigned char *) s1; register const unsigned char *p2 = (const unsigned char *) s2; register const unsigned char *e1 = p1 + l1, *e2 = p2 + l2; int c1, c2; while (p1 < e1 && p2 < e2) { GET_UTF8_CHAR(p1, e1, c1); GET_UTF8_CHAR(p2, e2, c2); if (c1 == c2) continue; c1 = TOLOWER(c1); c2 = TOLOWER(c2); if (c1 != c2) return c1 - c2; } return l1 - l2; } /*************************************** * CHMD_EXTRACT *************************************** * extracts a file from a CHM helpfile */ static int chmd_extract(struct mschm_decompressor *base, struct mschmd_file *file, const char *filename) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mspack_system *sys; struct mschmd_header *chm; struct mspack_file *fh; off_t bytes; if (!self) return MSPACK_ERR_ARGS; if (!file || !file->section) return self->error = MSPACK_ERR_ARGS; sys = self->system; chm = file->section->chm; /* create decompression state if it doesn't exist */ if (!self->d) { self->d = (struct mschmd_decompress_state *) sys->alloc(sys, sizeof(struct mschmd_decompress_state)); if (!self->d) return self->error = MSPACK_ERR_NOMEMORY; self->d->chm = chm; self->d->offset = 0; self->d->state = NULL; self->d->sys = *sys; self->d->sys.write = &chmd_sys_write; self->d->infh = NULL; self->d->outfh = NULL; } /* open input chm file if not open, or the open one is a different chm */ if (!self->d->infh || (self->d->chm != chm)) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); self->d->chm = chm; self->d->offset = 0; self->d->state = NULL; self->d->infh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ); if (!self->d->infh) return self->error = MSPACK_ERR_OPEN; } /* open file for output */ if (!(fh = sys->open(sys, filename, MSPACK_SYS_OPEN_WRITE))) { return self->error = MSPACK_ERR_OPEN; } /* if file is empty, simply creating it is enough */ if (!file->length) { sys->close(fh); return self->error = MSPACK_ERR_OK; } self->error = MSPACK_ERR_OK; switch (file->section->id) { case 0: /* Uncompressed section file */ /* simple seek + copy */ if (sys->seek(self->d->infh, file->section->chm->sec0.offset + file->offset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; } else { unsigned char buf[512]; off_t length = file->length; while (length > 0) { int run = sizeof(buf); if ((off_t)run > length) run = (int)length; if (sys->read(self->d->infh, &buf[0], run) != run) { self->error = MSPACK_ERR_READ; break; } if (sys->write(fh, &buf[0], run) != run) { self->error = MSPACK_ERR_WRITE; break; } length -= run; } } break; case 1: /* MSCompressed section file */ /* (re)initialise compression state if we it is not yet initialised, * or we have advanced too far and have to backtrack */ if (!self->d->state || (file->offset < self->d->offset)) { if (self->d->state) { lzxd_free(self->d->state); self->d->state = NULL; } if (chmd_init_decomp(self, file)) break; } /* seek to input data */ if (sys->seek(self->d->infh, self->d->inoffset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; break; } /* get to correct offset. */ self->d->outfh = NULL; if ((bytes = file->offset - self->d->offset)) { self->error = lzxd_decompress(self->d->state, bytes); } /* if getting to the correct offset was error free, unpack file */ if (!self->error) { self->d->outfh = fh; self->error = lzxd_decompress(self->d->state, file->length); } /* save offset in input source stream, in case there is a section 0 * file between now and the next section 1 file extracted */ self->d->inoffset = sys->tell(self->d->infh); /* if an LZX error occured, the LZX decompressor is now useless */ if (self->error) { if (self->d->state) lzxd_free(self->d->state); self->d->state = NULL; } break; } sys->close(fh); return self->error; } /*************************************** * CHMD_SYS_WRITE *************************************** * chmd_sys_write is the internal writer function which the decompressor * uses. If either writes data to disk (self->d->outfh) with the real * sys->write() function, or does nothing with the data when * self->d->outfh == NULL. advances self->d->offset. */ static int chmd_sys_write(struct mspack_file *file, void *buffer, int bytes) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) file; self->d->offset += bytes; if (self->d->outfh) { return self->system->write(self->d->outfh, buffer, bytes); } return bytes; } /*************************************** * CHMD_INIT_DECOMP *************************************** * Initialises the LZX decompressor to decompress the compressed stream, * from the nearest reset offset and length that is needed for the given * file. */ static int chmd_init_decomp(struct mschm_decompressor_p *self, struct mschmd_file *file) { int window_size, window_bits, reset_interval, entry, err; struct mspack_system *sys = self->system; struct mschmd_sec_mscompressed *sec; unsigned char *data; off_t length, offset; sec = (struct mschmd_sec_mscompressed *) file->section; /* ensure we have a mscompressed content section */ err = find_sys_file(self, sec, &sec->content, content_name); if (err) return self->error = err; /* ensure we have a ControlData file */ err = find_sys_file(self, sec, &sec->control, control_name); if (err) return self->error = err; /* read ControlData */ if (sec->control->length < lzxcd_SIZEOF) { D(("ControlData file is too short")) return self->error = MSPACK_ERR_DATAFORMAT; } if (!(data = read_sys_file(self, sec->control))) { D(("can't read mscompressed control data file")) return self->error; } /* check LZXC signature */ if (EndGetI32(&data[lzxcd_Signature]) != 0x43585A4C) { sys->free(data); return self->error = MSPACK_ERR_SIGNATURE; } /* read reset_interval and window_size and validate version number */ switch (EndGetI32(&data[lzxcd_Version])) { case 1: reset_interval = EndGetI32(&data[lzxcd_ResetInterval]); window_size = EndGetI32(&data[lzxcd_WindowSize]); break; case 2: reset_interval = EndGetI32(&data[lzxcd_ResetInterval]) * LZX_FRAME_SIZE; window_size = EndGetI32(&data[lzxcd_WindowSize]) * LZX_FRAME_SIZE; break; default: D(("bad controldata version")) sys->free(data); return self->error = MSPACK_ERR_DATAFORMAT; } /* free ControlData */ sys->free(data); /* find window_bits from window_size */ switch (window_size) { case 0x008000: window_bits = 15; break; case 0x010000: window_bits = 16; break; case 0x020000: window_bits = 17; break; case 0x040000: window_bits = 18; break; case 0x080000: window_bits = 19; break; case 0x100000: window_bits = 20; break; case 0x200000: window_bits = 21; break; default: D(("bad controldata window size")) return self->error = MSPACK_ERR_DATAFORMAT; } /* validate reset_interval */ if (reset_interval == 0 || reset_interval % LZX_FRAME_SIZE) { D(("bad controldata reset interval")) return self->error = MSPACK_ERR_DATAFORMAT; } /* which reset table entry would we like? */ entry = file->offset / reset_interval; /* convert from reset interval multiple (usually 64k) to 32k frames */ entry *= reset_interval / LZX_FRAME_SIZE; /* read the reset table entry */ if (read_reset_table(self, sec, entry, &length, &offset)) { /* the uncompressed length given in the reset table is dishonest. * the uncompressed data is always padded out from the given * uncompressed length up to the next reset interval */ length += reset_interval - 1; length &= -reset_interval; } else { /* if we can't read the reset table entry, just start from * the beginning. Use spaninfo to get the uncompressed length */ entry = 0; offset = 0; err = read_spaninfo(self, sec, &length); } if (err) return self->error = err; /* get offset of compressed data stream: * = offset of uncompressed section from start of file * + offset of compressed stream from start of uncompressed section * + offset of chosen reset interval from start of compressed stream */ self->d->inoffset = file->section->chm->sec0.offset + sec->content->offset + offset; /* set start offset and overall remaining stream length */ self->d->offset = entry * LZX_FRAME_SIZE; length -= self->d->offset; /* initialise LZX stream */ self->d->state = lzxd_init(&self->d->sys, self->d->infh, (struct mspack_file *) self, window_bits, reset_interval / LZX_FRAME_SIZE, 4096, length, 0); if (!self->d->state) self->error = MSPACK_ERR_NOMEMORY; return self->error; } /*************************************** * READ_RESET_TABLE *************************************** * Reads one entry out of the reset table. Also reads the uncompressed * data length. Writes these to offset_ptr and length_ptr respectively. * Returns non-zero for success, zero for failure. */ static int read_reset_table(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, int entry, off_t *length_ptr, off_t *offset_ptr) { struct mspack_system *sys = self->system; unsigned char *data; unsigned int pos, entrysize; /* do we have a ResetTable file? */ int err = find_sys_file(self, sec, &sec->rtable, rtable_name); if (err) return 0; /* read ResetTable file */ if (sec->rtable->length < lzxrt_headerSIZEOF) { D(("ResetTable file is too short")) return 0; } if (!(data = read_sys_file(self, sec->rtable))) { D(("can't read reset table")) return 0; } /* check sanity of reset table */ if (EndGetI32(&data[lzxrt_FrameLen]) != LZX_FRAME_SIZE) { D(("bad reset table frame length")) sys->free(data); return 0; } /* get the uncompressed length of the LZX stream */ if (read_off64(length_ptr, &data[lzxrt_UncompLen], sys, self->d->infh)) { sys->free(data); return 0; } entrysize = EndGetI32(&data[lzxrt_EntrySize]); pos = EndGetI32(&data[lzxrt_TableOffset]) + (entry * entrysize); /* ensure reset table entry for this offset exists */ if (entry < EndGetI32(&data[lzxrt_NumEntries]) && pos <= (sec->rtable->length - entrysize)) { switch (entrysize) { case 4: *offset_ptr = EndGetI32(&data[pos]); err = 0; break; case 8: err = read_off64(offset_ptr, &data[pos], sys, self->d->infh); break; default: D(("reset table entry size neither 4 nor 8")) err = 1; break; } } else { D(("bad reset interval")) err = 1; } /* free the reset table */ sys->free(data); /* return success */ return (err == 0); } /*************************************** * READ_SPANINFO *************************************** * Reads the uncompressed data length from the spaninfo file. * Returns zero for success or a non-zero error code for failure. */ static int read_spaninfo(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, off_t *length_ptr) { struct mspack_system *sys = self->system; unsigned char *data; /* find SpanInfo file */ int err = find_sys_file(self, sec, &sec->spaninfo, spaninfo_name); if (err) return MSPACK_ERR_DATAFORMAT; /* check it's large enough */ if (sec->spaninfo->length != 8) { D(("SpanInfo file is wrong size")) return MSPACK_ERR_DATAFORMAT; } /* read the SpanInfo file */ if (!(data = read_sys_file(self, sec->spaninfo))) { D(("can't read SpanInfo file")) return self->error; } /* get the uncompressed length of the LZX stream */ err = read_off64(length_ptr, data, sys, self->d->infh); sys->free(data); if (err) return MSPACK_ERR_DATAFORMAT; if (*length_ptr <= 0) { D(("output length is invalid")) return MSPACK_ERR_DATAFORMAT; } return MSPACK_ERR_OK; } /*************************************** * FIND_SYS_FILE *************************************** * Uses chmd_fast_find to locate a system file, and fills out that system * file's entry and links it into the list of system files. Returns zero * for success, non-zero for both failure and the file not existing. */ static int find_sys_file(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, struct mschmd_file **f_ptr, const char *name) { struct mspack_system *sys = self->system; struct mschmd_file result; /* already loaded */ if (*f_ptr) return MSPACK_ERR_OK; /* try using fast_find to find the file - return DATAFORMAT error if * it fails, or successfully doesn't find the file */ if (chmd_fast_find((struct mschm_decompressor *) self, sec->base.chm, name, &result, (int)sizeof(result)) || !result.section) { return MSPACK_ERR_DATAFORMAT; } if (!(*f_ptr = (struct mschmd_file *) sys->alloc(sys, sizeof(result)))) { return MSPACK_ERR_NOMEMORY; } /* copy result */ *(*f_ptr) = result; (*f_ptr)->filename = (char *) name; /* link file into sysfiles list */ (*f_ptr)->next = sec->base.chm->sysfiles; sec->base.chm->sysfiles = *f_ptr; return MSPACK_ERR_OK; } /*************************************** * READ_SYS_FILE *************************************** * Allocates memory for a section 0 (uncompressed) file and reads it into * memory. */ static unsigned char *read_sys_file(struct mschm_decompressor_p *self, struct mschmd_file *file) { struct mspack_system *sys = self->system; unsigned char *data = NULL; int len; if (!file || !file->section || (file->section->id != 0)) { self->error = MSPACK_ERR_DATAFORMAT; return NULL; } len = (int) file->length; if (!(data = (unsigned char *) sys->alloc(sys, (size_t) len))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } if (sys->seek(self->d->infh, file->section->chm->sec0.offset + file->offset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; sys->free(data); return NULL; } if (sys->read(self->d->infh, data, len) != len) { self->error = MSPACK_ERR_READ; sys->free(data); return NULL; } return data; } /*************************************** * CHMD_ERROR *************************************** * returns the last error that occurred */ static int chmd_error(struct mschm_decompressor *base) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; return (self) ? self->error : MSPACK_ERR_ARGS; } /*************************************** * READ_OFF64 *************************************** * Reads a 64-bit signed integer from memory in Intel byte order. * If running on a system with a 64-bit off_t, this is simply done. * If running on a system with a 32-bit off_t, offsets up to 0x7FFFFFFF * are accepted, offsets beyond that cause an error message. */ static int read_off64(off_t *var, unsigned char *mem, struct mspack_system *sys, struct mspack_file *fh) { #ifdef LARGEFILE_SUPPORT *var = EndGetI64(mem); #else *var = EndGetI32(mem); if ((*var & 0x80000000) || EndGetI32(mem+4)) { sys->message(fh, (char *)largefile_msg); return 1; } #endif return 0; }
./CrossVul/dataset_final_sorted/CWE-682/c/good_278_1
crossvul-cpp_data_bad_3331_0
// imagew-bmp.c // Part of ImageWorsener, Copyright (c) 2011 by Jason Summers. // For more information, see the readme.txt file. #include "imagew-config.h" #include <stdio.h> // for SEEK_SET #include <stdlib.h> #include <string.h> #define IW_INCLUDE_UTIL_FUNCTIONS #include "imagew.h" #define IWBMP_BI_RGB 0 // = uncompressed #define IWBMP_BI_RLE8 1 #define IWBMP_BI_RLE4 2 #define IWBMP_BI_BITFIELDS 3 #define IWBMP_BI_JPEG 4 #define IWBMP_BI_PNG 5 #define IWBMPCS_CALIBRATED_RGB 0 #define IWBMPCS_DEVICE_RGB 1 // (Unconfirmed) #define IWBMPCS_DEVICE_CMYK 2 // (Unconfirmed) #define IWBMPCS_SRGB 0x73524742 #define IWBMPCS_WINDOWS 0x57696e20 #define IWBMPCS_PROFILE_LINKED 0x4c494e4b #define IWBMPCS_PROFILE_EMBEDDED 0x4d424544 static size_t iwbmp_calc_bpr(int bpp, size_t width) { return ((bpp*width+31)/32)*4; } struct iwbmprcontext { struct iw_iodescr *iodescr; struct iw_context *ctx; struct iw_image *img; int bmpversion; int width, height; int topdown; int has_fileheader; unsigned int bitcount; // bits per pixel unsigned int compression; // IWBMP_BI_* int uses_bitfields; // 'compression' is BI_BITFIELDS int has_alpha_channel; int bitfields_set; int need_16bit; unsigned int palette_entries; size_t fileheader_size; size_t infoheader_size; size_t bitfields_nbytes; // Bytes consumed by BITFIELDs, if not part of the header. size_t palette_nbytes; size_t bfOffBits; struct iw_palette palette; // For 16- & 32-bit images: unsigned int bf_mask[4]; int bf_high_bit[4]; int bf_low_bit[4]; int bf_bits_count[4]; // number of bits in each channel struct iw_csdescr csdescr; }; static int iwbmp_read(struct iwbmprcontext *rctx, iw_byte *buf, size_t buflen) { int ret; size_t bytesread = 0; ret = (*rctx->iodescr->read_fn)(rctx->ctx,rctx->iodescr, buf,buflen,&bytesread); if(!ret || bytesread!=buflen) { return 0; } return 1; } static int iwbmp_skip_bytes(struct iwbmprcontext *rctx, size_t n) { iw_byte buf[1024]; size_t still_to_read; size_t num_to_read; still_to_read = n; while(still_to_read>0) { num_to_read = still_to_read; if(num_to_read>1024) num_to_read=1024; if(!iwbmp_read(rctx,buf,num_to_read)) { return 0; } still_to_read -= num_to_read; } return 1; } static int iwbmp_read_file_header(struct iwbmprcontext *rctx) { iw_byte buf[14]; if(!iwbmp_read(rctx,buf,14)) return 0; rctx->fileheader_size = 14; if(buf[0]=='B' && buf[1]=='A') { // OS/2 Bitmap Array // TODO: This type of file can contain more than one BMP image. // We only support the first one. if(!iwbmp_read(rctx,buf,14)) return 0; rctx->fileheader_size += 14; } if(buf[0]=='B' && buf[1]=='M') { ; } else if((buf[0]=='C' && buf[1]=='I') || // OS/2 Color Icon (buf[0]=='C' && buf[1]=='P') || // OS/2 Color Pointer (buf[0]=='I' && buf[1]=='C') || // OS/2 Icon (buf[0]=='P' && buf[1]=='T')) // OS/2 Pointer { iw_set_error(rctx->ctx,"This type of BMP file is not supported"); return 0; } else { iw_set_error(rctx->ctx,"Not a BMP file"); return 0; } rctx->bfOffBits = iw_get_ui32le(&buf[10]); return 1; } // Read the 12-byte header of a Windows v2 BMP (also known as OS/2 v1 BMP). static int decode_v2_header(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int nplanes; rctx->width = iw_get_ui16le(&buf[4]); rctx->height = iw_get_ui16le(&buf[6]); nplanes = iw_get_ui16le(&buf[8]); if(nplanes!=1) return 0; rctx->bitcount = iw_get_ui16le(&buf[10]); if(rctx->bitcount!=1 && rctx->bitcount!=4 && rctx->bitcount!=8 && rctx->bitcount!=24) { return 0; } if(rctx->bitcount<=8) { size_t palette_start, palette_end; rctx->palette_entries = 1<<rctx->bitcount; rctx->palette_nbytes = 3*rctx->palette_entries; // Since v2 BMPs have no direct way to indicate that the palette is not // full-sized, assume the palette ends no later than the start of the // bitmap bits. palette_start = rctx->fileheader_size + rctx->infoheader_size; palette_end = palette_start + rctx->palette_nbytes; if(rctx->bfOffBits >= palette_start+3 && rctx->bfOffBits < palette_end) { rctx->palette_entries = (unsigned int)((rctx->bfOffBits - palette_start)/3); rctx->palette_nbytes = 3*rctx->palette_entries; } } return 1; } // Read a Windows v3 or OS/2 v2 header. static int decode_v3_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int nplanes; int biXPelsPerMeter, biYPelsPerMeter; unsigned int biClrUsed = 0; //unsigned int biSizeImage; rctx->width = iw_get_i32le(&buf[4]); rctx->height = iw_get_i32le(&buf[8]); if(rctx->height<0) { rctx->height = -rctx->height; rctx->topdown = 1; } nplanes = iw_get_ui16le(&buf[12]); if(nplanes!=1) return 0; rctx->bitcount = iw_get_ui16le(&buf[14]); // We allow bitcount=2 because it's legal in Windows CE BMPs. if(rctx->bitcount!=1 && rctx->bitcount!=2 && rctx->bitcount!=4 && rctx->bitcount!=8 && rctx->bitcount!=16 && rctx->bitcount!=24 && rctx->bitcount!=32) { iw_set_errorf(rctx->ctx,"Bad or unsupported bit count (%d)",(int)rctx->bitcount); return 0; } if(rctx->infoheader_size<=16) { goto infoheaderdone; } rctx->compression = iw_get_ui32le(&buf[16]); if(rctx->compression==IWBMP_BI_BITFIELDS) { if(rctx->bitcount==1) { iw_set_error(rctx->ctx,"Huffman 1D compression not supported"); return 0; } else if(rctx->bitcount!=16 && rctx->bitcount!=32) { iw_set_error(rctx->ctx,"Bad or unsupported image type"); return 0; } // The compression field is overloaded: BITFIELDS is not a type of // compression. Un-overload it. rctx->uses_bitfields = 1; // The v4/v5 documentation for the "BitCount" field says that the // BITFIELDS data comes after the header, the same as with v3. // The v4/v5 documentation for the "Compression" field says that the // BITFIELDS data is stored in the "Mask" fields of the header. // Am I supposed to conclude that it is redundantly stored in both // places? // Evidence and common sense suggests the "BitCount" documentation is // incorrect, and v4/v5 BMPs never have a separate "bitfields" segment. if(rctx->bmpversion==3) { rctx->bitfields_nbytes = 12; } rctx->compression=IWBMP_BI_RGB; } //biSizeImage = iw_get_ui32le(&buf[20]); biXPelsPerMeter = iw_get_i32le(&buf[24]); biYPelsPerMeter = iw_get_i32le(&buf[28]); rctx->img->density_code = IW_DENSITY_UNITS_PER_METER; rctx->img->density_x = (double)biXPelsPerMeter; rctx->img->density_y = (double)biYPelsPerMeter; if(!iw_is_valid_density(rctx->img->density_x,rctx->img->density_y,rctx->img->density_code)) { rctx->img->density_code=IW_DENSITY_UNKNOWN; } biClrUsed = iw_get_ui32le(&buf[32]); if(biClrUsed>100000) return 0; infoheaderdone: // The documentation of the biClrUsed field is not very clear. // I'm going to assume that if biClrUsed is 0 and bitcount<=8, then // the number of palette colors is the maximum that would be useful // for that bitcount. In all other cases, the number of palette colors // equals biClrUsed. if(biClrUsed==0 && rctx->bitcount<=8) { rctx->palette_entries = 1<<rctx->bitcount; } else { rctx->palette_entries = biClrUsed; } rctx->palette_nbytes = 4*rctx->palette_entries; return 1; } static int process_bf_mask(struct iwbmprcontext *rctx, int k); // Decode the fields that are in v4 and not in v3. static int decode_v4_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { int k; unsigned int cstype; if(rctx->uses_bitfields) { // Set the bitfields masks here, instead of in iwbmp_read_bitfields(). for(k=0;k<4;k++) { rctx->bf_mask[k] = 0; } for(k=0;k<4;k++) { if(rctx->infoheader_size < (size_t)(40+k*4+4)) break; rctx->bf_mask[k] = iw_get_ui32le(&buf[40+k*4]); if(!process_bf_mask(rctx,k)) return 0; } rctx->bitfields_set=1; // Remember not to overwrite the bf_* fields. if(rctx->bf_mask[3]!=0) { // The documentation says this is the mask that "specifies the // alpha component of each pixel." // It doesn't say whther it's associated, or unassociated alpha. // It doesn't say whether 0=transparent, or 0=opaque. // It doesn't say how to tell whether an image has an alpha // channel. // These are the answers I'm going with: // - Unassociated alpha // - 0=transparent // - 16- and 32-bit images have an alpha channel if 'compression' // is set to BI_BITFIELDS, and this alpha mask is nonzero. rctx->has_alpha_channel = 1; } } if(rctx->infoheader_size < 108) return 1; cstype = iw_get_ui32le(&buf[56]); switch(cstype) { case IWBMPCS_CALIBRATED_RGB: // "indicates that endpoints and gamma values are given in the // appropriate fields." (TODO) break; case IWBMPCS_DEVICE_RGB: case IWBMPCS_SRGB: case IWBMPCS_WINDOWS: break; case IWBMPCS_PROFILE_LINKED: case IWBMPCS_PROFILE_EMBEDDED: if(rctx->bmpversion<5) { iw_warning(rctx->ctx,"Invalid colorspace type for BMPv4"); } break; default: iw_warningf(rctx->ctx,"Unrecognized or unsupported colorspace type (0x%x)",cstype); } // Read Gamma fields if(cstype==IWBMPCS_CALIBRATED_RGB) { unsigned int bmpgamma; double gamma[3]; double avggamma; for(k=0;k<3;k++) { bmpgamma = iw_get_ui32le(&buf[96+k*4]); gamma[k] = ((double)bmpgamma)/65536.0; } avggamma = (gamma[0] + gamma[1] + gamma[2])/3.0; if(avggamma>=0.1 && avggamma<=10.0) { iw_make_gamma_csdescr(&rctx->csdescr,1.0/avggamma); } } return 1; } // Decode the fields that are in v5 and not in v4. static int decode_v5_header_fields(struct iwbmprcontext *rctx, const iw_byte *buf) { unsigned int intent_bmp_style; int intent_iw_style; intent_bmp_style = iw_get_ui32le(&buf[108]); intent_iw_style = IW_INTENT_UNKNOWN; switch(intent_bmp_style) { case 1: intent_iw_style = IW_INTENT_SATURATION; break; // LCS_GM_BUSINESS case 2: intent_iw_style = IW_INTENT_RELATIVE; break; // LCS_GM_GRAPHICS case 4: intent_iw_style = IW_INTENT_PERCEPTUAL; break; // LCS_GM_IMAGES case 8: intent_iw_style = IW_INTENT_ABSOLUTE; break; // LCS_GM_ABS_COLORIMETRIC } rctx->img->rendering_intent = intent_iw_style; // The profile may either be after the color table, or after the bitmap bits. // I'm assuming that we will never need to use the profile size in order to // find the bitmap bits; i.e. that if the bfOffBits field in the file header // is not available, the profile must be after the bits. //profile_offset = iw_get_ui32le(&buf[112]); // bV5ProfileData; //profile_size = iw_get_ui32le(&buf[116]); // bV5ProfileSize; return 1; } static int iwbmp_read_info_header(struct iwbmprcontext *rctx) { iw_byte buf[124]; int retval = 0; size_t n; // First, read just the "size" field. It tells the size of the header // structure, and identifies the BMP version. if(!iwbmp_read(rctx,buf,4)) goto done; rctx->infoheader_size = iw_get_ui32le(&buf[0]); if(rctx->infoheader_size<12) goto done; // Read the rest of the header. n = rctx->infoheader_size; if(n>sizeof(buf)) n=sizeof(buf); if(!iwbmp_read(rctx,&buf[4],n-4)) goto done; if(rctx->infoheader_size==12) { // This is a "Windows BMP v2" or "OS/2 BMP v1" bitmap. rctx->bmpversion=2; if(!decode_v2_header(rctx,buf)) goto done; } else if(rctx->infoheader_size==16 || rctx->infoheader_size==40 || rctx->infoheader_size==64) { // A Windows v3 or OS/2 v2 BMP. // OS/2 v2 BMPs can technically have other header sizes between 16 and 64, // but it's not clear if such files actually exist. rctx->bmpversion=3; if(!decode_v3_header_fields(rctx,buf)) goto done; } else if(rctx->infoheader_size==108 || rctx->infoheader_size==52 || rctx->infoheader_size==56) { // We assume a a 52- or 56-byte header is for BITMAPV2INFOHEADER/BITMAPV3INFOHEADER, // and not OS/2v2 format. But if it OS/2v2, it will probably either work (because // the formats are similar enough), or fail due to an unsupported combination of // compression and bits/pixel. rctx->bmpversion=4; if(!decode_v3_header_fields(rctx,buf)) goto done; if(!decode_v4_header_fields(rctx,buf)) goto done; } else if(rctx->infoheader_size==124) { rctx->bmpversion=5; if(!decode_v3_header_fields(rctx,buf)) goto done; if(!decode_v4_header_fields(rctx,buf)) goto done; if(!decode_v5_header_fields(rctx,buf)) goto done; } else { iw_set_error(rctx->ctx,"Unsupported BMP version"); goto done; } if(!iw_check_image_dimensions(rctx->ctx,rctx->width,rctx->height)) { goto done; } retval = 1; done: return retval; } // Find the highest/lowest bit that is set. static int find_high_bit(unsigned int x) { int i; for(i=31;i>=0;i--) { if(x&(1<<i)) return i; } return 0; } static int find_low_bit(unsigned int x) { int i; for(i=0;i<=31;i++) { if(x&(1<<i)) return i; } return 0; } // Given .bf_mask[k], set high_bit[k], low_bit[k], etc. static int process_bf_mask(struct iwbmprcontext *rctx, int k) { // The bits representing the mask for each channel are required to be // contiguous, so all we need to do is find the highest and lowest bit. rctx->bf_high_bit[k] = find_high_bit(rctx->bf_mask[k]); rctx->bf_low_bit[k] = find_low_bit(rctx->bf_mask[k]); rctx->bf_bits_count[k] = 1+rctx->bf_high_bit[k]-rctx->bf_low_bit[k]; // Check if the mask specifies an invalid bit if(rctx->bf_high_bit[k] > (int)(rctx->bitcount-1)) return 0; if(rctx->bf_bits_count[k]>16) { // We only support up to 16 bits. Ignore any bits after the 16th. rctx->bf_low_bit[k] = rctx->bf_high_bit[k]-15; rctx->bf_bits_count[k] = 16; } if(rctx->bf_bits_count[k]>8) { rctx->need_16bit = 1; } return 1; } static int iwbmp_read_bitfields(struct iwbmprcontext *rctx) { iw_byte buf[12]; int k; if(!iwbmp_read(rctx,buf,12)) return 0; for(k=0;k<3;k++) { rctx->bf_mask[k] = iw_get_ui32le(&buf[k*4]); if(rctx->bf_mask[k]==0) return 0; // Find the high bit, low bit, etc. if(!process_bf_mask(rctx,k)) return 0; } return 1; } static void iwbmp_set_default_bitfields(struct iwbmprcontext *rctx) { int k; if(rctx->bitfields_set) return; if(rctx->bitcount==16) { // Default is 5 bits for each channel. rctx->bf_mask[0]=0x7c00; // 01111100 00000000 (red) rctx->bf_mask[1]=0x03e0; // 00000011 11100000 (green) rctx->bf_mask[2]=0x001f; // 00000000 00011111 (blue) } else if(rctx->bitcount==32) { rctx->bf_mask[0]=0x00ff0000; rctx->bf_mask[1]=0x0000ff00; rctx->bf_mask[2]=0x000000ff; } else { return; } for(k=0;k<3;k++) { process_bf_mask(rctx,k); } } static int iwbmp_read_palette(struct iwbmprcontext *rctx) { size_t i; iw_byte buf[4*256]; size_t b; unsigned int valid_palette_entries; size_t valid_palette_nbytes; b = (rctx->bmpversion==2) ? 3 : 4; // bytes per palette entry if(rctx->infoheader_size==64) { // According to what little documentation I can find, OS/2v2 BMP files // have 4 bytes per palette entry. But some of the files I've seen have // only 3. This is a little hack to support them. if(rctx->fileheader_size + rctx->infoheader_size + rctx->palette_entries*3 == rctx->bfOffBits) { iw_warning(rctx->ctx,"BMP bitmap overlaps colormap; assuming colormap uses 3 bytes per entry instead of 4"); b = 3; rctx->palette_nbytes = 3*rctx->palette_entries; } } // If the palette has >256 colors, only use the first 256. valid_palette_entries = (rctx->palette_entries<=256) ? rctx->palette_entries : 256; valid_palette_nbytes = valid_palette_entries * b; if(!iwbmp_read(rctx,buf,valid_palette_nbytes)) return 0; rctx->palette.num_entries = valid_palette_entries; for(i=0;i<valid_palette_entries;i++) { rctx->palette.entry[i].b = buf[i*b+0]; rctx->palette.entry[i].g = buf[i*b+1]; rctx->palette.entry[i].r = buf[i*b+2]; rctx->palette.entry[i].a = 255; } // If the palette is oversized, skip over the unused part of it. if(rctx->palette_nbytes > valid_palette_nbytes) { iwbmp_skip_bytes(rctx, rctx->palette_nbytes - valid_palette_nbytes); } return 1; } static void bmpr_convert_row_32_16(struct iwbmprcontext *rctx, const iw_byte *src, size_t row) { int i,k; unsigned int v,x; int numchannels; numchannels = rctx->has_alpha_channel ? 4 : 3; for(i=0;i<rctx->width;i++) { if(rctx->bitcount==32) { x = ((unsigned int)src[i*4+0]) | ((unsigned int)src[i*4+1])<<8 | ((unsigned int)src[i*4+2])<<16 | ((unsigned int)src[i*4+3])<<24; } else { // 16 x = ((unsigned int)src[i*2+0]) | ((unsigned int)src[i*2+1])<<8; } v = 0; for(k=0;k<numchannels;k++) { // For red, green, blue [, alpha]: v = x & rctx->bf_mask[k]; if(rctx->bf_low_bit[k]>0) v >>= rctx->bf_low_bit[k]; if(rctx->img->bit_depth==16) { rctx->img->pixels[row*rctx->img->bpr + i*numchannels*2 + k*2+0] = (iw_byte)(v>>8); rctx->img->pixels[row*rctx->img->bpr + i*numchannels*2 + k*2+1] = (iw_byte)(v&0xff); } else { rctx->img->pixels[row*rctx->img->bpr + i*numchannels + k] = (iw_byte)v; } } } } static void bmpr_convert_row_24(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; for(i=0;i<rctx->width;i++) { rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = src[i*3+2]; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = src[i*3+1]; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = src[i*3+0]; } } static void bmpr_convert_row_8(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; for(i=0;i<rctx->width;i++) { rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[src[i]].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[src[i]].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[src[i]].b; } } static void bmpr_convert_row_4(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (i&0x1) ? src[i/2]&0x0f : src[i/2]>>4; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static void bmpr_convert_row_2(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (src[i/4]>>(2*(3-i%4)))&0x03; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static void bmpr_convert_row_1(struct iwbmprcontext *rctx,const iw_byte *src, size_t row) { int i; int pal_index; for(i=0;i<rctx->width;i++) { pal_index = (src[i/8] & (1<<(7-i%8))) ? 1 : 0; rctx->img->pixels[row*rctx->img->bpr + i*3 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[row*rctx->img->bpr + i*3 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[row*rctx->img->bpr + i*3 + 2] = rctx->palette.entry[pal_index].b; } } static int bmpr_read_uncompressed(struct iwbmprcontext *rctx) { iw_byte *rowbuf = NULL; size_t bmp_bpr; int j; int retval = 0; if(rctx->has_alpha_channel) { rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = rctx->need_16bit ? 16 : 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,4*rctx->img->bit_depth); } else { rctx->img->imgtype = IW_IMGTYPE_RGB; rctx->img->bit_depth = rctx->need_16bit ? 16 : 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,3*rctx->img->bit_depth); } bmp_bpr = iwbmp_calc_bpr(rctx->bitcount,rctx->width); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; rowbuf = iw_malloc(rctx->ctx,bmp_bpr); for(j=0;j<rctx->img->height;j++) { // Read a row of the BMP file. if(!iwbmp_read(rctx,rowbuf,bmp_bpr)) { goto done; } switch(rctx->bitcount) { case 32: case 16: bmpr_convert_row_32_16(rctx,rowbuf,j); break; case 24: bmpr_convert_row_24(rctx,rowbuf,j); break; case 8: bmpr_convert_row_8(rctx,rowbuf,j); break; case 4: bmpr_convert_row_4(rctx,rowbuf,j); break; case 2: bmpr_convert_row_2(rctx,rowbuf,j); break; case 1: bmpr_convert_row_1(rctx,rowbuf,j); break; } } retval = 1; done: if(rowbuf) iw_free(rctx->ctx,rowbuf); return retval; } // Read and decompress RLE8 or RLE4-compressed bits, and write pixels to // rctx->img->pixels. static int bmpr_read_rle_internal(struct iwbmprcontext *rctx) { int retval = 0; int pos_x, pos_y; iw_byte buf[255]; size_t n_pix; size_t n_bytes; size_t i; size_t pal_index; // The position of the next pixel to set. // pos_y is in IW coordinates (top=0), not BMP coordinates (bottom=0). pos_x = 0; pos_y = 0; // Initially make all pixels transparent, so that any any pixels we // don't modify will be transparent. iw_zeromem(rctx->img->pixels,rctx->img->bpr*rctx->img->height); while(1) { // If we've reached the end of the bitmap, stop. if(pos_y>rctx->img->height-1) break; if(pos_y==rctx->img->height-1 && pos_x>=rctx->img->width) break; if(!iwbmp_read(rctx,buf,2)) goto done; if(buf[0]==0) { if(buf[1]==0) { // End of Line pos_y++; pos_x=0; } else if(buf[1]==1) { // (Premature) End of Bitmap break; } else if(buf[1]==2) { // DELTA: The next two bytes are unsigned values representing // the relative position of the next pixel from the "current // position". // I interpret "current position" to mean the position at which // the next pixel would normally have been. if(!iwbmp_read(rctx,buf,2)) goto done; if(pos_x<rctx->img->width) pos_x += buf[0]; pos_y += buf[1]; } else { // A uncompressed segment n_pix = (size_t)buf[1]; // Number of uncompressed pixels which follow if(rctx->compression==IWBMP_BI_RLE4) { n_bytes = ((n_pix+3)/4)*2; } else { n_bytes = ((n_pix+1)/2)*2; } if(!iwbmp_read(rctx,buf,n_bytes)) goto done; for(i=0;i<n_pix;i++) { if(pos_x<rctx->img->width) { if(rctx->compression==IWBMP_BI_RLE4) { pal_index = (i%2) ? buf[i/2]&0x0f : buf[i/2]>>4; } else { pal_index = buf[i]; } rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 2] = rctx->palette.entry[pal_index].b; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 3] = 255; pos_x++; } } } } else { // An RLE-compressed segment n_pix = (size_t)buf[0]; for(i=0;i<n_pix;i++) { if(pos_x<rctx->img->width) { if(rctx->compression==IWBMP_BI_RLE4) { pal_index = (i%2) ? buf[1]&0x0f : buf[1]>>4; } else { pal_index = buf[1]; } rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 0] = rctx->palette.entry[pal_index].r; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 1] = rctx->palette.entry[pal_index].g; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 2] = rctx->palette.entry[pal_index].b; rctx->img->pixels[rctx->img->bpr*pos_y + pos_x*4 + 3] = 255; pos_x++; } } } } retval = 1; done: return retval; } static int bmpr_has_transparency(struct iw_image *img) { int i,j; if(img->imgtype!=IW_IMGTYPE_RGBA) return 0; for(j=0;j<img->height;j++) { for(i=0;i<img->width;i++) { if(img->pixels[j*img->bpr + i*4 + 3] != 255) return 1; } } return 0; } // Remove the alpha channel. // This doesn't free the extra memory used by the alpha channel, it just // moves the pixels around in-place. static void bmpr_strip_alpha(struct iw_image *img) { int i,j; size_t oldbpr; img->imgtype = IW_IMGTYPE_RGB; oldbpr = img->bpr; img->bpr = iw_calc_bytesperrow(img->width,24); for(j=0;j<img->height;j++) { for(i=0;i<img->width;i++) { img->pixels[j*img->bpr + i*3 + 0] = img->pixels[j*oldbpr + i*4 + 0]; img->pixels[j*img->bpr + i*3 + 1] = img->pixels[j*oldbpr + i*4 + 1]; img->pixels[j*img->bpr + i*3 + 2] = img->pixels[j*oldbpr + i*4 + 2]; } } } static int bmpr_read_rle(struct iwbmprcontext *rctx) { int retval = 0; if(!(rctx->compression==IWBMP_BI_RLE8 && rctx->bitcount==8) && !(rctx->compression==IWBMP_BI_RLE4 && rctx->bitcount==4)) { iw_set_error(rctx->ctx,"Compression type incompatible with image type"); } if(rctx->topdown) { // The documentation says that top-down images may not be compressed. iw_set_error(rctx->ctx,"Compression not allowed with top-down images"); } // RLE-compressed BMP images don't have to assign a color to every pixel, // and it's reasonable to interpret undefined pixels as transparent. // I'm not going to worry about handling compressed BMP images as // efficiently as possible, so start with an RGBA image, and convert to // RGB format later if (as is almost always the case) there was no // transparency. rctx->img->imgtype = IW_IMGTYPE_RGBA; rctx->img->bit_depth = 8; rctx->img->bpr = iw_calc_bytesperrow(rctx->width,32); rctx->img->pixels = (iw_byte*)iw_malloc_large(rctx->ctx,rctx->img->bpr,rctx->img->height); if(!rctx->img->pixels) goto done; if(!bmpr_read_rle_internal(rctx)) goto done; if(!bmpr_has_transparency(rctx->img)) { bmpr_strip_alpha(rctx->img); } retval = 1; done: return retval; } static int iwbmp_read_bits(struct iwbmprcontext *rctx) { int retval = 0; rctx->img->width = rctx->width; rctx->img->height = rctx->height; // If applicable, use the fileheader's "bits offset" field to locate the // bitmap bits. if(rctx->fileheader_size>0) { size_t expected_offbits; expected_offbits = rctx->fileheader_size + rctx->infoheader_size + rctx->bitfields_nbytes + rctx->palette_nbytes; if(rctx->bfOffBits==expected_offbits) { ; } else if(rctx->bfOffBits>expected_offbits && rctx->bfOffBits<1000000) { // Apparently, there's some extra space between the header data and // the bits. If it's not unreasonably large, skip over it. if(!iwbmp_skip_bytes(rctx, rctx->bfOffBits - expected_offbits)) goto done; } else { iw_set_error(rctx->ctx,"Invalid BMP bits offset"); goto done; } } if(rctx->compression==IWBMP_BI_RGB) { if(!bmpr_read_uncompressed(rctx)) goto done; } else if(rctx->compression==IWBMP_BI_RLE8 || rctx->compression==IWBMP_BI_RLE4) { if(!bmpr_read_rle(rctx)) goto done; } else { iw_set_errorf(rctx->ctx,"Unsupported BMP compression or image type (%d)",(int)rctx->compression); goto done; } retval = 1; done: return retval; } static void iwbmpr_misc_config(struct iw_context *ctx, struct iwbmprcontext *rctx) { // Have IW flip the image, if necessary. if(!rctx->topdown) { iw_reorient_image(ctx,IW_REORIENT_FLIP_V); } // Tell IW the colorspace. iw_set_input_colorspace(ctx,&rctx->csdescr); // Tell IW the significant bits. if(rctx->bitcount==16 || rctx->bitcount==32) { if(rctx->bf_bits_count[0]!=8 || rctx->bf_bits_count[1]!=8 || rctx->bf_bits_count[2]!=8 || (IW_IMGTYPE_HAS_ALPHA(rctx->img->imgtype) && rctx->bf_bits_count[3]!=8)) { iw_set_input_max_color_code(ctx,0, (1 << rctx->bf_bits_count[0])-1 ); iw_set_input_max_color_code(ctx,1, (1 << rctx->bf_bits_count[1])-1 ); iw_set_input_max_color_code(ctx,2, (1 << rctx->bf_bits_count[2])-1 ); if(IW_IMGTYPE_HAS_ALPHA(rctx->img->imgtype)) { iw_set_input_max_color_code(ctx,3, (1 << rctx->bf_bits_count[3])-1 ); } } } } IW_IMPL(int) iw_read_bmp_file(struct iw_context *ctx, struct iw_iodescr *iodescr) { struct iwbmprcontext rctx; struct iw_image img; int retval = 0; iw_zeromem(&rctx,sizeof(struct iwbmprcontext)); iw_zeromem(&img,sizeof(struct iw_image)); rctx.ctx = ctx; rctx.img = &img; rctx.iodescr = iodescr; // Start with a default sRGB colorspace. This may be overridden later. iw_make_srgb_csdescr_2(&rctx.csdescr); rctx.has_fileheader = !iw_get_value(ctx,IW_VAL_BMP_NO_FILEHEADER); if(rctx.has_fileheader) { if(!iwbmp_read_file_header(&rctx)) goto done; } if(!iwbmp_read_info_header(&rctx)) goto done; iwbmp_set_default_bitfields(&rctx); if(rctx.bitfields_nbytes>0) { if(!iwbmp_read_bitfields(&rctx)) goto done; } if(rctx.palette_entries>0) { if(!iwbmp_read_palette(&rctx)) goto done; } if(!iwbmp_read_bits(&rctx)) goto done; iw_set_input_image(ctx, &img); iwbmpr_misc_config(ctx, &rctx); retval = 1; done: if(!retval) { iw_set_error(ctx,"BMP read failed"); // If we didn't call iw_set_input_image, 'img' still belongs to us, // so free its contents. iw_free(ctx, img.pixels); } return retval; } struct iwbmpwcontext { int bmpversion; int include_file_header; int bitcount; int palentries; int compressed; int uses_bitfields; size_t header_size; size_t bitfields_size; size_t palsize; size_t unc_dst_bpr; size_t unc_bitssize; struct iw_iodescr *iodescr; struct iw_context *ctx; struct iw_image *img; const struct iw_palette *pal; size_t total_written; int bf_amt_to_shift[4]; // For 16-bit images unsigned int bf_mask[4]; unsigned int maxcolor[4]; // R, G, B -- For 16-bit images. struct iw_csdescr csdescr; int no_cslabel; }; static void iwbmp_write(struct iwbmpwcontext *wctx, const void *buf, size_t n) { (*wctx->iodescr->write_fn)(wctx->ctx,wctx->iodescr,buf,n); wctx->total_written+=n; } static void bmpw_convert_row_1(const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; int m; for(i=0;i<width;i++) { m = i%8; if(m==0) dstrow[i/8] = srcrow[i]<<7; else dstrow[i/8] |= srcrow[i]<<(7-m); } } static void bmpw_convert_row_4(const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; for(i=0;i<width;i++) { if(i%2==0) dstrow[i/2] = srcrow[i]<<4; else dstrow[i/2] |= srcrow[i]; } } static void bmpw_convert_row_8(const iw_byte *srcrow, iw_byte *dstrow, int width) { memcpy(dstrow,srcrow,width); } static void bmpw_convert_row_16_32(struct iwbmpwcontext *wctx, const iw_byte *srcrow, iw_byte *dstrow, int width) { int i,k; unsigned int v; int num_src_samples; unsigned int src_sample[4]; for(k=0;k<4;k++) src_sample[k]=0; num_src_samples = iw_imgtype_num_channels(wctx->img->imgtype); for(i=0;i<width;i++) { // Read the source samples into a convenient format. for(k=0;k<num_src_samples;k++) { if(wctx->img->bit_depth==16) { src_sample[k] = (srcrow[num_src_samples*2*i + k*2]<<8) | srcrow[num_src_samples*2*i + k*2 +1]; } else { src_sample[k] = srcrow[num_src_samples*i + k]; } } // Pack the pixels' bits into a single int. switch(wctx->img->imgtype) { case IW_IMGTYPE_GRAY: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[0] << wctx->bf_amt_to_shift[1]; v |= src_sample[0] << wctx->bf_amt_to_shift[2]; break; case IW_IMGTYPE_RGBA: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[1] << wctx->bf_amt_to_shift[1]; v |= src_sample[2] << wctx->bf_amt_to_shift[2]; v |= src_sample[3] << wctx->bf_amt_to_shift[3]; break; case IW_IMGTYPE_GRAYA: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[0] << wctx->bf_amt_to_shift[1]; v |= src_sample[0] << wctx->bf_amt_to_shift[2]; v |= src_sample[1] << wctx->bf_amt_to_shift[3]; break; default: v = src_sample[0] << wctx->bf_amt_to_shift[0]; v |= src_sample[1] << wctx->bf_amt_to_shift[1]; v |= src_sample[2] << wctx->bf_amt_to_shift[2]; } // Split the int into bytes, and write it to the target image. if(wctx->bitcount==32) { dstrow[i*4+0] = (iw_byte)(v&0xff); dstrow[i*4+1] = (iw_byte)((v&0x0000ff00)>>8); dstrow[i*4+2] = (iw_byte)((v&0x00ff0000)>>16); dstrow[i*4+3] = (iw_byte)((v&0xff000000)>>24); } else { dstrow[i*2+0] = (iw_byte)(v&0xff); dstrow[i*2+1] = (iw_byte)(v>>8); } } } static void bmpw_convert_row_24(struct iwbmpwcontext *wctx, const iw_byte *srcrow, iw_byte *dstrow, int width) { int i; if(wctx->img->imgtype==IW_IMGTYPE_GRAY) { for(i=0;i<width;i++) { dstrow[i*3+0] = srcrow[i]; dstrow[i*3+1] = srcrow[i]; dstrow[i*3+2] = srcrow[i]; } } else { // RGB for(i=0;i<width;i++) { dstrow[i*3+0] = srcrow[i*3+2]; dstrow[i*3+1] = srcrow[i*3+1]; dstrow[i*3+2] = srcrow[i*3+0]; } } } static void iwbmp_write_file_header(struct iwbmpwcontext *wctx) { iw_byte fileheader[14]; if(!wctx->include_file_header) return; iw_zeromem(fileheader,sizeof(fileheader)); fileheader[0] = 66; // 'B' fileheader[1] = 77; // 'M' // This will be overwritten later, if the bitmap was compressed. iw_set_ui32le(&fileheader[ 2], (unsigned int)(14+wctx->header_size+ wctx->bitfields_size+wctx->palsize+wctx->unc_bitssize)); // bfSize iw_set_ui32le(&fileheader[10],(unsigned int)(14+wctx->header_size+ wctx->bitfields_size+wctx->palsize)); // bfOffBits iwbmp_write(wctx,fileheader,14); } static int iwbmp_write_bmp_v2header(struct iwbmpwcontext *wctx) { iw_byte header[12]; if(wctx->img->width>65535 || wctx->img->height>65535) { iw_set_error(wctx->ctx,"Output image is too large for this BMP version"); return 0; } iw_zeromem(header,sizeof(header)); iw_set_ui32le(&header[ 0],12); // bcSize iw_set_ui16le(&header[ 4],wctx->img->width); // bcWidth iw_set_ui16le(&header[ 6],wctx->img->height); // bcHeight iw_set_ui16le(&header[ 8],1); // bcPlanes iw_set_ui16le(&header[10],wctx->bitcount); // bcBitCount iwbmp_write(wctx,header,12); return 1; } static int iwbmp_write_bmp_v3header(struct iwbmpwcontext *wctx) { unsigned int dens_x, dens_y; unsigned int cmpr; iw_byte header[40]; iw_zeromem(header,sizeof(header)); iw_set_ui32le(&header[ 0],(unsigned int)wctx->header_size); // biSize iw_set_ui32le(&header[ 4],wctx->img->width); // biWidth iw_set_ui32le(&header[ 8],wctx->img->height); // biHeight iw_set_ui16le(&header[12],1); // biPlanes iw_set_ui16le(&header[14],wctx->bitcount); // biBitCount cmpr = IWBMP_BI_RGB; if(wctx->compressed) { if(wctx->bitcount==8) cmpr = IWBMP_BI_RLE8; else if(wctx->bitcount==4) cmpr = IWBMP_BI_RLE4; } else if(wctx->uses_bitfields) { cmpr = IWBMP_BI_BITFIELDS; } iw_set_ui32le(&header[16],cmpr); // biCompression iw_set_ui32le(&header[20],(unsigned int)wctx->unc_bitssize); // biSizeImage if(wctx->img->density_code==IW_DENSITY_UNITS_PER_METER) { dens_x = (unsigned int)(0.5+wctx->img->density_x); dens_y = (unsigned int)(0.5+wctx->img->density_y); } else { dens_x = dens_y = 2835; } iw_set_ui32le(&header[24],dens_x); // biXPelsPerMeter iw_set_ui32le(&header[28],dens_y); // biYPelsPerMeter iw_set_ui32le(&header[32],wctx->palentries); // biClrUsed //iw_set_ui32le(&header[36],0); // biClrImportant iwbmp_write(wctx,header,40); return 1; } static int iwbmp_write_bmp_v45header_fields(struct iwbmpwcontext *wctx) { iw_byte header[124]; unsigned int intent_bmp_style; iw_zeromem(header,sizeof(header)); if(wctx->uses_bitfields) { iw_set_ui32le(&header[40],wctx->bf_mask[0]); iw_set_ui32le(&header[44],wctx->bf_mask[1]); iw_set_ui32le(&header[48],wctx->bf_mask[2]); iw_set_ui32le(&header[52],wctx->bf_mask[3]); } // Colorspace Type // TODO: We could support CSTYPE_GAMMA by using LCS_CALIBRATED_RGB, // but documentation about how to do that is hard to find. if(wctx->csdescr.cstype==IW_CSTYPE_SRGB && !wctx->no_cslabel) iw_set_ui32le(&header[56],IWBMPCS_SRGB); else iw_set_ui32le(&header[56],IWBMPCS_DEVICE_RGB); // Intent //intent_bmp_style = 4; // Perceptual //if(wctx->csdescr.cstype==IW_CSTYPE_SRGB && !wctx->no_cslabel) { switch(wctx->img->rendering_intent) { case IW_INTENT_PERCEPTUAL: intent_bmp_style = 4; break; case IW_INTENT_RELATIVE: intent_bmp_style = 2; break; case IW_INTENT_SATURATION: intent_bmp_style = 1; break; case IW_INTENT_ABSOLUTE: intent_bmp_style = 8; break; default: intent_bmp_style = 4; } //} iw_set_ui32le(&header[108],intent_bmp_style); iwbmp_write(wctx,&header[40],124-40); return 1; } static int iwbmp_write_bmp_header(struct iwbmpwcontext *wctx) { if(wctx->bmpversion==2) { return iwbmp_write_bmp_v2header(wctx); } else if(wctx->bmpversion==5) { if(!iwbmp_write_bmp_v3header(wctx)) return 0; return iwbmp_write_bmp_v45header_fields(wctx); } return iwbmp_write_bmp_v3header(wctx); } // Given wctx->maxcolor[*], sets -> bf_mask[*] and bf_amt_to_shift[*], // and sets wctx->bitcount (to 16 or 32). static int iwbmp_calc_bitfields_masks(struct iwbmpwcontext *wctx, int num_masks) { int k; int bits[4]; // R, G, B, A int tot_bits = 0; for(k=0;k<num_masks;k++) { bits[k] = iw_max_color_to_bitdepth(wctx->maxcolor[k]); tot_bits += bits[k]; } if(tot_bits > 32) { iw_set_error(wctx->ctx,"Cannot write a BMP image in this color format"); return 0; } wctx->bitcount = (tot_bits>16) ? 32 : 16; wctx->bf_amt_to_shift[0] = bits[1] + bits[2]; wctx->bf_amt_to_shift[1] = bits[2]; wctx->bf_amt_to_shift[2] = 0; if(num_masks>3) wctx->bf_amt_to_shift[3] = bits[0] + bits[1] + bits[2]; for(k=0;k<num_masks;k++) { wctx->bf_mask[k] = wctx->maxcolor[k] << wctx->bf_amt_to_shift[k]; } return 1; } // Write the BITFIELDS segment, and set the wctx->bf_amt_to_shift[] values. static int iwbmp_write_bitfields(struct iwbmpwcontext *wctx) { iw_byte buf[12]; int k; if(wctx->bitcount!=16 && wctx->bitcount!=32) return 0; for(k=0;k<3;k++) { iw_set_ui32le(&buf[4*k],wctx->bf_mask[k]); } iwbmp_write(wctx,buf,12); return 1; } static void iwbmp_write_palette(struct iwbmpwcontext *wctx) { int i,k; iw_byte buf[4]; if(wctx->palentries<1) return; buf[3] = 0; // Reserved field; always 0. for(i=0;i<wctx->palentries;i++) { if(i<wctx->pal->num_entries) { if(wctx->pal->entry[i].a == 0) { // A transparent color. Because of the way we handle writing // transparent BMP images, the first palette entry may be a // fully transparent color, whose index will not be used when // we write the image. But many apps will interpret our // "transparent" pixels as having color #0. So, set it to // the background label color if available, otherwise to an // arbitrary high-contrast color (magenta). if(wctx->img->has_bkgdlabel) { for(k=0;k<3;k++) { buf[k] = (iw_byte)iw_color_get_int_sample(&wctx->img->bkgdlabel,2-k,255); } } else { buf[0] = 255; buf[1] = 0; buf[2] = 255; } } else { buf[0] = wctx->pal->entry[i].b; buf[1] = wctx->pal->entry[i].g; buf[2] = wctx->pal->entry[i].r; } } else { buf[0] = buf[1] = buf[2] = 0; } if(wctx->bmpversion==2) iwbmp_write(wctx,buf,3); // v2 BMPs don't have the 'reserved' field. else iwbmp_write(wctx,buf,4); } } struct rle_context { struct iw_context *ctx; struct iwbmpwcontext *wctx; const iw_byte *srcrow; size_t img_width; int cur_row; // current row; 0=top (last) // Position in srcrow of the first byte that hasn't been written to the // output file size_t pending_data_start; // Current number of uncompressible bytes that haven't been written yet // (starting at pending_data_start) size_t unc_len; // Current number of identical bytes that haven't been written yet // (starting at pending_data_start+unc_len) size_t run_len; // The value of the bytes referred to by run_len. // Valid if run_len>0. iw_byte run_byte; size_t total_bytes_written; // Bytes written, after compression }; //============================ RLE8 encoder ============================ // TODO: The RLE8 and RLE4 encoders are more different than they should be. // The RLE8 encoder could probably be made more similar to the (more // complicated) RLE4 encoder. static void rle8_write_unc(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; if(rlectx->unc_len<1) return; if(rlectx->unc_len>=3 && (rlectx->unc_len&1)) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 4"); return; } if(rlectx->unc_len>254) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 5"); return; } if(rlectx->unc_len<3) { // The minimum length for a noncompressed run is 3. For shorter runs // write them "compressed". for(i=0;i<rlectx->unc_len;i++) { dstbuf[0] = 0x01; // count dstbuf[1] = rlectx->srcrow[i+rlectx->pending_data_start]; // value iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; } } else { dstbuf[0] = 0x00; dstbuf[1] = (iw_byte)rlectx->unc_len; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; iwbmp_write(rlectx->wctx,&rlectx->srcrow[rlectx->pending_data_start],rlectx->unc_len); rlectx->total_bytes_written+=rlectx->unc_len; if(rlectx->unc_len&0x1) { // Need a padding byte if the length was odd. (This shouldn't // happen, because we never write odd-length UNC segments.) dstbuf[0] = 0x00; iwbmp_write(rlectx->wctx,dstbuf,1); rlectx->total_bytes_written+=1; } } rlectx->pending_data_start+=rlectx->unc_len; rlectx->unc_len=0; } static void rle8_write_unc_and_run(struct rle_context *rlectx) { iw_byte dstbuf[2]; rle8_write_unc(rlectx); if(rlectx->run_len<1) { return; } if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 6"); return; } dstbuf[0] = (iw_byte)rlectx->run_len; dstbuf[1] = rlectx->run_byte; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; rlectx->pending_data_start+=rlectx->run_len; rlectx->run_len=0; } static void rle_write_trns(struct rle_context *rlectx, int num_trns) { iw_byte dstbuf[4]; int num_remaining = num_trns; int num_to_write; while(num_remaining>0) { num_to_write = num_remaining; if(num_to_write>255) num_to_write=255; dstbuf[0]=0x00; // 00 02 = Delta dstbuf[1]=0x02; dstbuf[2]=(iw_byte)num_to_write; // X offset dstbuf[3]=0x00; // Y offset iwbmp_write(rlectx->wctx,dstbuf,4); rlectx->total_bytes_written+=4; num_remaining -= num_to_write; } rlectx->pending_data_start += num_trns; } // The RLE format used by BMP files is pretty simple, but I've gone to some // effort to optimize it for file size, which makes for a complicated // algorithm. // The overall idea: // We defer writing data until certain conditions are met. In the meantime, // we split the unwritten data into two segments: // "UNC": data classified as uncompressible // "RUN": data classified as compressible. All bytes in this segment must be // identical. // The RUN segment always follows the UNC segment. // For each byte in turn, we examine the current state, and do one of a number // of things, such as: // - add it to RUN // - add it to UNC (if there is no RUN) // - move RUN into UNC, then add it to RUN (or to UNC) // - move UNC and RUN to the file, then make it the new RUN // Then, we check to see if we've accumulated enough data that something needs // to be written out. static int rle8_compress_row(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; iw_byte next_byte; int next_pix_is_trns; int num_trns = 0; // number of consecutive transparent pixels seen int retval = 0; rlectx->pending_data_start=0; rlectx->unc_len=0; rlectx->run_len=0; for(i=0;i<rlectx->img_width;i++) { // Read the next byte. next_byte = rlectx->srcrow[i]; next_pix_is_trns = (rlectx->wctx->pal->entry[next_byte].a==0); if(num_trns>0 && !next_pix_is_trns) { rle_write_trns(rlectx,num_trns); num_trns=0; } else if(next_pix_is_trns) { if (rlectx->unc_len>0 || rlectx->run_len>0) { rle8_write_unc_and_run(rlectx); } num_trns++; continue; } // -------------------------------------------------------------- // Add the byte we just read to either the UNC or the RUN data. if(rlectx->run_len>0 && next_byte==rlectx->run_byte) { // Byte fits in the current run; add it. rlectx->run_len++; } else if(rlectx->run_len==0) { // We don't have a RUN, so we can put this byte there. rlectx->run_len = 1; rlectx->run_byte = next_byte; } else if(rlectx->unc_len==0 && rlectx->run_len==1) { // We have one previous byte, and it's different from this one. // Move it to UNC, and make this one the RUN. rlectx->unc_len++; rlectx->run_byte = next_byte; } else if(rlectx->unc_len>0 && rlectx->run_len<(rlectx->unc_len==1 ? 3U : 4U)) { // We have a run, but it's not long enough to be beneficial. // Convert it to uncompressed bytes. // A good rule is that a run length of 4 or more (3 or more if // unc_len=1) should always be run-legth encoded. rlectx->unc_len += rlectx->run_len; rlectx->run_len = 0; // If UNC is now odd and >1, add the next byte to it to make it even. // Otherwise, add it to RUN. if(rlectx->unc_len>=3 && (rlectx->unc_len&0x1)) { rlectx->unc_len++; } else { rlectx->run_len = 1; rlectx->run_byte = next_byte; } } else { // Nowhere to put the byte: write out everything, and start fresh. rle8_write_unc_and_run(rlectx); rlectx->run_len = 1; rlectx->run_byte = next_byte; } // -------------------------------------------------------------- // If we hit certain high water marks, write out the current data. if(rlectx->unc_len>=254) { // Our maximum size for an UNC segment. rle8_write_unc(rlectx); } else if(rlectx->unc_len>0 && (rlectx->unc_len+rlectx->run_len)>254) { // It will not be possible to coalesce the RUN into the UNC (it // would be too big) so write out the UNC. rle8_write_unc(rlectx); } else if(rlectx->run_len>=255) { // The maximum size for an RLE segment. rle8_write_unc_and_run(rlectx); } // -------------------------------------------------------------- // Sanity checks. These can be removed if we're sure the algorithm // is bug-free. // We don't allow unc_len to be odd (except temporarily), except // that it can be 1. // What's special about 1 is that if we add another byte to it, it // increases the cost. For 3,5,...,253, we can add another byte for // free, so we should never fail to do that. if((rlectx->unc_len&0x1) && rlectx->unc_len!=1) { iw_set_errorf(rlectx->ctx,"Internal: BMP RLE encode error 1"); goto done; } // unc_len can be at most 252 at this point. // If it were 254, it should have been written out already. if(rlectx->unc_len>252) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 2"); goto done; } // run_len can be at most 254 at this point. // If it were 255, it should have been written out already. if(rlectx->run_len>254) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 3"); goto done; } } // End of row. Write out anything left over. rle8_write_unc_and_run(rlectx); // Write an end-of-line marker (0 0), or if this is the last row, // an end-of-bitmap marker (0 1). dstbuf[0]=0x00; dstbuf[1]= (rlectx->cur_row==0)? 0x01 : 0x00; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; retval = 1; done: return retval; } //============================ RLE4 encoder ============================ // Calculate the most efficient way to split a run of uncompressible pixels. // This only finds the first place to split the run. If the run is still // over 255 pixels, call it again to find the next split. static size_t rle4_get_best_unc_split(size_t n) { // For <=255 pixels, we can never do better than storing it as one run. if(n<=255) return n; // With runs of 252, we can store 252/128 = 1.96875 pixels/byte. // With runs of 255, we can store 255/130 = 1.96153 pixels/byte. // Hence, using runs of 252 is the most efficient way to store a large // number of uncompressible pixels. // (Lengths other than 252 or 255 are no help.) // However, there are three exceptional cases where, if we split at 252, // the most efficient encoding will no longer be possible: if(n==257 || n==510 || n==765) return 255; return 252; } // Returns the incremental cost of adding a pixel to the current UNC // (which is always either 0 or 2). // To derive this function, I calculated the optimal cost of every length, // and enumerated the exceptions to the (n%4)?0:2 rule. // The exceptions are mostly caused by the cases where // rle4_get_best_unc_split() returns 255 instead of 252. static int rle4_get_incr_unc_cost(struct rle_context *rlectx) { int n; int m; n = (int)rlectx->unc_len; if(n==2 || n==255 || n==257 || n==507 || n==510) return 2; if(n==256 || n==508) return 0; if(n>=759) { m = n%252; if(m==3 || m==6 || m==9) return 2; if(m==4 || m==8) return 0; } return (n%4)?0:2; } static void rle4_write_unc(struct rle_context *rlectx) { iw_byte dstbuf[128]; size_t pixels_to_write; size_t bytes_to_write; if(rlectx->unc_len<1) return; // Note that, unlike the RLE8 encoder, we allow this function to be called // with uncompressed runs of arbitrary length. while(rlectx->unc_len>0) { pixels_to_write = rle4_get_best_unc_split(rlectx->unc_len); if(pixels_to_write<3) { // The minimum length for an uncompressed run is 3. For shorter runs // write them "compressed". dstbuf[0] = (iw_byte)pixels_to_write; dstbuf[1] = (rlectx->srcrow[rlectx->pending_data_start]<<4); if(pixels_to_write>1) dstbuf[1] |= (rlectx->srcrow[rlectx->pending_data_start+1]); // The actual writing will occur below. Just indicate how many bytes // of dstbuf[] to write. bytes_to_write = 2; } else { size_t i; // Write the length of the uncompressed run. dstbuf[0] = 0x00; dstbuf[1] = (iw_byte)pixels_to_write; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; // Put the data to write in dstbuf[]. bytes_to_write = 2*((pixels_to_write+3)/4); iw_zeromem(dstbuf,bytes_to_write); for(i=0;i<pixels_to_write;i++) { if(i&0x1) dstbuf[i/2] |= rlectx->srcrow[rlectx->pending_data_start+i]; else dstbuf[i/2] = rlectx->srcrow[rlectx->pending_data_start+i]<<4; } } iwbmp_write(rlectx->wctx,dstbuf,bytes_to_write); rlectx->total_bytes_written += bytes_to_write; rlectx->unc_len -= pixels_to_write; rlectx->pending_data_start += pixels_to_write; } } static void rle4_write_unc_and_run(struct rle_context *rlectx) { iw_byte dstbuf[2]; rle4_write_unc(rlectx); if(rlectx->run_len<1) { return; } if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: RLE encode error 6"); return; } dstbuf[0] = (iw_byte)rlectx->run_len; dstbuf[1] = rlectx->run_byte; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; rlectx->pending_data_start+=rlectx->run_len; rlectx->run_len=0; } // Should we move the pending compressible data to the "uncompressed" // segment (return 1), or should we write it to disk as a compressed run of // pixels (0)? static int ok_to_move_to_unc(struct rle_context *rlectx) { // This logic is probably not optimal in every case. // One possible improvement might be to adjust the thresholds when // unc_len+run_len is around 255 or higher. // Other improvements might require looking ahead at pixels we haven't // read yet. if(rlectx->unc_len==0) { return (rlectx->run_len<4); } else if(rlectx->unc_len<=2) { return (rlectx->run_len<6); } else { return (rlectx->run_len<8); } return 0; } static int rle4_compress_row(struct rle_context *rlectx) { size_t i; iw_byte dstbuf[2]; iw_byte next_pix; int next_pix_is_trns; int num_trns = 0; // number of consecutive transparent pixels seen int retval = 0; iw_byte tmpb; rlectx->pending_data_start=0; rlectx->unc_len=0; rlectx->run_len=0; for(i=0;i<rlectx->img_width;i++) { // Read the next pixel next_pix = rlectx->srcrow[i]; next_pix_is_trns = (rlectx->wctx->pal->entry[next_pix].a==0); if(num_trns>0 && !next_pix_is_trns) { rle_write_trns(rlectx,num_trns); num_trns=0; } else if(next_pix_is_trns) { if (rlectx->unc_len>0 || rlectx->run_len>0) { rle4_write_unc_and_run(rlectx); } num_trns++; continue; } // -------------------------------------------------------------- // Add the pixel we just read to either the UNC or the RUN data. if(rlectx->run_len==0) { // We don't have a RUN, so we can put this pixel there. rlectx->run_len = 1; rlectx->run_byte = next_pix<<4; } else if(rlectx->run_len==1) { // If the run is 1, we can always add a 2nd pixel rlectx->run_byte |= next_pix; rlectx->run_len++; } else if(rlectx->run_len>=2 && (rlectx->run_len&1)==0 && next_pix==(rlectx->run_byte>>4)) { // pixel fits in the current run; add it. rlectx->run_len++; } else if(rlectx->run_len>=3 && (rlectx->run_len&1) && next_pix==(rlectx->run_byte&0x0f)) { // pixel fits in the current run; add it. rlectx->run_len++; } else if(rlectx->unc_len==0 && rlectx->run_len==2) { // We have one previous byte, and it's different from this one. // Move it to UNC, and make this one the RUN. rlectx->unc_len+=rlectx->run_len; rlectx->run_byte = next_pix<<4; rlectx->run_len = 1; } else if(ok_to_move_to_unc(rlectx)) { // We have a compressible run, but we think it's not long enough to be // beneficial. Convert it to uncompressed bytes -- except for the last // pixel, which can be left in the run. rlectx->unc_len += rlectx->run_len-1; if((rlectx->run_len&1)==0) rlectx->run_byte = (rlectx->run_byte&0x0f)<<4; else rlectx->run_byte = (rlectx->run_byte&0xf0); // Put the next byte in RLE. (It might get moved to UNC, below.) rlectx->run_len = 2; rlectx->run_byte |= next_pix; } else { // Nowhere to put the byte: write out everything, and start fresh. rle4_write_unc_and_run(rlectx); rlectx->run_len = 1; rlectx->run_byte = next_pix<<4; } // -------------------------------------------------------------- // If any RUN bytes that can be added to UNC for free, do so. while(rlectx->unc_len>0 && rlectx->run_len>0 && rle4_get_incr_unc_cost(rlectx)==0) { rlectx->unc_len++; rlectx->run_len--; tmpb = rlectx->run_byte; // Reverse the two pixels stored in run_byte. rlectx->run_byte = (tmpb>>4) | ((tmpb&0x0f)<<4); if(rlectx->run_len==1) rlectx->run_byte &= 0xf0; } // -------------------------------------------------------------- // If we hit certain high water marks, write out the current data. if(rlectx->run_len>=255) { // The maximum size for an RLE segment. rle4_write_unc_and_run(rlectx); } // -------------------------------------------------------------- // Sanity check(s). This can be removed if we're sure the algorithm // is bug-free. // run_len can be at most 254 at this point. // If it were 255, it should have been written out already. if(rlectx->run_len>255) { iw_set_error(rlectx->ctx,"Internal: BMP RLE encode error 3"); goto done; } } // End of row. Write out anything left over. rle4_write_unc_and_run(rlectx); // Write an end-of-line marker (0 0), or if this is the last row, // an end-of-bitmap marker (0 1). dstbuf[0]=0x00; dstbuf[1]= (rlectx->cur_row==0)? 0x01 : 0x00; iwbmp_write(rlectx->wctx,dstbuf,2); rlectx->total_bytes_written+=2; retval = 1; done: return retval; } //====================================================================== // Seek back and write the "file size" and "bits size" fields. static int rle_patch_file_size(struct iwbmpwcontext *wctx,size_t rlesize) { iw_byte buf[4]; size_t fileheader_size; int ret; if(!wctx->iodescr->seek_fn) { iw_set_error(wctx->ctx,"Writing compressed BMP requires a seek function"); return 0; } if(wctx->include_file_header) { // Patch the file size in the file header ret=(*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,2,SEEK_SET); if(!ret) return 0; iw_set_ui32le(buf,(unsigned int)(14+wctx->header_size+wctx->bitfields_size+wctx->palsize+rlesize)); iwbmp_write(wctx,buf,4); fileheader_size = 14; } else { fileheader_size = 0; } // Patch the "bits" size ret=(*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,fileheader_size+20,SEEK_SET); if(!ret) return 0; iw_set_ui32le(buf,(unsigned int)rlesize); iwbmp_write(wctx,buf,4); (*wctx->iodescr->seek_fn)(wctx->ctx,wctx->iodescr,0,SEEK_END); return 1; } static int iwbmp_write_pixels_compressed(struct iwbmpwcontext *wctx, struct iw_image *img) { struct rle_context rlectx; int j; int retval = 0; iw_zeromem(&rlectx,sizeof(struct rle_context)); rlectx.ctx = wctx->ctx; rlectx.wctx = wctx; rlectx.total_bytes_written = 0; rlectx.img_width = img->width; for(j=img->height-1;j>=0;j--) { // Compress and write a row of pixels rlectx.srcrow = &img->pixels[j*img->bpr]; rlectx.cur_row = j; if(wctx->bitcount==4) { if(!rle4_compress_row(&rlectx)) goto done; } else if(wctx->bitcount==8) { if(!rle8_compress_row(&rlectx)) goto done; } else { goto done; } } // Back-patch the 'file size' and 'bits size' fields if(!rle_patch_file_size(wctx,rlectx.total_bytes_written)) goto done; retval = 1; done: return retval; } static void iwbmp_write_pixels_uncompressed(struct iwbmpwcontext *wctx, struct iw_image *img) { int j; iw_byte *dstrow = NULL; const iw_byte *srcrow; dstrow = iw_mallocz(wctx->ctx,wctx->unc_dst_bpr); if(!dstrow) goto done; for(j=img->height-1;j>=0;j--) { srcrow = &img->pixels[j*img->bpr]; switch(wctx->bitcount) { case 32: bmpw_convert_row_16_32(wctx,srcrow,dstrow,img->width); break; case 24: bmpw_convert_row_24(wctx,srcrow,dstrow,img->width); break; case 16: bmpw_convert_row_16_32(wctx,srcrow,dstrow,img->width); break; case 8: bmpw_convert_row_8(srcrow,dstrow,img->width); break; case 4: bmpw_convert_row_4(srcrow,dstrow,img->width); break; case 1: bmpw_convert_row_1(srcrow,dstrow,img->width); break; } iwbmp_write(wctx,dstrow,wctx->unc_dst_bpr); } done: if(dstrow) iw_free(wctx->ctx,dstrow); return; } // 0 = no transparency // 1 = binary transparency // 2 = partial transparency static int check_palette_transparency(const struct iw_palette *p) { int i; int retval = 0; for(i=0;i<p->num_entries;i++) { if(p->entry[i].a!=255) retval=1; if(p->entry[i].a!=255 && p->entry[i].a!=0) return 2; } return retval; } // Do some preparations needed to write a 16-bit or 32-bit BMP. static int setup_16_32bit(struct iwbmpwcontext *wctx, int mcc_r, int mcc_g, int mcc_b, int mcc_a) { int has_alpha; has_alpha = IW_IMGTYPE_HAS_ALPHA(wctx->img->imgtype); if(wctx->bmpversion<3) { iw_set_errorf(wctx->ctx,"Bit depth incompatible with BMP version %d", wctx->bmpversion); return 0; } if(has_alpha && wctx->bmpversion<5) { iw_set_error(wctx->ctx,"Internal: Attempt to write v3 16- or 32-bit image with transparency"); return 0; } // Make our own copy of the max color codes, so that we don't have to // do "if(grayscale)" so much. wctx->maxcolor[0] = mcc_r; wctx->maxcolor[1] = mcc_g; wctx->maxcolor[2] = mcc_b; if(has_alpha) wctx->maxcolor[3] = mcc_a; if(!iwbmp_calc_bitfields_masks(wctx,has_alpha?4:3)) return 0; if(mcc_r==31 && mcc_g==31 && mcc_b==31 && !has_alpha) { // For the default 5-5-5, set the 'compression' to BI_RGB // instead of BITFIELDS, and don't write a BITFIELDS segment // (or for v5 BMP, don't set the Mask fields). wctx->bitfields_size = 0; } else { wctx->uses_bitfields = 1; wctx->bitfields_size = (wctx->bmpversion==3) ? 12 : 0; } return 1; } static int iwbmp_write_main(struct iwbmpwcontext *wctx) { struct iw_image *img; int cmpr_req; int retval = 0; int x; const char *optv; img = wctx->img; wctx->bmpversion = 0; optv = iw_get_option(wctx->ctx, "bmp:version"); if(optv) { wctx->bmpversion = iw_parse_int(optv); } if(wctx->bmpversion==0) wctx->bmpversion=3; if(wctx->bmpversion==4) { iw_warning(wctx->ctx,"Writing BMP v4 is not supported; using v3 instead"); wctx->bmpversion=3; } if(wctx->bmpversion!=2 && wctx->bmpversion!=3 && wctx->bmpversion!=5) { iw_set_errorf(wctx->ctx,"Unsupported BMP version: %d",wctx->bmpversion); goto done; } if(wctx->bmpversion>=3) cmpr_req = iw_get_value(wctx->ctx,IW_VAL_COMPRESSION); else cmpr_req = IW_COMPRESSION_NONE; if(wctx->bmpversion==2) wctx->header_size = 12; else if(wctx->bmpversion==5) wctx->header_size = 124; else wctx->header_size = 40; wctx->no_cslabel = iw_get_value(wctx->ctx,IW_VAL_NO_CSLABEL); // If any kind of compression was requested, use RLE if possible. if(cmpr_req==IW_COMPRESSION_AUTO || cmpr_req==IW_COMPRESSION_NONE) cmpr_req = IW_COMPRESSION_NONE; else cmpr_req = IW_COMPRESSION_RLE; if(img->imgtype==IW_IMGTYPE_RGB) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_RED], img->maxcolorcode[IW_CHANNELTYPE_GREEN], img->maxcolorcode[IW_CHANNELTYPE_BLUE],0)) { goto done; } } else { wctx->bitcount=24; } } else if(img->imgtype==IW_IMGTYPE_PALETTE) { if(!wctx->pal) goto done; x = check_palette_transparency(wctx->pal); if(x!=0 && wctx->bmpversion<3) { iw_set_error(wctx->ctx,"Cannot save as a transparent BMP: Incompatible BMP version"); goto done; } else if(x==2) { iw_set_error(wctx->ctx,"Cannot save this image as a transparent BMP: Has partial transparency"); goto done; } else if(x!=0 && cmpr_req!=IW_COMPRESSION_RLE) { iw_set_error(wctx->ctx,"Cannot save as a transparent BMP: RLE compression required"); goto done; } if(wctx->pal->num_entries<=2 && cmpr_req!=IW_COMPRESSION_RLE) wctx->bitcount=1; else if(wctx->pal->num_entries<=16) wctx->bitcount=4; else wctx->bitcount=8; } else if(img->imgtype==IW_IMGTYPE_RGBA) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_RED], img->maxcolorcode[IW_CHANNELTYPE_GREEN], img->maxcolorcode[IW_CHANNELTYPE_BLUE], img->maxcolorcode[IW_CHANNELTYPE_ALPHA])) { goto done; } } else { if(!setup_16_32bit(wctx,255,255,255,255)) { goto done; } } } else if(img->imgtype==IW_IMGTYPE_GRAYA) { if(img->reduced_maxcolors) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_ALPHA])) { goto done; } } else { if(!setup_16_32bit(wctx,255,255,255,255)) { goto done; } } } else if(img->imgtype==IW_IMGTYPE_GRAY) { if(img->reduced_maxcolors) { if(img->maxcolorcode[IW_CHANNELTYPE_GRAY]<=1023) { if(!setup_16_32bit(wctx,img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY], img->maxcolorcode[IW_CHANNELTYPE_GRAY],0)) { goto done; } } else { iw_set_error(wctx->ctx,"Cannot write grayscale BMP at this bit depth"); goto done; } } else { // We normally won't get here, because a grayscale image should have // been optimized and converted to a palette image. // But maybe that optimization was disabled. wctx->bitcount=24; } } else { iw_set_error(wctx->ctx,"Internal: Bad image type for BMP"); goto done; } if(cmpr_req==IW_COMPRESSION_RLE && (wctx->bitcount==4 || wctx->bitcount==8)) { wctx->compressed = 1; } wctx->unc_dst_bpr = iwbmp_calc_bpr(wctx->bitcount,img->width); wctx->unc_bitssize = wctx->unc_dst_bpr * img->height; wctx->palentries = 0; if(wctx->pal) { if(wctx->bmpversion==2) { wctx->palentries = 1<<wctx->bitcount; wctx->palsize = wctx->palentries*3; } else { if(wctx->bitcount==1) { // The documentation says that if the bitdepth is 1, the palette // contains exactly two entries. wctx->palentries=2; } else { wctx->palentries = wctx->pal->num_entries; } wctx->palsize = wctx->palentries*4; } } // File header iwbmp_write_file_header(wctx); // Bitmap header ("BITMAPINFOHEADER") if(!iwbmp_write_bmp_header(wctx)) { goto done; } if(wctx->bitfields_size>0) { if(!iwbmp_write_bitfields(wctx)) goto done; } // Palette iwbmp_write_palette(wctx); // Pixels if(wctx->compressed) { if(!iwbmp_write_pixels_compressed(wctx,img)) goto done; } else { iwbmp_write_pixels_uncompressed(wctx,img); } retval = 1; done: return retval; } IW_IMPL(int) iw_write_bmp_file(struct iw_context *ctx, struct iw_iodescr *iodescr) { struct iwbmpwcontext wctx; int retval=0; struct iw_image img1; iw_zeromem(&img1,sizeof(struct iw_image)); iw_zeromem(&wctx,sizeof(struct iwbmpwcontext)); wctx.ctx = ctx; wctx.include_file_header = 1; wctx.iodescr=iodescr; iw_get_output_image(ctx,&img1); wctx.img = &img1; if(wctx.img->imgtype==IW_IMGTYPE_PALETTE) { wctx.pal = iw_get_output_palette(ctx); if(!wctx.pal) goto done; } iw_get_output_colorspace(ctx,&wctx.csdescr); if(!iwbmp_write_main(&wctx)) { iw_set_error(ctx,"BMP write failed"); goto done; } retval=1; done: return retval; }
./CrossVul/dataset_final_sorted/CWE-682/c/bad_3331_0
crossvul-cpp_data_good_276_1
/* This file is part of libmspack. * (C) 2003-2018 Stuart Caie. * * libmspack is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License (LGPL) version 2.1 * * For further details, see the file COPYING.LIB distributed with libmspack */ /* CHM decompression implementation */ #include <system.h> #include <chm.h> /* prototypes */ static struct mschmd_header * chmd_open( struct mschm_decompressor *base, const char *filename); static struct mschmd_header * chmd_fast_open( struct mschm_decompressor *base, const char *filename); static struct mschmd_header *chmd_real_open( struct mschm_decompressor *base, const char *filename, int entire); static void chmd_close( struct mschm_decompressor *base, struct mschmd_header *chm); static int chmd_read_headers( struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire); static int chmd_fast_find( struct mschm_decompressor *base, struct mschmd_header *chm, const char *filename, struct mschmd_file *f_ptr, int f_size); static unsigned char *read_chunk( struct mschm_decompressor_p *self, struct mschmd_header *chm, struct mspack_file *fh, unsigned int chunk); static int search_chunk( struct mschmd_header *chm, const unsigned char *chunk, const char *filename, const unsigned char **result, const unsigned char **result_end); static inline int compare( const char *s1, const char *s2, int l1, int l2); static int chmd_extract( struct mschm_decompressor *base, struct mschmd_file *file, const char *filename); static int chmd_sys_write( struct mspack_file *file, void *buffer, int bytes); static int chmd_init_decomp( struct mschm_decompressor_p *self, struct mschmd_file *file); static int read_reset_table( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, int entry, off_t *length_ptr, off_t *offset_ptr); static int read_spaninfo( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, off_t *length_ptr); static int find_sys_file( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, struct mschmd_file **f_ptr, const char *name); static unsigned char *read_sys_file( struct mschm_decompressor_p *self, struct mschmd_file *file); static int chmd_error( struct mschm_decompressor *base); static int read_off64( off_t *var, unsigned char *mem, struct mspack_system *sys, struct mspack_file *fh); /* filenames of the system files used for decompression. * Content and ControlData are essential. * ResetTable is preferred, but SpanInfo can be used if not available */ static const char *content_name = "::DataSpace/Storage/MSCompressed/Content"; static const char *control_name = "::DataSpace/Storage/MSCompressed/ControlData"; static const char *spaninfo_name = "::DataSpace/Storage/MSCompressed/SpanInfo"; static const char *rtable_name = "::DataSpace/Storage/MSCompressed/Transform/" "{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable"; /*************************************** * MSPACK_CREATE_CHM_DECOMPRESSOR *************************************** * constructor */ struct mschm_decompressor * mspack_create_chm_decompressor(struct mspack_system *sys) { struct mschm_decompressor_p *self = NULL; if (!sys) sys = mspack_default_system; if (!mspack_valid_system(sys)) return NULL; if ((self = (struct mschm_decompressor_p *) sys->alloc(sys, sizeof(struct mschm_decompressor_p)))) { self->base.open = &chmd_open; self->base.close = &chmd_close; self->base.extract = &chmd_extract; self->base.last_error = &chmd_error; self->base.fast_open = &chmd_fast_open; self->base.fast_find = &chmd_fast_find; self->system = sys; self->error = MSPACK_ERR_OK; self->d = NULL; } return (struct mschm_decompressor *) self; } /*************************************** * MSPACK_DESTROY_CAB_DECOMPRESSOR *************************************** * destructor */ void mspack_destroy_chm_decompressor(struct mschm_decompressor *base) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; if (self) { struct mspack_system *sys = self->system; if (self->d) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); sys->free(self->d); } sys->free(self); } } /*************************************** * CHMD_OPEN *************************************** * opens a file and tries to read it as a CHM file. * Calls chmd_real_open() with entire=1. */ static struct mschmd_header *chmd_open(struct mschm_decompressor *base, const char *filename) { return chmd_real_open(base, filename, 1); } /*************************************** * CHMD_FAST_OPEN *************************************** * opens a file and tries to read it as a CHM file, but does not read * the file headers. Calls chmd_real_open() with entire=0 */ static struct mschmd_header *chmd_fast_open(struct mschm_decompressor *base, const char *filename) { return chmd_real_open(base, filename, 0); } /*************************************** * CHMD_REAL_OPEN *************************************** * the real implementation of chmd_open() and chmd_fast_open(). It simply * passes the "entire" parameter to chmd_read_headers(), which will then * either read all headers, or a bare mininum. */ static struct mschmd_header *chmd_real_open(struct mschm_decompressor *base, const char *filename, int entire) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mschmd_header *chm = NULL; struct mspack_system *sys; struct mspack_file *fh; int error; if (!base) return NULL; sys = self->system; if ((fh = sys->open(sys, filename, MSPACK_SYS_OPEN_READ))) { if ((chm = (struct mschmd_header *) sys->alloc(sys, sizeof(struct mschmd_header)))) { chm->filename = filename; error = chmd_read_headers(sys, fh, chm, entire); if (error) { /* if the error is DATAFORMAT, and there are some results, return * partial results with a warning, rather than nothing */ if (error == MSPACK_ERR_DATAFORMAT && (chm->files || chm->sysfiles)) { sys->message(fh, "WARNING; contents are corrupt"); error = MSPACK_ERR_OK; } else { chmd_close(base, chm); chm = NULL; } } self->error = error; } else { self->error = MSPACK_ERR_NOMEMORY; } sys->close(fh); } else { self->error = MSPACK_ERR_OPEN; } return chm; } /*************************************** * CHMD_CLOSE *************************************** * frees all memory associated with a given mschmd_header */ static void chmd_close(struct mschm_decompressor *base, struct mschmd_header *chm) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mschmd_file *fi, *nfi; struct mspack_system *sys; unsigned int i; if (!base) return; sys = self->system; self->error = MSPACK_ERR_OK; /* free files */ for (fi = chm->files; fi; fi = nfi) { nfi = fi->next; sys->free(fi); } for (fi = chm->sysfiles; fi; fi = nfi) { nfi = fi->next; sys->free(fi); } /* if this CHM was being decompressed, free decompression state */ if (self->d && (self->d->chm == chm)) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); sys->free(self->d); self->d = NULL; } /* if this CHM had a chunk cache, free it and contents */ if (chm->chunk_cache) { for (i = 0; i < chm->num_chunks; i++) sys->free(chm->chunk_cache[i]); sys->free(chm->chunk_cache); } sys->free(chm); } /*************************************** * CHMD_READ_HEADERS *************************************** * reads the basic CHM file headers. If the "entire" parameter is * non-zero, all file entries will also be read. fills out a pre-existing * mschmd_header structure, allocates memory for files as necessary */ /* The GUIDs found in CHM headers */ static const unsigned char guids[32] = { /* {7C01FD10-7BAA-11D0-9E0C-00A0-C922-E6EC} */ 0x10, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11, 0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC, /* {7C01FD11-7BAA-11D0-9E0C-00A0-C922-E6EC} */ 0x11, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11, 0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC }; /* reads an encoded integer into a variable; 7 bits of data per byte, * the high bit is used to indicate that there is another byte */ #define READ_ENCINT(var) do { \ (var) = 0; \ do { \ if (p >= end) goto chunk_end; \ (var) = ((var) << 7) | (*p & 0x7F); \ } while (*p++ & 0x80); \ } while (0) static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire) { unsigned int section, name_len, x, errors, num_chunks; unsigned char buf[0x54], *chunk = NULL, *name, *p, *end; struct mschmd_file *fi, *link = NULL; off_t offset, length; int num_entries; /* initialise pointers */ chm->files = NULL; chm->sysfiles = NULL; chm->chunk_cache = NULL; chm->sec0.base.chm = chm; chm->sec0.base.id = 0; chm->sec1.base.chm = chm; chm->sec1.base.id = 1; chm->sec1.content = NULL; chm->sec1.control = NULL; chm->sec1.spaninfo = NULL; chm->sec1.rtable = NULL; /* read the first header */ if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) { return MSPACK_ERR_READ; } /* check ITSF signature */ if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) { return MSPACK_ERR_SIGNATURE; } /* check both header GUIDs */ if (mspack_memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) { D(("incorrect GUIDs")) return MSPACK_ERR_SIGNATURE; } chm->version = EndGetI32(&buf[chmhead_Version]); chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]); chm->language = EndGetI32(&buf[chmhead_LanguageID]); if (chm->version > 3) { sys->message(fh, "WARNING; CHM version > 3"); } /* read the header section table */ if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) { return MSPACK_ERR_READ; } /* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files. * The offset will be corrected later, once HS1 is read. */ if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) || read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) || read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 0 */ if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 0 */ if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) { return MSPACK_ERR_READ; } if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 1 */ if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 1 */ if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) { return MSPACK_ERR_READ; } chm->dir_offset = sys->tell(fh); chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]); chm->density = EndGetI32(&buf[chmhs1_Density]); chm->depth = EndGetI32(&buf[chmhs1_Depth]); chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]); chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]); chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]); chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]); if (chm->version < 3) { /* versions before 3 don't have chmhst3_OffsetCS0 */ chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks); } /* check if content offset or file size is wrong */ if (chm->sec0.offset > chm->length) { D(("content section begins after file has ended")) return MSPACK_ERR_DATAFORMAT; } /* ensure there are chunks and that chunk size is * large enough for signature and num_entries */ if (chm->chunk_size < (pmgl_Entries + 2)) { D(("chunk size not large enough")) return MSPACK_ERR_DATAFORMAT; } if (chm->num_chunks == 0) { D(("no chunks")) return MSPACK_ERR_DATAFORMAT; } /* The chunk_cache data structure is not great; large values for num_chunks * or num_chunks*chunk_size can exhaust all memory. Until a better chunk * cache is implemented, put arbitrary limits on num_chunks and chunk size. */ if (chm->num_chunks > 100000) { D(("more than 100,000 chunks")) return MSPACK_ERR_DATAFORMAT; } if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) { D(("chunks larger than entire file")) return MSPACK_ERR_DATAFORMAT; } /* common sense checks on header section 1 fields */ if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) { sys->message(fh, "WARNING; chunk size is not a power of two"); } if (chm->first_pmgl != 0) { sys->message(fh, "WARNING; first PMGL chunk is not zero"); } if (chm->first_pmgl > chm->last_pmgl) { D(("first pmgl chunk is after last pmgl chunk")) return MSPACK_ERR_DATAFORMAT; } if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) { D(("index_root outside valid range")) return MSPACK_ERR_DATAFORMAT; } /* if we are doing a quick read, stop here! */ if (!entire) { return MSPACK_ERR_OK; } /* seek to the first PMGL chunk, and reduce the number of chunks to read */ if ((x = chm->first_pmgl) != 0) { if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) { return MSPACK_ERR_SEEK; } } num_chunks = chm->last_pmgl - x + 1; if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) { return MSPACK_ERR_NOMEMORY; } /* read and process all chunks from FirstPMGL to LastPMGL */ errors = 0; while (num_chunks--) { /* read next chunk */ if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) { sys->free(chunk); return MSPACK_ERR_READ; } /* process only directory (PMGL) chunks */ if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue; if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) { sys->message(fh, "WARNING; PMGL quickref area is too small"); } if (EndGetI32(&chunk[pmgl_QuickRefSize]) > ((int)chm->chunk_size - pmgl_Entries)) { sys->message(fh, "WARNING; PMGL quickref area is too large"); } p = &chunk[pmgl_Entries]; end = &chunk[chm->chunk_size - 2]; num_entries = EndGetI16(end); while (num_entries--) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; /* consider blank filenames to be an error */ if (name_len == 0) goto chunk_end; name = p; p += name_len; READ_ENCINT(section); READ_ENCINT(offset); READ_ENCINT(length); /* empty files and directory names are stored as a file entry at * offset 0 with length 0. We want to keep empty files, but not * directory names, which end with a "/" */ if ((offset == 0) && (length == 0)) { if ((name_len > 0) && (name[name_len-1] == '/')) continue; } if (section > 1) { sys->message(fh, "invalid section number '%u'.", section); continue; } if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) { sys->free(chunk); return MSPACK_ERR_NOMEMORY; } fi->next = NULL; fi->filename = (char *) &fi[1]; fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0) : (struct mschmd_section *) (&chm->sec1)); fi->offset = offset; fi->length = length; sys->copy(name, fi->filename, (size_t) name_len); fi->filename[name_len] = '\0'; if (name[0] == ':' && name[1] == ':') { /* system file */ if (mspack_memcmp(&name[2], &content_name[2], 31L) == 0) { if (mspack_memcmp(&name[33], &content_name[33], 8L) == 0) { chm->sec1.content = fi; } else if (mspack_memcmp(&name[33], &control_name[33], 11L) == 0) { chm->sec1.control = fi; } else if (mspack_memcmp(&name[33], &spaninfo_name[33], 8L) == 0) { chm->sec1.spaninfo = fi; } else if (mspack_memcmp(&name[33], &rtable_name[33], 72L) == 0) { chm->sec1.rtable = fi; } } fi->next = chm->sysfiles; chm->sysfiles = fi; } else { /* normal file */ if (link) link->next = fi; else chm->files = fi; link = fi; } } /* this is reached either when num_entries runs out, or if * reading data from the chunk reached a premature end of chunk */ chunk_end: if (num_entries >= 0) { D(("chunk ended before all entries could be read")) errors++; } } sys->free(chunk); return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK; } /*************************************** * CHMD_FAST_FIND *************************************** * uses PMGI index chunks and quickref data to quickly locate a file * directly from the on-disk index. * * TODO: protect against infinite loops in chunks (where pgml_NextChunk * or a PMGI index entry point to an already visited chunk) */ static int chmd_fast_find(struct mschm_decompressor *base, struct mschmd_header *chm, const char *filename, struct mschmd_file *f_ptr, int f_size) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mspack_system *sys; struct mspack_file *fh; const unsigned char *chunk, *p, *end; int err = MSPACK_ERR_OK, result = -1; unsigned int n, sec; if (!self || !chm || !f_ptr || (f_size != sizeof(struct mschmd_file))) { return MSPACK_ERR_ARGS; } sys = self->system; /* clear the results structure */ memset(f_ptr, 0, f_size); if (!(fh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ))) { return MSPACK_ERR_OPEN; } /* go through PMGI chunk hierarchy to reach PMGL chunk */ if (chm->index_root < chm->num_chunks) { n = chm->index_root; for (;;) { if (!(chunk = read_chunk(self, chm, fh, n))) { sys->close(fh); return self->error; } /* search PMGI/PMGL chunk. exit early if no entry found */ if ((result = search_chunk(chm, chunk, filename, &p, &end)) <= 0) { break; } /* found result. loop around for next chunk if this is PMGI */ if (chunk[3] == 0x4C) break; else READ_ENCINT(n); } } else { /* PMGL chunks only, search from first_pmgl to last_pmgl */ for (n = chm->first_pmgl; n <= chm->last_pmgl; n = EndGetI32(&chunk[pmgl_NextChunk])) { if (!(chunk = read_chunk(self, chm, fh, n))) { err = self->error; break; } /* search PMGL chunk. exit if file found */ if ((result = search_chunk(chm, chunk, filename, &p, &end)) > 0) { break; } /* stop simple infinite loops: can't visit the same chunk twice */ if ((int)n == EndGetI32(&chunk[pmgl_NextChunk])) { break; } } } /* if we found a file, read it */ if (result > 0) { READ_ENCINT(sec); f_ptr->section = (sec == 0) ? (struct mschmd_section *) &chm->sec0 : (struct mschmd_section *) &chm->sec1; READ_ENCINT(f_ptr->offset); READ_ENCINT(f_ptr->length); } else if (result < 0) { err = MSPACK_ERR_DATAFORMAT; } sys->close(fh); return self->error = err; chunk_end: D(("read beyond end of chunk entries")) sys->close(fh); return self->error = MSPACK_ERR_DATAFORMAT; } /* reads the given chunk into memory, storing it in a chunk cache * so it doesn't need to be read from disk more than once */ static unsigned char *read_chunk(struct mschm_decompressor_p *self, struct mschmd_header *chm, struct mspack_file *fh, unsigned int chunk_num) { struct mspack_system *sys = self->system; unsigned char *buf; /* check arguments - most are already checked by chmd_fast_find */ if (chunk_num >= chm->num_chunks) return NULL; /* ensure chunk cache is available */ if (!chm->chunk_cache) { size_t size = sizeof(unsigned char *) * chm->num_chunks; if (!(chm->chunk_cache = (unsigned char **) sys->alloc(sys, size))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } memset(chm->chunk_cache, 0, size); } /* try to answer out of chunk cache */ if (chm->chunk_cache[chunk_num]) return chm->chunk_cache[chunk_num]; /* need to read chunk - allocate memory for it */ if (!(buf = (unsigned char *) sys->alloc(sys, chm->chunk_size))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } /* seek to block and read it */ if (sys->seek(fh, (off_t) (chm->dir_offset + (chunk_num * chm->chunk_size)), MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; sys->free(buf); return NULL; } if (sys->read(fh, buf, (int)chm->chunk_size) != (int)chm->chunk_size) { self->error = MSPACK_ERR_READ; sys->free(buf); return NULL; } /* check the signature. Is is PMGL or PMGI? */ if (!((buf[0] == 0x50) && (buf[1] == 0x4D) && (buf[2] == 0x47) && ((buf[3] == 0x4C) || (buf[3] == 0x49)))) { self->error = MSPACK_ERR_SEEK; sys->free(buf); return NULL; } /* all OK. Store chunk in cache and return it */ return chm->chunk_cache[chunk_num] = buf; } /* searches a PMGI/PMGL chunk for a given filename entry. Returns -1 on * data format error, 0 if entry definitely not found, 1 if entry * found. In the latter case, *result and *result_end are set pointing * to that entry's data (either the "next chunk" ENCINT for a PMGI or * the section, offset and length ENCINTs for a PMGL). * * In the case of PMGL chunks, the entry has definitely been * found. In the case of PMGI chunks, the entry which points to the * chunk that may eventually contain that entry has been found. */ static int search_chunk(struct mschmd_header *chm, const unsigned char *chunk, const char *filename, const unsigned char **result, const unsigned char **result_end) { const unsigned char *start, *end, *p; unsigned int qr_size, num_entries, qr_entries, qr_density, name_len; unsigned int L, R, M, fname_len, entries_off, is_pmgl; int cmp; fname_len = strlen(filename); /* PMGL chunk or PMGI chunk? (note: read_chunk() has already * checked the rest of the characters in the chunk signature) */ if (chunk[3] == 0x4C) { is_pmgl = 1; entries_off = pmgl_Entries; } else { is_pmgl = 0; entries_off = pmgi_Entries; } /* Step 1: binary search first filename of each QR entry * - target filename == entry * found file * - target filename < all entries * file not found * - target filename > all entries * proceed to step 2 using final entry * - target filename between two searched entries * proceed to step 2 */ qr_size = EndGetI32(&chunk[pmgl_QuickRefSize]); start = &chunk[chm->chunk_size - 2]; end = &chunk[chm->chunk_size - qr_size]; num_entries = EndGetI16(start); qr_density = 1 + (1 << chm->density); qr_entries = (num_entries + qr_density-1) / qr_density; if (num_entries == 0) { D(("chunk has no entries")) return -1; } if (qr_size > chm->chunk_size) { D(("quickref size > chunk size")) return -1; } *result_end = end; if (((int)qr_entries * 2) > (start - end)) { D(("WARNING; more quickrefs than quickref space")) qr_entries = 0; /* but we can live with it */ } if (qr_entries > 0) { L = 0; R = qr_entries - 1; do { /* pick new midpoint */ M = (L + R) >> 1; /* compare filename with entry QR points to */ p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)]; READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; cmp = compare(filename, (char *)p, fname_len, name_len); if (cmp == 0) break; else if (cmp < 0) { if (M) R = M - 1; else return 0; } else if (cmp > 0) L = M + 1; } while (L <= R); M = (L + R) >> 1; if (cmp == 0) { /* exact match! */ p += name_len; *result = p; return 1; } /* otherwise, read the group of entries for QR entry M */ p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)]; num_entries -= (M * qr_density); if (num_entries > qr_density) num_entries = qr_density; } else { p = &chunk[entries_off]; } /* Step 2: linear search through the set of entries reached in step 1. * - filename == any entry * found entry * - filename < all entries (PMGI) or any entry (PMGL) * entry not found, stop now * - filename > all entries * entry not found (PMGL) / maybe found (PMGI) * - */ *result = NULL; while (num_entries-- > 0) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; cmp = compare(filename, (char *)p, fname_len, name_len); p += name_len; if (cmp == 0) { /* entry found */ *result = p; return 1; } if (cmp < 0) { /* entry not found (PMGL) / maybe found (PMGI) */ break; } /* read and ignore the rest of this entry */ if (is_pmgl) { READ_ENCINT(R); /* skip section */ READ_ENCINT(R); /* skip offset */ READ_ENCINT(R); /* skip length */ } else { *result = p; /* store potential final result */ READ_ENCINT(R); /* skip chunk number */ } } /* PMGL? not found. PMGI? maybe found */ return (is_pmgl) ? 0 : (*result ? 1 : 0); chunk_end: D(("reached end of chunk data while searching")) return -1; } #if HAVE_TOWLOWER # if HAVE_WCTYPE_H # include <wctype.h> # endif # define TOLOWER(x) towlower(x) #elif HAVE_TOLOWER # if HAVE_CTYPE_H # include <ctype.h> # endif # define TOLOWER(x) tolower(x) #else # define TOLOWER(x) (((x)<0||(x)>255)?(x):mspack_tolower_map[(x)]) /* Map of char -> lowercase char for the first 256 chars. Generated with: * LC_CTYPE=en_GB.utf-8 perl -Mlocale -le 'print map{ord(lc chr).","} 0..255' */ static const unsigned char mspack_tolower_map[256] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, 28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52, 53,54,55,56,57,58,59,60,61,62,63,64,97,98,99,100,101,102,103,104,105,106, 107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,91,92,93,94, 95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114, 115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133, 134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152, 153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171, 172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190, 191,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241, 242,243,244,245,246,215,248,249,250,251,252,253,254,223,224,225,226,227,228, 229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247, 248,249,250,251,252,253,254,255 }; #endif /* decodes a UTF-8 character from s[] into c. Will not read past e. * doesn't test that extension bytes are %10xxxxxx. * allows some overlong encodings. */ #define GET_UTF8_CHAR(s, e, c) do { \ unsigned char x = *s++; \ if (x < 0x80) c = x; \ else if (x >= 0xC2 && x < 0xE0 && s < e) { \ c = (x & 0x1F) << 6 | (*s++ & 0x3F); \ } \ else if (x >= 0xE0 && x < 0xF0 && s+1 < e) { \ c = (x & 0x0F) << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F); \ s += 2; \ } \ else if (x >= 0xF0 && x <= 0xF5 && s+2 < e) { \ c = (x & 0x07) << 18 | (s[0] & 0x3F) << 12 | \ (s[1] & 0x3F) << 6 | (s[2] & 0x3F); \ if (c > 0x10FFFF) c = 0xFFFD; \ s += 3; \ } \ else c = 0xFFFD; \ } while (0) /* case-insensitively compares two UTF8 encoded strings. String length for * both strings must be provided, null bytes are not terminators */ static inline int compare(const char *s1, const char *s2, int l1, int l2) { register const unsigned char *p1 = (const unsigned char *) s1; register const unsigned char *p2 = (const unsigned char *) s2; register const unsigned char *e1 = p1 + l1, *e2 = p2 + l2; int c1, c2; while (p1 < e1 && p2 < e2) { GET_UTF8_CHAR(p1, e1, c1); GET_UTF8_CHAR(p2, e2, c2); if (c1 == c2) continue; c1 = TOLOWER(c1); c2 = TOLOWER(c2); if (c1 != c2) return c1 - c2; } return l1 - l2; } /*************************************** * CHMD_EXTRACT *************************************** * extracts a file from a CHM helpfile */ static int chmd_extract(struct mschm_decompressor *base, struct mschmd_file *file, const char *filename) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mspack_system *sys; struct mschmd_header *chm; struct mspack_file *fh; off_t bytes; if (!self) return MSPACK_ERR_ARGS; if (!file || !file->section) return self->error = MSPACK_ERR_ARGS; sys = self->system; chm = file->section->chm; /* create decompression state if it doesn't exist */ if (!self->d) { self->d = (struct mschmd_decompress_state *) sys->alloc(sys, sizeof(struct mschmd_decompress_state)); if (!self->d) return self->error = MSPACK_ERR_NOMEMORY; self->d->chm = chm; self->d->offset = 0; self->d->state = NULL; self->d->sys = *sys; self->d->sys.write = &chmd_sys_write; self->d->infh = NULL; self->d->outfh = NULL; } /* open input chm file if not open, or the open one is a different chm */ if (!self->d->infh || (self->d->chm != chm)) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); self->d->chm = chm; self->d->offset = 0; self->d->state = NULL; self->d->infh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ); if (!self->d->infh) return self->error = MSPACK_ERR_OPEN; } /* open file for output */ if (!(fh = sys->open(sys, filename, MSPACK_SYS_OPEN_WRITE))) { return self->error = MSPACK_ERR_OPEN; } /* if file is empty, simply creating it is enough */ if (!file->length) { sys->close(fh); return self->error = MSPACK_ERR_OK; } self->error = MSPACK_ERR_OK; switch (file->section->id) { case 0: /* Uncompressed section file */ /* simple seek + copy */ if (sys->seek(self->d->infh, file->section->chm->sec0.offset + file->offset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; } else { unsigned char buf[512]; off_t length = file->length; while (length > 0) { int run = sizeof(buf); if ((off_t)run > length) run = (int)length; if (sys->read(self->d->infh, &buf[0], run) != run) { self->error = MSPACK_ERR_READ; break; } if (sys->write(fh, &buf[0], run) != run) { self->error = MSPACK_ERR_WRITE; break; } length -= run; } } break; case 1: /* MSCompressed section file */ /* (re)initialise compression state if we it is not yet initialised, * or we have advanced too far and have to backtrack */ if (!self->d->state || (file->offset < self->d->offset)) { if (self->d->state) { lzxd_free(self->d->state); self->d->state = NULL; } if (chmd_init_decomp(self, file)) break; } /* seek to input data */ if (sys->seek(self->d->infh, self->d->inoffset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; break; } /* get to correct offset. */ self->d->outfh = NULL; if ((bytes = file->offset - self->d->offset)) { self->error = lzxd_decompress(self->d->state, bytes); } /* if getting to the correct offset was error free, unpack file */ if (!self->error) { self->d->outfh = fh; self->error = lzxd_decompress(self->d->state, file->length); } /* save offset in input source stream, in case there is a section 0 * file between now and the next section 1 file extracted */ self->d->inoffset = sys->tell(self->d->infh); /* if an LZX error occured, the LZX decompressor is now useless */ if (self->error) { if (self->d->state) lzxd_free(self->d->state); self->d->state = NULL; } break; } sys->close(fh); return self->error; } /*************************************** * CHMD_SYS_WRITE *************************************** * chmd_sys_write is the internal writer function which the decompressor * uses. If either writes data to disk (self->d->outfh) with the real * sys->write() function, or does nothing with the data when * self->d->outfh == NULL. advances self->d->offset. */ static int chmd_sys_write(struct mspack_file *file, void *buffer, int bytes) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) file; self->d->offset += bytes; if (self->d->outfh) { return self->system->write(self->d->outfh, buffer, bytes); } return bytes; } /*************************************** * CHMD_INIT_DECOMP *************************************** * Initialises the LZX decompressor to decompress the compressed stream, * from the nearest reset offset and length that is needed for the given * file. */ static int chmd_init_decomp(struct mschm_decompressor_p *self, struct mschmd_file *file) { int window_size, window_bits, reset_interval, entry, err; struct mspack_system *sys = self->system; struct mschmd_sec_mscompressed *sec; unsigned char *data; off_t length, offset; sec = (struct mschmd_sec_mscompressed *) file->section; /* ensure we have a mscompressed content section */ err = find_sys_file(self, sec, &sec->content, content_name); if (err) return self->error = err; /* ensure we have a ControlData file */ err = find_sys_file(self, sec, &sec->control, control_name); if (err) return self->error = err; /* read ControlData */ if (sec->control->length < lzxcd_SIZEOF) { D(("ControlData file is too short")) return self->error = MSPACK_ERR_DATAFORMAT; } if (!(data = read_sys_file(self, sec->control))) { D(("can't read mscompressed control data file")) return self->error; } /* check LZXC signature */ if (EndGetI32(&data[lzxcd_Signature]) != 0x43585A4C) { sys->free(data); return self->error = MSPACK_ERR_SIGNATURE; } /* read reset_interval and window_size and validate version number */ switch (EndGetI32(&data[lzxcd_Version])) { case 1: reset_interval = EndGetI32(&data[lzxcd_ResetInterval]); window_size = EndGetI32(&data[lzxcd_WindowSize]); break; case 2: reset_interval = EndGetI32(&data[lzxcd_ResetInterval]) * LZX_FRAME_SIZE; window_size = EndGetI32(&data[lzxcd_WindowSize]) * LZX_FRAME_SIZE; break; default: D(("bad controldata version")) sys->free(data); return self->error = MSPACK_ERR_DATAFORMAT; } /* free ControlData */ sys->free(data); /* find window_bits from window_size */ switch (window_size) { case 0x008000: window_bits = 15; break; case 0x010000: window_bits = 16; break; case 0x020000: window_bits = 17; break; case 0x040000: window_bits = 18; break; case 0x080000: window_bits = 19; break; case 0x100000: window_bits = 20; break; case 0x200000: window_bits = 21; break; default: D(("bad controldata window size")) return self->error = MSPACK_ERR_DATAFORMAT; } /* validate reset_interval */ if (reset_interval == 0 || reset_interval % LZX_FRAME_SIZE) { D(("bad controldata reset interval")) return self->error = MSPACK_ERR_DATAFORMAT; } /* which reset table entry would we like? */ entry = file->offset / reset_interval; /* convert from reset interval multiple (usually 64k) to 32k frames */ entry *= reset_interval / LZX_FRAME_SIZE; /* read the reset table entry */ if (read_reset_table(self, sec, entry, &length, &offset)) { /* the uncompressed length given in the reset table is dishonest. * the uncompressed data is always padded out from the given * uncompressed length up to the next reset interval */ length += reset_interval - 1; length &= -reset_interval; } else { /* if we can't read the reset table entry, just start from * the beginning. Use spaninfo to get the uncompressed length */ entry = 0; offset = 0; err = read_spaninfo(self, sec, &length); } if (err) return self->error = err; /* get offset of compressed data stream: * = offset of uncompressed section from start of file * + offset of compressed stream from start of uncompressed section * + offset of chosen reset interval from start of compressed stream */ self->d->inoffset = file->section->chm->sec0.offset + sec->content->offset + offset; /* set start offset and overall remaining stream length */ self->d->offset = entry * LZX_FRAME_SIZE; length -= self->d->offset; /* initialise LZX stream */ self->d->state = lzxd_init(&self->d->sys, self->d->infh, (struct mspack_file *) self, window_bits, reset_interval / LZX_FRAME_SIZE, 4096, length, 0); if (!self->d->state) self->error = MSPACK_ERR_NOMEMORY; return self->error; } /*************************************** * READ_RESET_TABLE *************************************** * Reads one entry out of the reset table. Also reads the uncompressed * data length. Writes these to offset_ptr and length_ptr respectively. * Returns non-zero for success, zero for failure. */ static int read_reset_table(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, int entry, off_t *length_ptr, off_t *offset_ptr) { struct mspack_system *sys = self->system; unsigned char *data; unsigned int pos, entrysize; /* do we have a ResetTable file? */ int err = find_sys_file(self, sec, &sec->rtable, rtable_name); if (err) return 0; /* read ResetTable file */ if (sec->rtable->length < lzxrt_headerSIZEOF) { D(("ResetTable file is too short")) return 0; } if (!(data = read_sys_file(self, sec->rtable))) { D(("can't read reset table")) return 0; } /* check sanity of reset table */ if (EndGetI32(&data[lzxrt_FrameLen]) != LZX_FRAME_SIZE) { D(("bad reset table frame length")) sys->free(data); return 0; } /* get the uncompressed length of the LZX stream */ if (read_off64(length_ptr, &data[lzxrt_UncompLen], sys, self->d->infh)) { sys->free(data); return 0; } entrysize = EndGetI32(&data[lzxrt_EntrySize]); pos = EndGetI32(&data[lzxrt_TableOffset]) + (entry * entrysize); /* ensure reset table entry for this offset exists */ if (entry < EndGetI32(&data[lzxrt_NumEntries]) && pos <= (sec->rtable->length - entrysize)) { switch (entrysize) { case 4: *offset_ptr = EndGetI32(&data[pos]); err = 0; break; case 8: err = read_off64(offset_ptr, &data[pos], sys, self->d->infh); break; default: D(("reset table entry size neither 4 nor 8")) err = 1; break; } } else { D(("bad reset interval")) err = 1; } /* free the reset table */ sys->free(data); /* return success */ return (err == 0); } /*************************************** * READ_SPANINFO *************************************** * Reads the uncompressed data length from the spaninfo file. * Returns zero for success or a non-zero error code for failure. */ static int read_spaninfo(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, off_t *length_ptr) { struct mspack_system *sys = self->system; unsigned char *data; /* find SpanInfo file */ int err = find_sys_file(self, sec, &sec->spaninfo, spaninfo_name); if (err) return MSPACK_ERR_DATAFORMAT; /* check it's large enough */ if (sec->spaninfo->length != 8) { D(("SpanInfo file is wrong size")) return MSPACK_ERR_DATAFORMAT; } /* read the SpanInfo file */ if (!(data = read_sys_file(self, sec->spaninfo))) { D(("can't read SpanInfo file")) return self->error; } /* get the uncompressed length of the LZX stream */ err = read_off64(length_ptr, data, sys, self->d->infh); sys->free(data); if (err) return MSPACK_ERR_DATAFORMAT; if (*length_ptr <= 0) { D(("output length is invalid")) return MSPACK_ERR_DATAFORMAT; } return MSPACK_ERR_OK; } /*************************************** * FIND_SYS_FILE *************************************** * Uses chmd_fast_find to locate a system file, and fills out that system * file's entry and links it into the list of system files. Returns zero * for success, non-zero for both failure and the file not existing. */ static int find_sys_file(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, struct mschmd_file **f_ptr, const char *name) { struct mspack_system *sys = self->system; struct mschmd_file result; /* already loaded */ if (*f_ptr) return MSPACK_ERR_OK; /* try using fast_find to find the file - return DATAFORMAT error if * it fails, or successfully doesn't find the file */ if (chmd_fast_find((struct mschm_decompressor *) self, sec->base.chm, name, &result, (int)sizeof(result)) || !result.section) { return MSPACK_ERR_DATAFORMAT; } if (!(*f_ptr = (struct mschmd_file *) sys->alloc(sys, sizeof(result)))) { return MSPACK_ERR_NOMEMORY; } /* copy result */ *(*f_ptr) = result; (*f_ptr)->filename = (char *) name; /* link file into sysfiles list */ (*f_ptr)->next = sec->base.chm->sysfiles; sec->base.chm->sysfiles = *f_ptr; return MSPACK_ERR_OK; } /*************************************** * READ_SYS_FILE *************************************** * Allocates memory for a section 0 (uncompressed) file and reads it into * memory. */ static unsigned char *read_sys_file(struct mschm_decompressor_p *self, struct mschmd_file *file) { struct mspack_system *sys = self->system; unsigned char *data = NULL; int len; if (!file || !file->section || (file->section->id != 0)) { self->error = MSPACK_ERR_DATAFORMAT; return NULL; } len = (int) file->length; if (!(data = (unsigned char *) sys->alloc(sys, (size_t) len))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } if (sys->seek(self->d->infh, file->section->chm->sec0.offset + file->offset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; sys->free(data); return NULL; } if (sys->read(self->d->infh, data, len) != len) { self->error = MSPACK_ERR_READ; sys->free(data); return NULL; } return data; } /*************************************** * CHMD_ERROR *************************************** * returns the last error that occurred */ static int chmd_error(struct mschm_decompressor *base) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; return (self) ? self->error : MSPACK_ERR_ARGS; } /*************************************** * READ_OFF64 *************************************** * Reads a 64-bit signed integer from memory in Intel byte order. * If running on a system with a 64-bit off_t, this is simply done. * If running on a system with a 32-bit off_t, offsets up to 0x7FFFFFFF * are accepted, offsets beyond that cause an error message. */ static int read_off64(off_t *var, unsigned char *mem, struct mspack_system *sys, struct mspack_file *fh) { #ifdef LARGEFILE_SUPPORT *var = EndGetI64(mem); #else *var = EndGetI32(mem); if ((*var & 0x80000000) || EndGetI32(mem+4)) { sys->message(fh, (char *)largefile_msg); return 1; } #endif return 0; }
./CrossVul/dataset_final_sorted/CWE-682/c/good_276_1
crossvul-cpp_data_bad_278_1
/* This file is part of libmspack. * (C) 2003-2011 Stuart Caie. * * libmspack is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License (LGPL) version 2.1 * * For further details, see the file COPYING.LIB distributed with libmspack */ /* CHM decompression implementation */ #include <system.h> #include <chm.h> /* prototypes */ static struct mschmd_header * chmd_open( struct mschm_decompressor *base, const char *filename); static struct mschmd_header * chmd_fast_open( struct mschm_decompressor *base, const char *filename); static struct mschmd_header *chmd_real_open( struct mschm_decompressor *base, const char *filename, int entire); static void chmd_close( struct mschm_decompressor *base, struct mschmd_header *chm); static int chmd_read_headers( struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire); static int chmd_fast_find( struct mschm_decompressor *base, struct mschmd_header *chm, const char *filename, struct mschmd_file *f_ptr, int f_size); static unsigned char *read_chunk( struct mschm_decompressor_p *self, struct mschmd_header *chm, struct mspack_file *fh, unsigned int chunk); static int search_chunk( struct mschmd_header *chm, const unsigned char *chunk, const char *filename, const unsigned char **result, const unsigned char **result_end); static inline int compare( const char *s1, const char *s2, int l1, int l2); static int chmd_extract( struct mschm_decompressor *base, struct mschmd_file *file, const char *filename); static int chmd_sys_write( struct mspack_file *file, void *buffer, int bytes); static int chmd_init_decomp( struct mschm_decompressor_p *self, struct mschmd_file *file); static int read_reset_table( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, int entry, off_t *length_ptr, off_t *offset_ptr); static int read_spaninfo( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, off_t *length_ptr); static int find_sys_file( struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, struct mschmd_file **f_ptr, const char *name); static unsigned char *read_sys_file( struct mschm_decompressor_p *self, struct mschmd_file *file); static int chmd_error( struct mschm_decompressor *base); static int read_off64( off_t *var, unsigned char *mem, struct mspack_system *sys, struct mspack_file *fh); /* filenames of the system files used for decompression. * Content and ControlData are essential. * ResetTable is preferred, but SpanInfo can be used if not available */ static const char *content_name = "::DataSpace/Storage/MSCompressed/Content"; static const char *control_name = "::DataSpace/Storage/MSCompressed/ControlData"; static const char *spaninfo_name = "::DataSpace/Storage/MSCompressed/SpanInfo"; static const char *rtable_name = "::DataSpace/Storage/MSCompressed/Transform/" "{7FC28940-9D31-11D0-9B27-00A0C91E9C7C}/InstanceData/ResetTable"; /*************************************** * MSPACK_CREATE_CHM_DECOMPRESSOR *************************************** * constructor */ struct mschm_decompressor * mspack_create_chm_decompressor(struct mspack_system *sys) { struct mschm_decompressor_p *self = NULL; if (!sys) sys = mspack_default_system; if (!mspack_valid_system(sys)) return NULL; if ((self = (struct mschm_decompressor_p *) sys->alloc(sys, sizeof(struct mschm_decompressor_p)))) { self->base.open = &chmd_open; self->base.close = &chmd_close; self->base.extract = &chmd_extract; self->base.last_error = &chmd_error; self->base.fast_open = &chmd_fast_open; self->base.fast_find = &chmd_fast_find; self->system = sys; self->error = MSPACK_ERR_OK; self->d = NULL; } return (struct mschm_decompressor *) self; } /*************************************** * MSPACK_DESTROY_CAB_DECOMPRESSOR *************************************** * destructor */ void mspack_destroy_chm_decompressor(struct mschm_decompressor *base) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; if (self) { struct mspack_system *sys = self->system; if (self->d) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); sys->free(self->d); } sys->free(self); } } /*************************************** * CHMD_OPEN *************************************** * opens a file and tries to read it as a CHM file. * Calls chmd_real_open() with entire=1. */ static struct mschmd_header *chmd_open(struct mschm_decompressor *base, const char *filename) { return chmd_real_open(base, filename, 1); } /*************************************** * CHMD_FAST_OPEN *************************************** * opens a file and tries to read it as a CHM file, but does not read * the file headers. Calls chmd_real_open() with entire=0 */ static struct mschmd_header *chmd_fast_open(struct mschm_decompressor *base, const char *filename) { return chmd_real_open(base, filename, 0); } /*************************************** * CHMD_REAL_OPEN *************************************** * the real implementation of chmd_open() and chmd_fast_open(). It simply * passes the "entire" parameter to chmd_read_headers(), which will then * either read all headers, or a bare mininum. */ static struct mschmd_header *chmd_real_open(struct mschm_decompressor *base, const char *filename, int entire) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mschmd_header *chm = NULL; struct mspack_system *sys; struct mspack_file *fh; int error; if (!base) return NULL; sys = self->system; if ((fh = sys->open(sys, filename, MSPACK_SYS_OPEN_READ))) { if ((chm = (struct mschmd_header *) sys->alloc(sys, sizeof(struct mschmd_header)))) { chm->filename = filename; error = chmd_read_headers(sys, fh, chm, entire); if (error) { /* if the error is DATAFORMAT, and there are some results, return * partial results with a warning, rather than nothing */ if (error == MSPACK_ERR_DATAFORMAT && (chm->files || chm->sysfiles)) { sys->message(fh, "WARNING; contents are corrupt"); error = MSPACK_ERR_OK; } else { chmd_close(base, chm); chm = NULL; } } self->error = error; } else { self->error = MSPACK_ERR_NOMEMORY; } sys->close(fh); } else { self->error = MSPACK_ERR_OPEN; } return chm; } /*************************************** * CHMD_CLOSE *************************************** * frees all memory associated with a given mschmd_header */ static void chmd_close(struct mschm_decompressor *base, struct mschmd_header *chm) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mschmd_file *fi, *nfi; struct mspack_system *sys; unsigned int i; if (!base) return; sys = self->system; self->error = MSPACK_ERR_OK; /* free files */ for (fi = chm->files; fi; fi = nfi) { nfi = fi->next; sys->free(fi); } for (fi = chm->sysfiles; fi; fi = nfi) { nfi = fi->next; sys->free(fi); } /* if this CHM was being decompressed, free decompression state */ if (self->d && (self->d->chm == chm)) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); sys->free(self->d); self->d = NULL; } /* if this CHM had a chunk cache, free it and contents */ if (chm->chunk_cache) { for (i = 0; i < chm->num_chunks; i++) sys->free(chm->chunk_cache[i]); sys->free(chm->chunk_cache); } sys->free(chm); } /*************************************** * CHMD_READ_HEADERS *************************************** * reads the basic CHM file headers. If the "entire" parameter is * non-zero, all file entries will also be read. fills out a pre-existing * mschmd_header structure, allocates memory for files as necessary */ /* The GUIDs found in CHM headers */ static const unsigned char guids[32] = { /* {7C01FD10-7BAA-11D0-9E0C-00A0-C922-E6EC} */ 0x10, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11, 0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC, /* {7C01FD11-7BAA-11D0-9E0C-00A0-C922-E6EC} */ 0x11, 0xFD, 0x01, 0x7C, 0xAA, 0x7B, 0xD0, 0x11, 0x9E, 0x0C, 0x00, 0xA0, 0xC9, 0x22, 0xE6, 0xEC }; /* reads an encoded integer into a variable; 7 bits of data per byte, * the high bit is used to indicate that there is another byte */ #define READ_ENCINT(var) do { \ (var) = 0; \ do { \ if (p >= end) goto chunk_end; \ (var) = ((var) << 7) | (*p & 0x7F); \ } while (*p++ & 0x80); \ } while (0) static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh, struct mschmd_header *chm, int entire) { unsigned int section, name_len, x, errors, num_chunks; unsigned char buf[0x54], *chunk = NULL, *name, *p, *end; struct mschmd_file *fi, *link = NULL; off_t offset, length; int num_entries; /* initialise pointers */ chm->files = NULL; chm->sysfiles = NULL; chm->chunk_cache = NULL; chm->sec0.base.chm = chm; chm->sec0.base.id = 0; chm->sec1.base.chm = chm; chm->sec1.base.id = 1; chm->sec1.content = NULL; chm->sec1.control = NULL; chm->sec1.spaninfo = NULL; chm->sec1.rtable = NULL; /* read the first header */ if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) { return MSPACK_ERR_READ; } /* check ITSF signature */ if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) { return MSPACK_ERR_SIGNATURE; } /* check both header GUIDs */ if (mspack_memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) { D(("incorrect GUIDs")) return MSPACK_ERR_SIGNATURE; } chm->version = EndGetI32(&buf[chmhead_Version]); chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]); chm->language = EndGetI32(&buf[chmhead_LanguageID]); if (chm->version > 3) { sys->message(fh, "WARNING; CHM version > 3"); } /* read the header section table */ if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) { return MSPACK_ERR_READ; } /* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files. * The offset will be corrected later, once HS1 is read. */ if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) || read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) || read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 0 */ if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 0 */ if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) { return MSPACK_ERR_READ; } if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) { return MSPACK_ERR_DATAFORMAT; } /* seek to header section 1 */ if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) { return MSPACK_ERR_SEEK; } /* read header section 1 */ if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) { return MSPACK_ERR_READ; } chm->dir_offset = sys->tell(fh); chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]); chm->density = EndGetI32(&buf[chmhs1_Density]); chm->depth = EndGetI32(&buf[chmhs1_Depth]); chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]); chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]); chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]); chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]); if (chm->version < 3) { /* versions before 3 don't have chmhst3_OffsetCS0 */ chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks); } /* check if content offset or file size is wrong */ if (chm->sec0.offset > chm->length) { D(("content section begins after file has ended")) return MSPACK_ERR_DATAFORMAT; } /* ensure there are chunks and that chunk size is * large enough for signature and num_entries */ if (chm->chunk_size < (pmgl_Entries + 2)) { D(("chunk size not large enough")) return MSPACK_ERR_DATAFORMAT; } if (chm->num_chunks == 0) { D(("no chunks")) return MSPACK_ERR_DATAFORMAT; } /* The chunk_cache data structure is not great; large values for num_chunks * or num_chunks*chunk_size can exhaust all memory. Until a better chunk * cache is implemented, put arbitrary limits on num_chunks and chunk size. */ if (chm->num_chunks > 100000) { D(("more than 100,000 chunks")) return MSPACK_ERR_DATAFORMAT; } if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) { D(("chunks larger than entire file")) return MSPACK_ERR_DATAFORMAT; } /* common sense checks on header section 1 fields */ if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) { sys->message(fh, "WARNING; chunk size is not a power of two"); } if (chm->first_pmgl != 0) { sys->message(fh, "WARNING; first PMGL chunk is not zero"); } if (chm->first_pmgl > chm->last_pmgl) { D(("first pmgl chunk is after last pmgl chunk")) return MSPACK_ERR_DATAFORMAT; } if (chm->index_root != 0xFFFFFFFF && chm->index_root > chm->num_chunks) { D(("index_root outside valid range")) return MSPACK_ERR_DATAFORMAT; } /* if we are doing a quick read, stop here! */ if (!entire) { return MSPACK_ERR_OK; } /* seek to the first PMGL chunk, and reduce the number of chunks to read */ if ((x = chm->first_pmgl) != 0) { if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) { return MSPACK_ERR_SEEK; } } num_chunks = chm->last_pmgl - x + 1; if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) { return MSPACK_ERR_NOMEMORY; } /* read and process all chunks from FirstPMGL to LastPMGL */ errors = 0; while (num_chunks--) { /* read next chunk */ if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) { sys->free(chunk); return MSPACK_ERR_READ; } /* process only directory (PMGL) chunks */ if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue; if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) { sys->message(fh, "WARNING; PMGL quickref area is too small"); } if (EndGetI32(&chunk[pmgl_QuickRefSize]) > ((int)chm->chunk_size - pmgl_Entries)) { sys->message(fh, "WARNING; PMGL quickref area is too large"); } p = &chunk[pmgl_Entries]; end = &chunk[chm->chunk_size - 2]; num_entries = EndGetI16(end); while (num_entries--) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; name = p; p += name_len; READ_ENCINT(section); READ_ENCINT(offset); READ_ENCINT(length); /* empty files and directory names are stored as a file entry at * offset 0 with length 0. We want to keep empty files, but not * directory names, which end with a "/" */ if ((offset == 0) && (length == 0)) { if ((name_len > 0) && (name[name_len-1] == '/')) continue; } if (section > 1) { sys->message(fh, "invalid section number '%u'.", section); continue; } if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) { sys->free(chunk); return MSPACK_ERR_NOMEMORY; } fi->next = NULL; fi->filename = (char *) &fi[1]; fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0) : (struct mschmd_section *) (&chm->sec1)); fi->offset = offset; fi->length = length; sys->copy(name, fi->filename, (size_t) name_len); fi->filename[name_len] = '\0'; if (name[0] == ':' && name[1] == ':') { /* system file */ if (mspack_memcmp(&name[2], &content_name[2], 31L) == 0) { if (mspack_memcmp(&name[33], &content_name[33], 8L) == 0) { chm->sec1.content = fi; } else if (mspack_memcmp(&name[33], &control_name[33], 11L) == 0) { chm->sec1.control = fi; } else if (mspack_memcmp(&name[33], &spaninfo_name[33], 8L) == 0) { chm->sec1.spaninfo = fi; } else if (mspack_memcmp(&name[33], &rtable_name[33], 72L) == 0) { chm->sec1.rtable = fi; } } fi->next = chm->sysfiles; chm->sysfiles = fi; } else { /* normal file */ if (link) link->next = fi; else chm->files = fi; link = fi; } } /* this is reached either when num_entries runs out, or if * reading data from the chunk reached a premature end of chunk */ chunk_end: if (num_entries >= 0) { D(("chunk ended before all entries could be read")) errors++; } } sys->free(chunk); return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK; } /*************************************** * CHMD_FAST_FIND *************************************** * uses PMGI index chunks and quickref data to quickly locate a file * directly from the on-disk index. * * TODO: protect against infinite loops in chunks (where pgml_NextChunk * or a PGMI index entry point to an already visited chunk) */ static int chmd_fast_find(struct mschm_decompressor *base, struct mschmd_header *chm, const char *filename, struct mschmd_file *f_ptr, int f_size) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mspack_system *sys; struct mspack_file *fh; const unsigned char *chunk, *p, *end; int err = MSPACK_ERR_OK, result = -1; unsigned int n, sec; if (!self || !chm || !f_ptr || (f_size != sizeof(struct mschmd_file))) { return MSPACK_ERR_ARGS; } sys = self->system; /* clear the results structure */ memset(f_ptr, 0, f_size); if (!(fh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ))) { return MSPACK_ERR_OPEN; } /* go through PMGI chunk hierarchy to reach PMGL chunk */ if (chm->index_root < chm->num_chunks) { n = chm->index_root; for (;;) { if (!(chunk = read_chunk(self, chm, fh, n))) { sys->close(fh); return self->error; } /* search PMGI/PMGL chunk. exit early if no entry found */ if ((result = search_chunk(chm, chunk, filename, &p, &end)) <= 0) { break; } /* found result. loop around for next chunk if this is PMGI */ if (chunk[3] == 0x4C) break; else READ_ENCINT(n); } } else { /* PMGL chunks only, search from first_pmgl to last_pmgl */ for (n = chm->first_pmgl; n <= chm->last_pmgl; n = EndGetI32(&chunk[pmgl_NextChunk])) { if (!(chunk = read_chunk(self, chm, fh, n))) { err = self->error; break; } /* search PMGL chunk. exit if file found */ if ((result = search_chunk(chm, chunk, filename, &p, &end)) > 0) { break; } /* stop simple infinite loops: can't visit the same chunk twice */ if ((int)n == EndGetI32(&chunk[pmgl_NextChunk])) { break; } } } /* if we found a file, read it */ if (result > 0) { READ_ENCINT(sec); f_ptr->section = (sec == 0) ? (struct mschmd_section *) &chm->sec0 : (struct mschmd_section *) &chm->sec1; READ_ENCINT(f_ptr->offset); READ_ENCINT(f_ptr->length); } else if (result < 0) { err = MSPACK_ERR_DATAFORMAT; } sys->close(fh); return self->error = err; chunk_end: D(("read beyond end of chunk entries")) sys->close(fh); return self->error = MSPACK_ERR_DATAFORMAT; } /* reads the given chunk into memory, storing it in a chunk cache * so it doesn't need to be read from disk more than once */ static unsigned char *read_chunk(struct mschm_decompressor_p *self, struct mschmd_header *chm, struct mspack_file *fh, unsigned int chunk_num) { struct mspack_system *sys = self->system; unsigned char *buf; /* check arguments - most are already checked by chmd_fast_find */ if (chunk_num > chm->num_chunks) return NULL; /* ensure chunk cache is available */ if (!chm->chunk_cache) { size_t size = sizeof(unsigned char *) * chm->num_chunks; if (!(chm->chunk_cache = (unsigned char **) sys->alloc(sys, size))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } memset(chm->chunk_cache, 0, size); } /* try to answer out of chunk cache */ if (chm->chunk_cache[chunk_num]) return chm->chunk_cache[chunk_num]; /* need to read chunk - allocate memory for it */ if (!(buf = (unsigned char *) sys->alloc(sys, chm->chunk_size))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } /* seek to block and read it */ if (sys->seek(fh, (off_t) (chm->dir_offset + (chunk_num * chm->chunk_size)), MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; sys->free(buf); return NULL; } if (sys->read(fh, buf, (int)chm->chunk_size) != (int)chm->chunk_size) { self->error = MSPACK_ERR_READ; sys->free(buf); return NULL; } /* check the signature. Is is PMGL or PMGI? */ if (!((buf[0] == 0x50) && (buf[1] == 0x4D) && (buf[2] == 0x47) && ((buf[3] == 0x4C) || (buf[3] == 0x49)))) { self->error = MSPACK_ERR_SEEK; sys->free(buf); return NULL; } /* all OK. Store chunk in cache and return it */ return chm->chunk_cache[chunk_num] = buf; } /* searches a PMGI/PMGL chunk for a given filename entry. Returns -1 on * data format error, 0 if entry definitely not found, 1 if entry * found. In the latter case, *result and *result_end are set pointing * to that entry's data (either the "next chunk" ENCINT for a PMGI or * the section, offset and length ENCINTs for a PMGL). * * In the case of PMGL chunks, the entry has definitely been * found. In the case of PMGI chunks, the entry which points to the * chunk that may eventually contain that entry has been found. */ static int search_chunk(struct mschmd_header *chm, const unsigned char *chunk, const char *filename, const unsigned char **result, const unsigned char **result_end) { const unsigned char *start, *end, *p; unsigned int qr_size, num_entries, qr_entries, qr_density, name_len; unsigned int L, R, M, fname_len, entries_off, is_pmgl; int cmp; fname_len = strlen(filename); /* PMGL chunk or PMGI chunk? (note: read_chunk() has already * checked the rest of the characters in the chunk signature) */ if (chunk[3] == 0x4C) { is_pmgl = 1; entries_off = pmgl_Entries; } else { is_pmgl = 0; entries_off = pmgi_Entries; } /* Step 1: binary search first filename of each QR entry * - target filename == entry * found file * - target filename < all entries * file not found * - target filename > all entries * proceed to step 2 using final entry * - target filename between two searched entries * proceed to step 2 */ qr_size = EndGetI32(&chunk[pmgl_QuickRefSize]); start = &chunk[chm->chunk_size - 2]; end = &chunk[chm->chunk_size - qr_size]; num_entries = EndGetI16(start); qr_density = 1 + (1 << chm->density); qr_entries = (num_entries + qr_density-1) / qr_density; if (num_entries == 0) { D(("chunk has no entries")) return -1; } if (qr_size > chm->chunk_size) { D(("quickref size > chunk size")) return -1; } *result_end = end; if (((int)qr_entries * 2) > (start - end)) { D(("WARNING; more quickrefs than quickref space")) qr_entries = 0; /* but we can live with it */ } if (qr_entries > 0) { L = 0; R = qr_entries - 1; do { /* pick new midpoint */ M = (L + R) >> 1; /* compare filename with entry QR points to */ p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)]; READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; cmp = compare(filename, (char *)p, fname_len, name_len); if (cmp == 0) break; else if (cmp < 0) { if (M) R = M - 1; else return 0; } else if (cmp > 0) L = M + 1; } while (L <= R); M = (L + R) >> 1; if (cmp == 0) { /* exact match! */ p += name_len; *result = p; return 1; } /* otherwise, read the group of entries for QR entry M */ p = &chunk[entries_off + (M ? EndGetI16(start - (M << 1)) : 0)]; num_entries -= (M * qr_density); if (num_entries > qr_density) num_entries = qr_density; } else { p = &chunk[entries_off]; } /* Step 2: linear search through the set of entries reached in step 1. * - filename == any entry * found entry * - filename < all entries (PMGI) or any entry (PMGL) * entry not found, stop now * - filename > all entries * entry not found (PMGL) / maybe found (PMGI) * - */ *result = NULL; while (num_entries-- > 0) { READ_ENCINT(name_len); if (name_len > (unsigned int) (end - p)) goto chunk_end; cmp = compare(filename, (char *)p, fname_len, name_len); p += name_len; if (cmp == 0) { /* entry found */ *result = p; return 1; } if (cmp < 0) { /* entry not found (PMGL) / maybe found (PMGI) */ break; } /* read and ignore the rest of this entry */ if (is_pmgl) { READ_ENCINT(R); /* skip section */ READ_ENCINT(R); /* skip offset */ READ_ENCINT(R); /* skip length */ } else { *result = p; /* store potential final result */ READ_ENCINT(R); /* skip chunk number */ } } /* PMGL? not found. PMGI? maybe found */ return (is_pmgl) ? 0 : (*result ? 1 : 0); chunk_end: D(("reached end of chunk data while searching")) return -1; } #if HAVE_TOWLOWER # if HAVE_WCTYPE_H # include <wctype.h> # endif # define TOLOWER(x) towlower(x) #elif HAVE_TOLOWER # if HAVE_CTYPE_H # include <ctype.h> # endif # define TOLOWER(x) tolower(x) #else # define TOLOWER(x) (((x)<0||(x)>256)?(x):mspack_tolower_map[(x)]) /* Map of char -> lowercase char for the first 256 chars. Generated with: * LC_CTYPE=en_GB.utf-8 perl -Mlocale -le 'print map{ord(lc chr).","} 0..255' */ static const unsigned char mspack_tolower_map[256] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, 28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52, 53,54,55,56,57,58,59,60,61,62,63,64,97,98,99,100,101,102,103,104,105,106, 107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,91,92,93,94, 95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114, 115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133, 134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152, 153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171, 172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190, 191,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241, 242,243,244,245,246,215,248,249,250,251,252,253,254,223,224,225,226,227,228, 229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247, 248,249,250,251,252,253,254,255 }; #endif /* decodes a UTF-8 character from s[] into c. Will not read past e. * doesn't test that extension bytes are %10xxxxxx. * allows some overlong encodings. */ #define GET_UTF8_CHAR(s, e, c) do { \ unsigned char x = *s++; \ if (x < 0x80) c = x; \ else if (x >= 0xC2 && x < 0xE0 && s < e) { \ c = (x & 0x1F) << 6 | (*s++ & 0x3F); \ } \ else if (x >= 0xE0 && x < 0xF0 && s+1 < e) { \ c = (x & 0x0F) << 12 | (s[0] & 0x3F) << 6 | (s[1] & 0x3F); \ s += 2; \ } \ else if (x >= 0xF0 && x <= 0xF5 && s+2 < e) { \ c = (x & 0x07) << 18 | (s[0] & 0x3F) << 12 | \ (s[1] & 0x3F) << 6 | (s[2] & 0x3F); \ if (c > 0x10FFFF) c = 0xFFFD; \ s += 3; \ } \ else c = 0xFFFD; \ } while (0) /* case-insensitively compares two UTF8 encoded strings. String length for * both strings must be provided, null bytes are not terminators */ static inline int compare(const char *s1, const char *s2, int l1, int l2) { register const unsigned char *p1 = (const unsigned char *) s1; register const unsigned char *p2 = (const unsigned char *) s2; register const unsigned char *e1 = p1 + l1, *e2 = p2 + l2; int c1, c2; while (p1 < e1 && p2 < e2) { GET_UTF8_CHAR(p1, e1, c1); GET_UTF8_CHAR(p2, e2, c2); if (c1 == c2) continue; c1 = TOLOWER(c1); c2 = TOLOWER(c2); if (c1 != c2) return c1 - c2; } return l1 - l2; } /*************************************** * CHMD_EXTRACT *************************************** * extracts a file from a CHM helpfile */ static int chmd_extract(struct mschm_decompressor *base, struct mschmd_file *file, const char *filename) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; struct mspack_system *sys; struct mschmd_header *chm; struct mspack_file *fh; off_t bytes; if (!self) return MSPACK_ERR_ARGS; if (!file || !file->section) return self->error = MSPACK_ERR_ARGS; sys = self->system; chm = file->section->chm; /* create decompression state if it doesn't exist */ if (!self->d) { self->d = (struct mschmd_decompress_state *) sys->alloc(sys, sizeof(struct mschmd_decompress_state)); if (!self->d) return self->error = MSPACK_ERR_NOMEMORY; self->d->chm = chm; self->d->offset = 0; self->d->state = NULL; self->d->sys = *sys; self->d->sys.write = &chmd_sys_write; self->d->infh = NULL; self->d->outfh = NULL; } /* open input chm file if not open, or the open one is a different chm */ if (!self->d->infh || (self->d->chm != chm)) { if (self->d->infh) sys->close(self->d->infh); if (self->d->state) lzxd_free(self->d->state); self->d->chm = chm; self->d->offset = 0; self->d->state = NULL; self->d->infh = sys->open(sys, chm->filename, MSPACK_SYS_OPEN_READ); if (!self->d->infh) return self->error = MSPACK_ERR_OPEN; } /* open file for output */ if (!(fh = sys->open(sys, filename, MSPACK_SYS_OPEN_WRITE))) { return self->error = MSPACK_ERR_OPEN; } /* if file is empty, simply creating it is enough */ if (!file->length) { sys->close(fh); return self->error = MSPACK_ERR_OK; } self->error = MSPACK_ERR_OK; switch (file->section->id) { case 0: /* Uncompressed section file */ /* simple seek + copy */ if (sys->seek(self->d->infh, file->section->chm->sec0.offset + file->offset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; } else { unsigned char buf[512]; off_t length = file->length; while (length > 0) { int run = sizeof(buf); if ((off_t)run > length) run = (int)length; if (sys->read(self->d->infh, &buf[0], run) != run) { self->error = MSPACK_ERR_READ; break; } if (sys->write(fh, &buf[0], run) != run) { self->error = MSPACK_ERR_WRITE; break; } length -= run; } } break; case 1: /* MSCompressed section file */ /* (re)initialise compression state if we it is not yet initialised, * or we have advanced too far and have to backtrack */ if (!self->d->state || (file->offset < self->d->offset)) { if (self->d->state) { lzxd_free(self->d->state); self->d->state = NULL; } if (chmd_init_decomp(self, file)) break; } /* seek to input data */ if (sys->seek(self->d->infh, self->d->inoffset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; break; } /* get to correct offset. */ self->d->outfh = NULL; if ((bytes = file->offset - self->d->offset)) { self->error = lzxd_decompress(self->d->state, bytes); } /* if getting to the correct offset was error free, unpack file */ if (!self->error) { self->d->outfh = fh; self->error = lzxd_decompress(self->d->state, file->length); } /* save offset in input source stream, in case there is a section 0 * file between now and the next section 1 file extracted */ self->d->inoffset = sys->tell(self->d->infh); /* if an LZX error occured, the LZX decompressor is now useless */ if (self->error) { if (self->d->state) lzxd_free(self->d->state); self->d->state = NULL; } break; } sys->close(fh); return self->error; } /*************************************** * CHMD_SYS_WRITE *************************************** * chmd_sys_write is the internal writer function which the decompressor * uses. If either writes data to disk (self->d->outfh) with the real * sys->write() function, or does nothing with the data when * self->d->outfh == NULL. advances self->d->offset. */ static int chmd_sys_write(struct mspack_file *file, void *buffer, int bytes) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) file; self->d->offset += bytes; if (self->d->outfh) { return self->system->write(self->d->outfh, buffer, bytes); } return bytes; } /*************************************** * CHMD_INIT_DECOMP *************************************** * Initialises the LZX decompressor to decompress the compressed stream, * from the nearest reset offset and length that is needed for the given * file. */ static int chmd_init_decomp(struct mschm_decompressor_p *self, struct mschmd_file *file) { int window_size, window_bits, reset_interval, entry, err; struct mspack_system *sys = self->system; struct mschmd_sec_mscompressed *sec; unsigned char *data; off_t length, offset; sec = (struct mschmd_sec_mscompressed *) file->section; /* ensure we have a mscompressed content section */ err = find_sys_file(self, sec, &sec->content, content_name); if (err) return self->error = err; /* ensure we have a ControlData file */ err = find_sys_file(self, sec, &sec->control, control_name); if (err) return self->error = err; /* read ControlData */ if (sec->control->length < lzxcd_SIZEOF) { D(("ControlData file is too short")) return self->error = MSPACK_ERR_DATAFORMAT; } if (!(data = read_sys_file(self, sec->control))) { D(("can't read mscompressed control data file")) return self->error; } /* check LZXC signature */ if (EndGetI32(&data[lzxcd_Signature]) != 0x43585A4C) { sys->free(data); return self->error = MSPACK_ERR_SIGNATURE; } /* read reset_interval and window_size and validate version number */ switch (EndGetI32(&data[lzxcd_Version])) { case 1: reset_interval = EndGetI32(&data[lzxcd_ResetInterval]); window_size = EndGetI32(&data[lzxcd_WindowSize]); break; case 2: reset_interval = EndGetI32(&data[lzxcd_ResetInterval]) * LZX_FRAME_SIZE; window_size = EndGetI32(&data[lzxcd_WindowSize]) * LZX_FRAME_SIZE; break; default: D(("bad controldata version")) sys->free(data); return self->error = MSPACK_ERR_DATAFORMAT; } /* free ControlData */ sys->free(data); /* find window_bits from window_size */ switch (window_size) { case 0x008000: window_bits = 15; break; case 0x010000: window_bits = 16; break; case 0x020000: window_bits = 17; break; case 0x040000: window_bits = 18; break; case 0x080000: window_bits = 19; break; case 0x100000: window_bits = 20; break; case 0x200000: window_bits = 21; break; default: D(("bad controldata window size")) return self->error = MSPACK_ERR_DATAFORMAT; } /* validate reset_interval */ if (reset_interval == 0 || reset_interval % LZX_FRAME_SIZE) { D(("bad controldata reset interval")) return self->error = MSPACK_ERR_DATAFORMAT; } /* which reset table entry would we like? */ entry = file->offset / reset_interval; /* convert from reset interval multiple (usually 64k) to 32k frames */ entry *= reset_interval / LZX_FRAME_SIZE; /* read the reset table entry */ if (read_reset_table(self, sec, entry, &length, &offset)) { /* the uncompressed length given in the reset table is dishonest. * the uncompressed data is always padded out from the given * uncompressed length up to the next reset interval */ length += reset_interval - 1; length &= -reset_interval; } else { /* if we can't read the reset table entry, just start from * the beginning. Use spaninfo to get the uncompressed length */ entry = 0; offset = 0; err = read_spaninfo(self, sec, &length); } if (err) return self->error = err; /* get offset of compressed data stream: * = offset of uncompressed section from start of file * + offset of compressed stream from start of uncompressed section * + offset of chosen reset interval from start of compressed stream */ self->d->inoffset = file->section->chm->sec0.offset + sec->content->offset + offset; /* set start offset and overall remaining stream length */ self->d->offset = entry * LZX_FRAME_SIZE; length -= self->d->offset; /* initialise LZX stream */ self->d->state = lzxd_init(&self->d->sys, self->d->infh, (struct mspack_file *) self, window_bits, reset_interval / LZX_FRAME_SIZE, 4096, length, 0); if (!self->d->state) self->error = MSPACK_ERR_NOMEMORY; return self->error; } /*************************************** * READ_RESET_TABLE *************************************** * Reads one entry out of the reset table. Also reads the uncompressed * data length. Writes these to offset_ptr and length_ptr respectively. * Returns non-zero for success, zero for failure. */ static int read_reset_table(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, int entry, off_t *length_ptr, off_t *offset_ptr) { struct mspack_system *sys = self->system; unsigned char *data; unsigned int pos, entrysize; /* do we have a ResetTable file? */ int err = find_sys_file(self, sec, &sec->rtable, rtable_name); if (err) return 0; /* read ResetTable file */ if (sec->rtable->length < lzxrt_headerSIZEOF) { D(("ResetTable file is too short")) return 0; } if (!(data = read_sys_file(self, sec->rtable))) { D(("can't read reset table")) return 0; } /* check sanity of reset table */ if (EndGetI32(&data[lzxrt_FrameLen]) != LZX_FRAME_SIZE) { D(("bad reset table frame length")) sys->free(data); return 0; } /* get the uncompressed length of the LZX stream */ if (read_off64(length_ptr, &data[lzxrt_UncompLen], sys, self->d->infh)) { sys->free(data); return 0; } entrysize = EndGetI32(&data[lzxrt_EntrySize]); pos = EndGetI32(&data[lzxrt_TableOffset]) + (entry * entrysize); /* ensure reset table entry for this offset exists */ if (entry < EndGetI32(&data[lzxrt_NumEntries]) && pos <= (sec->rtable->length - entrysize)) { switch (entrysize) { case 4: *offset_ptr = EndGetI32(&data[pos]); err = 0; break; case 8: err = read_off64(offset_ptr, &data[pos], sys, self->d->infh); break; default: D(("reset table entry size neither 4 nor 8")) err = 1; break; } } else { D(("bad reset interval")) err = 1; } /* free the reset table */ sys->free(data); /* return success */ return (err == 0); } /*************************************** * READ_SPANINFO *************************************** * Reads the uncompressed data length from the spaninfo file. * Returns zero for success or a non-zero error code for failure. */ static int read_spaninfo(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, off_t *length_ptr) { struct mspack_system *sys = self->system; unsigned char *data; /* find SpanInfo file */ int err = find_sys_file(self, sec, &sec->spaninfo, spaninfo_name); if (err) return MSPACK_ERR_DATAFORMAT; /* check it's large enough */ if (sec->spaninfo->length != 8) { D(("SpanInfo file is wrong size")) return MSPACK_ERR_DATAFORMAT; } /* read the SpanInfo file */ if (!(data = read_sys_file(self, sec->spaninfo))) { D(("can't read SpanInfo file")) return self->error; } /* get the uncompressed length of the LZX stream */ err = read_off64(length_ptr, data, sys, self->d->infh); sys->free(data); if (err) return MSPACK_ERR_DATAFORMAT; if (*length_ptr <= 0) { D(("output length is invalid")) return MSPACK_ERR_DATAFORMAT; } return MSPACK_ERR_OK; } /*************************************** * FIND_SYS_FILE *************************************** * Uses chmd_fast_find to locate a system file, and fills out that system * file's entry and links it into the list of system files. Returns zero * for success, non-zero for both failure and the file not existing. */ static int find_sys_file(struct mschm_decompressor_p *self, struct mschmd_sec_mscompressed *sec, struct mschmd_file **f_ptr, const char *name) { struct mspack_system *sys = self->system; struct mschmd_file result; /* already loaded */ if (*f_ptr) return MSPACK_ERR_OK; /* try using fast_find to find the file - return DATAFORMAT error if * it fails, or successfully doesn't find the file */ if (chmd_fast_find((struct mschm_decompressor *) self, sec->base.chm, name, &result, (int)sizeof(result)) || !result.section) { return MSPACK_ERR_DATAFORMAT; } if (!(*f_ptr = (struct mschmd_file *) sys->alloc(sys, sizeof(result)))) { return MSPACK_ERR_NOMEMORY; } /* copy result */ *(*f_ptr) = result; (*f_ptr)->filename = (char *) name; /* link file into sysfiles list */ (*f_ptr)->next = sec->base.chm->sysfiles; sec->base.chm->sysfiles = *f_ptr; return MSPACK_ERR_OK; } /*************************************** * READ_SYS_FILE *************************************** * Allocates memory for a section 0 (uncompressed) file and reads it into * memory. */ static unsigned char *read_sys_file(struct mschm_decompressor_p *self, struct mschmd_file *file) { struct mspack_system *sys = self->system; unsigned char *data = NULL; int len; if (!file || !file->section || (file->section->id != 0)) { self->error = MSPACK_ERR_DATAFORMAT; return NULL; } len = (int) file->length; if (!(data = (unsigned char *) sys->alloc(sys, (size_t) len))) { self->error = MSPACK_ERR_NOMEMORY; return NULL; } if (sys->seek(self->d->infh, file->section->chm->sec0.offset + file->offset, MSPACK_SYS_SEEK_START)) { self->error = MSPACK_ERR_SEEK; sys->free(data); return NULL; } if (sys->read(self->d->infh, data, len) != len) { self->error = MSPACK_ERR_READ; sys->free(data); return NULL; } return data; } /*************************************** * CHMD_ERROR *************************************** * returns the last error that occurred */ static int chmd_error(struct mschm_decompressor *base) { struct mschm_decompressor_p *self = (struct mschm_decompressor_p *) base; return (self) ? self->error : MSPACK_ERR_ARGS; } /*************************************** * READ_OFF64 *************************************** * Reads a 64-bit signed integer from memory in Intel byte order. * If running on a system with a 64-bit off_t, this is simply done. * If running on a system with a 32-bit off_t, offsets up to 0x7FFFFFFF * are accepted, offsets beyond that cause an error message. */ static int read_off64(off_t *var, unsigned char *mem, struct mspack_system *sys, struct mspack_file *fh) { #ifdef LARGEFILE_SUPPORT *var = EndGetI64(mem); #else *var = EndGetI32(mem); if ((*var & 0x80000000) || EndGetI32(mem+4)) { sys->message(fh, (char *)largefile_msg); return 1; } #endif return 0; }
./CrossVul/dataset_final_sorted/CWE-682/c/bad_278_1